PageSourceSearch

https://energycompare.ai/assets/DashboardPage-CRe7InBH.js

js energycompare.ai collected 2026-10-05 12:13:25 UTC 3,418,086 bytes, 53 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/StepLeaseSummary-B7v0zP5O.js","assets/vendor-CMvvE79M.js","assets/pdf-Bf_FUwzp.js","assets/vendor-DeqiE6li.css","assets/index-CJhDLLQN.js","assets/index-CY59A6I7.css","assets/checkbox-f2Bkp6Dm.js","assets/collapsible-BYY0UvDl.js","assets/LeaseholdStepLayout-BP_CJ-eS.js","assets/scroll-area-DxnNy9Vx.js","assets/ModeToggle-BR7ekiJk.js","assets/StepLayout-Co5kgNkK.js","assets/AgencyQcPanel-vy24dqh2.js","assets/StepAgencyEligibility-Bly9mtpY.js","assets/StepCalculator-hHoP8msT.js","assets/tabs-CtFENyHp.js","assets/table-Dx2DCkzd.js","assets/alert-D7EgiqET.js","assets/StepRightsAdjustment-CGwrn6hP.js","assets/switch-60NKGYKO.js","assets/StepAddendumPreview-CKjd1bBk.js","assets/separator-C55a0Ko7.js","assets/alert-dialog-F1Xac2S4.js","assets/StrReportDataModal-C4svxdQm.js","assets/Uad36UrarPanel-DlJwoJrM.js","assets/label-B2udOYFm.js","assets/sheet-CW_ZFNUH.js","assets/uad36DraftBackup-Dg8NqaZa.js","assets/Uad36ValidationNoticeDialog-DWrw-Xoe.js","assets/DateField-CCwn-aIi.js","assets/popover-E1IVhB14.js","assets/sketch-CLNTnFNv.js","assets/uad36ImagePreprocess-5jaGBucA.js","assets/cardinality-CoXArXef.js","assets/mapboxToken-BBXATyou.js","assets/maps-CuvAq4kb.js","assets/maps-C72Jagsk.css","assets/MapInitErrorFallback-D3v7joX5.js","assets/parseAddress-Ct4gQxae.js","assets/reportTypes-D_oyZ7kO.js","assets/participantHelpers-FlJsqgZS.js","assets/PartiesParticipantsPanel-DQ5Pvnkz.js","assets/postIntakeHome-DjwkXGKO.js","assets/DeleteOrderDialog-Dk0O8VCr.js","assets/banks-technologies-primary-BbIkhlAd.js","assets/addressFormat-DLubgzGL.js","assets/useSubModuleAccess-1MphY0wX.js","assets/useRemarksInsights-DviFm035.js","assets/BlockBuilderStep-Bb4lkk1k.js","assets/useCreateOrder-BcJ-Ir92.js","assets/AddressAutocomplete-CCkrHulz.js","assets/banksInspectionEvidence--gLc3mJa.js","assets/MapboxAppraiserMap-BIHQyUIs.js","assets/derivedAddressLabel-ES5c8WKa.js","assets/cloudinaryUtils-CQJwpvXf.js","assets/OptimizedImage-YxgniqTY.js","assets/PropertyDetailView-CpyNUgXB.js","assets/StreetViewPhotoFallback-DMWDvGoR.js","assets/SubjectDrawer-DCkfnPNg.js","assets/api-Ds5L1_hM.js","assets/WizardSourceBadge-BpYodh4T.js","assets/FieldVerificationFilter-jURH6mJd.js","assets/StepOrder36-DAt5s_0Q.js","assets/appraiserLicenseType-VO0iBsAK.js","assets/AssignmentInfoSection-CBOu-HhR.js","assets/ScopeOfWorkSection-CSFsfXGc.js","assets/MultiComboboxWithCustom-Djs0pwwL.js","assets/SupplementalInfoTab-Ttsg_Llg.js","assets/CertificationsSection-D2T1k6un.js","assets/employmentTypeOptions-B5jPvqWj.js","assets/urarRequiredTabRouting-DRxYWhze.js","assets/settingsReturnTarget-CpWIiTyq.js","assets/subjectSiteRegistry-CDjebX0F.js","assets/slider-CUI_8__q.js","assets/salesGridSite-CH9kNfs6.js","assets/safeMapboxMap-CSUmZdu5.js","assets/MonthYearField-CApL0GvK.js","assets/ExhibitPhotosPanel-uhhWyph5.js","assets/radio-group-CBFXXW_C.js","assets/schema-C00ZrNCW.js","assets/DualSearchBar-DQw-rOBN.js","assets/useMapPopoutSync-CX2ZB2s-.js","assets/StrWizardContext-BBCYxIpu.js","assets/StepStrWelcome-WYalB1vW.js","assets/accordion-DHkr7kmb.js","assets/useStrReportContacts-Bttmd0rK.js","assets/strTypes-D3VpkGz4.js","assets/StepStrLegality-D49rn5pp.js","assets/StepStrMarket-D_OKIm8o.js","assets/strGlossary-DLi4_HZa.js","assets/StepStrMarketData-IQtWjKMZ.js","assets/PropertyDetailModal-DbmOu39u.js","assets/StepStrIncome-oNWC9Quo.js","assets/strLtrCommentHelper-BeYHCPE4.js","assets/StepStrCertifyExport-C8MB-hxo.js","assets/typed-signature-BM-bxsdV.js","assets/EvalWizardRevamped-DeNMlGyn.js","assets/EvalSectionCertification-CIsH8jkT.js","assets/EvalReportPanel-BNlZJCi1.js","assets/StepAtAGlance36-Bj97DrDl.js","assets/AtAGlanceSection-SYPjIY8g.js","assets/AddressBlock-vzbf-xeH.js","assets/SubjectPhotoField-BJb5Eurr.js","assets/SubjectPropertySection-cUSo20uV.js","assets/LegalDescriptionField-HDKkjOAs.js","assets/PropertyAmenitiesSection-Ceux1O47.js","assets/command-CoOgFdJf.js","assets/ExposureTimeField-BkG3Qo_z.js","assets/StepAssignment36-CoB2Tf-q.js","assets/StepSite36-BQtwh67M.js","assets/SiteSection-ZRaB1Lhn.js","assets/StepImprovements36-CoP0qibK.js","assets/ImprovementsSection-rAX68pzT.js","assets/NumberField-BIKXwH4P.js","assets/StepSubjectProperty36-DWD5YQHK.js","assets/DisasterMitigationSection-BUqAN6Bf.js","assets/EnergyFeaturesSection-DUByWUIn.js","assets/FunctionalObsolescenceSection-DlyXgg4u.js","assets/HighestBestUseSection-BLSq1IP9.js","assets/StepSalesContract36-C3HLUB_T.js","assets/SalesContractSection-lsapKhxn.js","assets/StepProjectInformation36-DZ0kG0J9.js","assets/ProjectInformationSection-gHXNqPSr.js","assets/PredefinedCaptionPhotosField-BlSjZaMb.js","assets/StepMarket36-Bp8J4Z4G.js","assets/MarketSection-4G9t3FkP.js","assets/StepCostApproach36-Dw4N7OjR.js","assets/CostApproachSection-BPaqhMr3.js","assets/StepListingSaleHistory36-CybzeJ_m.js","assets/ListingSaleHistorySection-CRGIH0cZ.js"])))=>i.map(i=>d[i]);
2import{r as o,u as ku,k as Vr,j as e,ai as Kl,ah as za,aq as Di,aX as Wl,aE as kr,b1 as uN,ae as Hh,Z as Rr,m as fo,v as Bs,b2 as x5,b3 as on,X as ur,b4 as Ru,aY as rf,aj as Eu,b5 as un,b6 as pN,b7 as Ci,b8 as jr,b9 as ul,$ as Du,ab as Ns,ba as fI,bb as Jj,bc as H0,bd as mc,be as Um,a$ as FO,bf as lp,bg as _O,bh as zR,b0 as Fo,bi as b5,bj as y5,bk as xg,bl as UO,bm as Zx,bn as gI,bo as VO,bp as Jx,bq as m0,br as $O,bs as BO,bt as gn,bu as zO,as as Zp,bv as Lo,bw as S5,aP as Wh,bx as hv,by as qR,bz as qO,bA as v5,bB as W0,aN as Ng,bC as pf,bD as cc,bE as Fh,bF as $d,bG as dc,bH as ql,bI as uc,bJ as KS,b
2K as np,bL as wu,bM as QS,bN as Xj,bO as Rh,bP as $x,bQ as xI,aZ as mN,bR as bg,bS as hN,aF as nf,bT as YO,bU as GO,bV as HO,bW as N5,bX as oy,aJ as I0,aK as Kh,bY as WO,bZ as Hy,b_ as Ex,b$ as KO,c0 as A5,c1 as fN,c2 as Vi,ad as of,x as fv,c3 as Mn,c4 as j5,c5 as ub,c6 as YR,c7 as Pu,c8 as Xx,ac as bI,ag as T5,c9 as eT,ca as I5,cb as C5,cc as QO,cd as R5,ce as ZO,cf as GR,cg as JO,ch as gN,ci as xN,aL as pc,cj as Wp,aH as Hr,ck as E5,cl as lf,cm as Ql,cn as w5,co as P5,cp as HR,cq as O5,cr as L5,cs as D5,ct as k5,cu as tT,cv as Bx,cw as M5,cx as F5,cy as _5,cz as WR,cA as KR,cB as U5,cC as V5,cD as $5,cE as XO,cF as B5,cG as z5,cH as q5,az as Pl,cI as eL,cJ as Y5,cK as bN,cL as yI,cM as gv,cN as tL,cO as G5,al as yN,cP as SI,cQ as aL,cR as H5,cS as sL,cT as W5,cU as pb,cV as _h,cW as K0,cX as K5,cY as C0,aI as Yd,cZ as R0,c_ as Q5,N as Z5,G as J5,O as X5,H as e2,c$ as SN,d0 as LA,aA as xv,d1 as bv,d2 as aT,d3 as vI,d4 as NI,d5 as rL,d6 as QR,d7 as t2,d8 as nL,d9 as a2,da as AI,ay as s2,db as r2,dc as n2,dd as i2,de as o2,df as l2,dg as ZR,dh as c2,di as d2,dj as u2,dk as p2,dl as m2,aW as iL,dm as h2,dn as f2,aG as oL,ar as sT,dp as g2,am as rT,an as nT,dq as x2,dr as b2,ds as y2,dt as JR,du as S2,dv as v2,dw as N2,dx as XR,dy as eE}from"./vendor-CMvvE79M.js";import{g as hc,D as xi,h as bi,i as $i,j as si,k as pl,B as De,d as kt,l as Lc,m as iT,n as A2,o as h0,p as eb,G as j2,T as gr,q as Ga,r as Ha,s as Wa,S as sr,t as rr,v as or,w as nr,x as vs,I as ze,y as Q,z as Go,A as fc,E as Fs,F as Qh,H as Zh,J as Jh,K as Yl,L as f0,M as T2,N as Lh,O as lL,P as jI,Q as yg,R as cL,U as I2,V as fi,W as ZS,X as kx,C as ja,e as Do,f as ko,Y as C2,c as Ta,Z as tE,_ as Qo,$ as yi,a0 as Uh,u as ly,a1 as R2,a2 as E2,a3 as tb,a4 as ri,a5 as ho,a6 as Zi,a7 as w2,a8 as tx,a9 as dL,aa as uL,ab as wo,ac as pL,ad as oT,ae as DA,af as kA,b as aE,ag as sE,ah as P2,ai as O2,aj as L2,ak as D2,al as JS,am as k2,an as mL,ao as M2,ap as F2,aq as _2,a as U2,ar as rE,as as V2,at as $2,au as B2,av as nE,aw as z2}from"./index-CJhDLLQN.js";import{g as q2,a as ax}from"./postIntakeHome-DjwkXGKO.js";import{D as Y2}from"./DeleteOrderDialog-Dk0O8VCr.js";import{T as Gd,a as Hd,b as gi,c as Ds,d as Wd,e as ws}from"./table-Dx2DCkzd.js";import{b as G2}from"./banks-technologies-primary-BbIkhlAd.js";import{f as Mx}from"./addressFormat-DLubgzGL.js";import{u as H2}from"./useSubModuleAccess-1MphY0wX.js";import{u as W2}from"./useRemarksInsights-DviFm035.js";import{B as K2}from"./BlockBuilderStep-Bb4lkk1k.js";import{G as Q2,M as Z2}from"./ModeToggle-BR7ekiJk.js";import{T as up,a as pp,b as $n,c as Bd}from"./tabs-CtFENyHp.js";import{i as TI,a as J2,v as yv,B as Kp,r as XS,b as X2,n as e_,c as t_,d as a_,e as sx,f as s_,g as r_,I as n_}from"./banksInspectionEvidence--gLc3mJa.js";import{a as Zn,b as Ho,c as dn,A as qo,d as Wy,e as ol}from"./sketch-CLNTnFNv.js";import{e as Hs,f as cf,R as Gp,D as vN,a as hL}from"./DateField-CCwn-aIi.js";import{c as fL,R as gL,F as xL,W as bL,a as yL,n as i_,d as Sv,b as o_,e as l_,r as E0,g as Pr,i as Xh,B as vv,f as II,h as Nv,j as c_,O as ab,A as cd,k as d_,o as SL,l as u_,m as Dc,p as vL,N as lT,C as Ky,q as iE,s as p_,D as sg,t as m_,u as h_,S as NL,M as oE,T as ug,v as cT,w as f_,x as g_,y as Kd,z as g0,E as x_,G as b_,H as y_,I as S_,J as v_,K as Il,L as N_,P as A_,Q as Xf,U as pg,V as AL,X as j_,Y as T_,Z as MA,_ as CI,$ as RI,a0 as I_,a1 as C_,a2 as R_,a3 as cl,a4 as lE,a5 as cE,a6 as rg,a7 as cy,a8 as Vm,a9 as mg,aa as Ag,ab as jL,ac as E_,ad as w_,ae as dE,af as TL,ag as IL,ah as eg,ai as uE,aj as P_,ak as O_,al as L_,am as D_,an as k_,ao as M_,ap as F_,aq as __,ar as U_,as as V_,at as rx,au as $_,av as B_,aw as z_,ax as q_,ay as Y_,az as G_,aA as H_,aB as W_,aC as K_,aD as Q_,aE as Z_,aF as pE,aG as J_,aH as X_,aI as Ou,aJ as eU,aK as tU,aL as aU,aM as sU,aN as rU,aO as CL,aP as nU,aQ as RL,aR as EL,aS as iU,aT as oU,aU as lU,aV as nx,aW as mE,aX as cU,aY as hE,aZ as FA,a_ as dU,a$ as uU,b0 as pU,b1 as fE,b2 as mU,b3 as hU,b4 as NN,b5 as Vh,b6 as Ob,b7 as fU,b8 as gE,b9 as gU,ba as xU,bb as xE,bc as bU,bd as yU,be as bE,bf as SU,bg as dT,bh as yE,bi as vU,bj as SE,bk as NU,bl as AU,bm as wL,bn as PL,bo as 
2jU,bp as TU,bq as IU,br as vE,bs as CU,bt as RU,bu as NE,bv as AE,bw as EU,bx as wU,by as PU,bz as jE,bA as TE,bB as IE,bC as OU,bD as LU,bE as DU,bF as kU}from"./Uad36ValidationNoticeDialog-DWrw-Xoe.js";import{d as OL,p as Rm,V as uT,a as LL,b as DL,c as MU,v as FU,i as _U,e as UU,f as Av,g as VU,h as kL,n as Em,j as CE,k as ML,l as RE,m as EE,u as Cu,D as $U,P as BU,Q as FL,o as _L,S as UL,A as zU,q as wE,r as pT,s as VL,t as PE,w as $L,x as qU,y as BL,z as OE,B as zL,E as _A,C as YU,F as LE,G as GU,R as ev,H as DE,I as HU,J as WU,K as Qy,L as KU,M as Vn,N as Fd,O as Lb,T as ix,U as kE,W as Zy,X as QU,Y as ZU,Z as JU,_ as XU,$ as eV,a0 as tV,a1 as aV,a2 as zx,a3 as Jy,a4 as Xy,a5 as qL,a6 as sV,a7 as rV,a8 as nV,a9 as EI,aa as iV,ab as oV,ac as lV,ad as YL,ae as cV,af as GL,ag as HL,ah as dV,ai as uV,aj as pV,ak as mV,al as hV,am as fV,an as gV,ao as xV,ap as bV,aq as yV,ar as SV,as as vV,at as ME,au as NV,av as AV,aw as jV,ax as TV}from"./Uad36UrarPanel-DlJwoJrM.js";import{L as Ja}from"./label-B2udOYFm.js";import{S as Qd}from"./scroll-area-DxnNy9Vx.js";import{A as WL,a as KL,b as QL,c as ZL,d as JL,e as XL,f as eD,g as tD}from"./alert-dialog-F1Xac2S4.js";import{U as w0,a as P0,c as Q0,e as dy,f as wI,b as aD,d as Mm,g as IV,h as sD,i as uy,j as jv,k as CV,l as sb,A as RV,m as Tv,n as PI,o as Iv,p as OI,u as EV,q as ng,r as mT,s as wV,t as LI,v as PV,M as OV,w as LV,x as DV,y as kV,z as MV,B as FE,C as _E,E as FV,D as _V,F as UV,G as VV,H as $V,I as BV,J as zV,K as qV,L as YV,N as eS,O as GV,P as HV,Q as WV}from"./MapboxAppraiserMap-BIHQyUIs.js";import{P as KV,d as DI,u as QV,N as kI,f as ZV,r as JV,a as XV,U as e$,b as t$}from"./PropertyDetailView-CpyNUgXB.js";import{u as a$,S as s$}from"./SubjectDrawer-DCkfnPNg.js";import{P as xn,a as bn,b as yn}from"./popover-E1IVhB14.js";import{g as MI,a as rb,b as rD,c as r$,p as n$}from"./cloudinaryUtils-CQJwpvXf.js";import{i as nD,g as i$,c as o$}from"./reportTypes-D_oyZ7kO.js";import{f as FI,a as hT,p as jm}from"./api-Ds5L1_hM.js";import{n as _f,e as l$}from"./AddressAutocomplete-CCkrHulz.js";import{g as iD,D as oD,a as lD,E as UE,S as pd,n as cD,b as Z0}from"./WizardSourceBadge-BpYodh4T.js";import{c as dD,F as uD,v as pD,a as VE}from"./FieldVerificationFilter-jURH6mJd.js";import{S as c$,u as AN}from"./StepOrder36-DAt5s_0Q.js";import{S as d$,a as u$}from"./sheet-CW_ZFNUH.js";import{u as _I,r as $E,p as p$,P as BE,g as m$,e as h$,h as f$,c as g$,a as x$,s as b$}from"./settingsReturnTarget-CpWIiTyq.js";import{B as Cv,C as tg}from"./subjectSiteRegistry-CDjebX0F.js";import{n as J0,g as jN,i as UI,m as TN,a as O0,D as y$}from"./derivedAddressLabel-ES5c8WKa.js";import{d as S$}from"./cardinality-CoXArXef.js";import{C as Pa}from"./checkbox-f2Bkp6Dm.js";import{P as v$}from"./PartiesParticipantsPanel-DQ5Pvnkz.js";import{S as IN}from"./slider-CUI_8__q.js";import{M as qx}from"./MultiComboboxWithCustom-Djs0pwwL.js";import{S as N$}from"./switch-60NKGYKO.js";import{S as sd,a as tS,i as zE,s as aS,b as qE,h as A$,H as j$,c as T$,d as I$,f as C$,e as R$}from"./salesGridSite-CH9kNfs6.js";import{a as ox}from"./maps-CuvAq4kb.js";import{g as E$,l as w$}from"./mapboxToken-BBXATyou.js";import{c as P$}from"./safeMapboxMap-CSUmZdu5.js";import{M as O$}from"./MapInitErrorFallback-D3v7joX5.js";import{S as Rv}from"./separator-C55a0Ko7.js";import{M as L$}from"./MonthYearField-CApL0GvK.js";import{E as mD}from"./ExhibitPhotosPanel-uhhWyph5.js";import{C as CN,a as RN,b as EN}from"./collapsible-BYY0UvDl.js";import{R as D$,a as YE}from"./radio-group-CBFXXW_C.js";import{O as k$}from"./OptimizedImage-YxgniqTY.js";import{B as GE,a as HE}from"./schema-C00ZrNCW.js";import{A as WE,a as KE}from"./alert-D7EgiqET.js";import{D as M$}from"./DualSearchBar-DQw-rOBN.js";import{u as F$}from"./useMapPopoutSync-CX2ZB2s-.js";import{S as _$,u as U$}from"./StrWizardContext-BBCYxIpu.js";import{g as lx,f as sS}from"./participantHelpers-FlJsqgZS.js";const hD={roofType:["Asphalt Shingle","Metal","Tile","Slate","Wood","Membrane","Other"],exteriorWall:["Brick","Stucco","Wood","Vinyl Siding","Aluminum Siding","Fiber Cement","Stone","Other"],foundation:["Slab","Crawl Space","Basement","Post and Pier","Runner","Other"],basement:["Full Finished","Full Unfinished","Partial Finished","Partial Unfinished","Full","Partial","None"],garageType:["Attached","Detached","Built-in","Garage","Carport","Driveway","Shared Driveway","Open Lot","Common Carport","Parking Garage","None","Other"],derivedLotShape:["Rectangular","Irregular","Triangular","Trapezoidal","Other"],utilities:["All Public","Public","Community","Private","Well & Septic","Mixed"],driveway:["Asphalt","Concrete","Gravel","Pavers","Dirt","None","Other"]},V$={roofType:{compshingle:"Asphalt Shingle",compositionshingle:"Asphalt Shingle",composition:"Asphalt Shingle",asphaltshingle:"Asphalt Shingle",asphalt:"Asphalt Shingle",shingle:"Asphalt Shingle",flatbuiltup:"Membrane",builtup:"Membrane",flat:"Membrane",rubber:"Membrane",epdm:"Membrane",tpo:"Membrane",woodshake:"Wood",shake:"Wood",woodshingle:"Wood",claytile:"Tile",concretetile:"Tile",spanishtile:"Tile"},exteriorWall:{vinylsiding:"Vinyl Siding",vinyl:"Vinyl Siding",aluminumsiding:"Aluminum Siding",aluminum:"Aluminum Siding",hardiplank:"Fiber Cement",hardieplank:"Fiber Cement",hardiboard:"Fiber Cement",fibercement:"Fiber Cement",cementfiber:"Fiber Cement",cementboard:"Fiber Cement",woodsiding:"Wood",brickveneer:"Brick"},foundation:{fullbasement:"Basement",partialbasement:"Basement",basementfull:"Basement",basementpartial:"Basement",crawlspace
2:"Crawl Space",crawl:"Crawl Space",pierpost:"Post and Pier",postandpier:"Post and Pier",postpier:"Post and Pier",pier:"Post and Pier",pierandbeam:"Post and Pier",piers:"Post and Pier",concreteslab:"Slab",slabongrade:"Slab"},basement:{fullbasement:"Full",partialbasement:"Partial",nobasement:"None",no:"None",fullfinished:"Full Finished",fullunfinished:"Full Unfinished",partialfinished:"Partial Finished",partialunfinished:"Partial Unfinished"},garageType:{attachedgarage:"Attached",garageattached:"Attached",detachedgarage:"Detached",garagedetached:"Detached",builtin:"Built-in",builtingarage:"Built-in",shareddriveway:"Shared Driveway",openlot:"Open Lot",commoncarport:"Common Carport",parkinggarage:"Parking Garage",nogarage:"None",no:"None"},derivedLotShape:{rectangulartypical:"Rectangular",irregularlargelot:"Irregular",rect:"Rectangular",square:"Rectangular",trapezoid:"Trapezoidal",triangle:"Triangular"},utilities:{allpublic:"All Public",publicutilities:"Public",wellseptic:"Well & Septic",wellandseptic:"Well & Septic",septic:"Well & Septic",well:"Well & Septic",publicprivate:"Mixed",publicandprivate:"Mixed"},driveway:{paver:"Pavers",brickpavers:"Pavers",brickpaver:"Pavers",blacktop:"Asphalt",cement:"Concrete",earth:"Dirt",nodriveway:"None",no:"None"}};function fT(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}function fD(t,a){if(a==null)return null;const s=String(a).trim();if(!s)return null;const r=hD[t];if(!r)return s;const n=fT(s);for(const l of r)if(fT(l)===n)return l;const i=V$[t]?.[n];return i||s}function ete(t,a){const s=[...hD[t]??[]],r=(a??"").trim();return r&&!s.some(n=>n===r)&&s.push(r),s}function $$(t,a){const s=i=>{const l=fT(i??"");return l?l.includes("public")||l.includes("municipal")||l.includes("city")?"public":l.includes("community")||l.includes("shared")?"community":l.includes("well")||l.includes("septic")||l.includes("private")||l.includes("individual")?"private":null:null},r=s(t),n=s(a);if(!r&&!n)return null;if(r==="public"&&n==="public")return"All Public";if((r??n)===(n??r)){const i=r??n;return i==="public"?"All Public":i==="community"?"Community":"Well & Septic"}return"Mixed"}function cx(t,a,s){const r=p=>p==null?"":String(p).trim(),n=r(a),i=r(s),l=n||i;if(!l)return;const c=fD(t,l)??l,d={};return n&&(d.mls=n),i&&(d.public_record=i),{value:c,source:n?"MLS":"PublicRecord",isEdited:!1,alternatives:d}}function gD(t,a){if(a==null)return;const s=String(a).trim();if(s)return fD(t,s)??s}function B$(t){if(t==null)return null;const a=String(t).trim().toLowerCase();return a===""?null:/\bpurchase\b/.test(a)||a==="buy"?"Purchase":/\brefi(nance)?\b/.test(a)?"Refinance":"Other"}const QE="#072034",ZE="#C5A572",z$="#FAF9F7",q$="#EDE8E4",Uf=t=>(t??"").trim().toLowerCase();function Y$(t,a){if(!a)return!1;const s=Uf(a.address);return!(!s||!Uf(t.propertyAddress)||Uf(t.propertyAddress)!==s||a.city&&t.city&&Uf(t.city)!==Uf(a.city)||a.state&&t.state&&Uf(t.state)!==Uf(a.state))}function G$(t){if(!t)return null;const a=new Date(t);return Number.isNaN(a.getTime())?null:a.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})+" at "+a.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})}function H$({open:t,onOpenChange:a,orderId:s,onPulled:r}){const[n,i]=o.useState(null),[l,c]=o.useState(null),{toast:d}=hc(),p=ku(),u=["/api/integrations/banks-inspection/inspections",s],{data:m,isLoading:h,isError:f,error:v,refetch:S,isFetching:N}=Vr({queryKey:u,queryFn:()=>Zn(`/api/integrations/banks-inspection/inspections?orderId=${encodeURIComponent(s)}`),enabled:t&&!!s,staleTime:15e3}),x=o.useMemo(()=>(m?.inspections??[]).map(T=>({item:T,match:Y$(T,m?.orderAddress)})).sort((T,O)=>T.match!==O.match?T.match?-1:1:String(O.item.completedAt??"").localeCompare(String(T.item.completedAt??""))),[m]),y=async b=>{i(b),c(null);try{const j=await Zn(`/api/integrations/banks-inspection/orders/${encodeURIComponent(s)}/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jobId:b})});d({title:"Inspection pulled",description:`Inspection data${j.address?` for ${j.address}`:""} was imported into this order.`+(j.photoCount?` ${j.photoCount} photo(s) included.`:"")+(j.evidence?` Evidence package ${j.evidence.status??"imported"}: ${j.evidence.itemCount??0} item(s), ${j.evidence.assetCount??0} asset(s)${j.evidence.revisionId?`, revision ${j.evidence.revisionId}`:""}${j.evidence.failedAssetCount?`, ${j.evidence.failedAssetCount} asset retrieval(s) failed`:""}.`:"")}
2),p.invalidateQueries({queryKey:u}),r(),a(!1)}catch(j){c(j instanceof Error?j.message:"Failed to pull the inspection.")}finally{i(null)}};return e.jsx(xi,{open:t,onOpenChange:b=>!n&&a(b),children:e.jsxs(bi,{className:"max-w-2xl","data-testid":"banks-inspection-pull-dialog",children:[e.jsxs($i,{children:[e.jsx(si,{className:"text-sm font-semibold",style:{color:QE},children:"Pull from Banks Inspection"}),e.jsx(pl,{className:"text-xs text-slate-500",children:"Completed inspections submitted on the Banks Inspection App. Pulling stores the full inspection data on this order."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[11px] text-slate-400","data-testid":"text-banks-inspection-count",children:x.length>0?`${x.length} inspection${x.length===1?"":"s"}`:""}),e.jsxs(De,{variant:"ghost",size:"sm",className:"h-6 px-2 text-[11px] text-slate-500",onClick:()=>S(),disabled:N,"data-testid":"button-refresh-banks-inspections",children:[e.jsx(Kl,{className:`w-3 h-3 mr-1 ${N?"animate-spin":""}`}),"Refresh"]})]}),e.jsxs("div",{className:"max-h-[50vh] overflow-y-auto space-y-2","data-testid":"banks-inspection-list",children:[h&&e.jsx("div",{className:"flex items-center justify-center py-10 text-slate-400","data-testid":"banks-inspection-loading",children:e.jsx(za,{className:"w-5 h-5 animate-spin"})}),f&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-red-600 py-4","data-testid":"banks-inspection-error",children:[e.jsx(Di,{className:"w-4 h-4 shrink-0"}),v instanceof Error?v.message:"Could not load inspections."]}),!h&&!f&&x.length===0&&e.jsx("div",{className:"text-xs text-slate-500 py-8 text-center","data-testid":"banks-inspection-empty",children:"No completed inspections are ready to pull. Once an appraiser submits an inspection in the Banks Inspection App it will show up here."}),x.map(({item:b,match:j})=>{const T=G$(b.completedAt);return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-white px-3 py-2.5",style:{borderColor:j?ZE:q$,backgroundColor:j?z$:void 0},"data-testid":`banks-inspection-item-${b.jobId}`,children:[e.jsx(Wl,{className:"w-4 h-4 shrink-0",style:{color:j?ZE:"#94a3b8"}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-700 truncate","data-testid":`text-banks-address-${b.jobId}`,children:[b.propertyAddress,b.city,b.state].filter(Boolean).join(", ")||b.jobId}),j&&e.jsx(kt,{className:"text-[10px] px-1.5 py-0 border-0",style:{backgroundColor:"#F3EBDD",color:"#8B6F47"},"data-testid":`badge-banks-match-${b.jobId}`,children:"Matches this order"}),b.retrieved&&e.jsxs(kt,{className:"bg-slate-100 text-slate-500 text-[10px] px-1.5 py-0 border-0","data-testid":`badge-banks-retrieved-${b.jobId}`,children:[e.jsx(kr,{className:"w-3 h-3 mr-0.5"}),"Pulled before"]})]}),e.jsx("div",{className:"text-[11px] text-slate-400 truncate",children:[b.clientName||null,T?`Completed ${T}`:null,b.packageVersion!=null?`v${b.packageVersion}`:null].filter(Boolean).join(" · ")})]}),e.jsxs(De,{size:"sm",className:"h-7 px-3 text-xs text-white hover:opacity-90 shrink-0",style:{backgroundColor:QE},onClick:()=>y(b.jobId),disabled:n!==null,"data-testid":`button-pull-banks-${b.jobId}`,children:[n===b.jobId?e.jsx(za,{className:"w-3.5 h-3.5 mr-1.5 animate-spin"}):e.jsx(uN,{className:"w-3.5 h-3.5 mr-1.5"}),"Pull"]})]},b.jobId)})]}),l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-red-600","data-testid":"text-banks-pull-error",children:[e.jsx(Di,{className:"w-3.5 h-3.5 shrink-0"}),l]})]})})}function W$(t){const a=String(t??"").match(/\b(1[6-9]\d{2}|20\d{2})\b/);return a?Number(a[1]):null}function K$(t){const a=Number(String(t??"").replace(/[^\d.]/g,""));return Number.isFinite(a)&&a>0?Math.round(a):null}const Q$=["AFrame","Barn","BiLevel","Bungalow","CapeCod","Chalet","Colonial","Contemporary","Cottage","Craftsman","EarthBerm","Farmhouse","GeodesicDome","Georgian","Log","Mediterranean","Modern","NeoEclectic","RaisedRanch","Rambler","Ranch","Southwest","Spanish","SplitFoyerOrEntry","SplitLevel","Stilt","Traditional","Tudor","Victorian"];function Sg(t){return t.toLowerCase().replace(/[^a-z]/g,"")}function Z$(t){const a=Sg(String(t??""));if(!a)return null;for(const s of Q$)if(Sg(s)===a)return s;return/splitfoyer|splitentry/.test(a)?"SplitFoyerOrEntry":/conventional/.test(a)?"Traditional":null}function J$(t){const a=String(t??"").toLowerCase();return a.trim()?/mini[\s-]*split|ductless/.test(a)?"MiniSplit":/forced|
2warm\s*air|central\s*(heat|furnace)|furnace|hot\s*air/.test(a)?"ForcedWarmAir":/baseboard/.test(a)?"Baseboard":/gravity/.test(a)?"GravityAir":/radiant|floor\s*heat/.test(a)?"Radiant":/radiator/.test(a)?"Radiators":/passive\s*solar/.test(a)?"PassiveSolar":/stove|pellet/.test(a)?"Stove":/fireplace/.test(a)?"Fireplace":/^none$|no\s*heat/.test(a.trim())?"None":null:null}function rS(t){if(typeof t=="boolean")return t;const a=String(t??"").trim().toLowerCase();return a==="true"||a==="yes"||a==="y"?!0:a==="false"||a==="no"||a==="n"?!1:null}function gT(t,a){const s=Sg(String(t??""));if(!s)return null;for(const r of a)if(Sg(r)===s)return r;return null}const X$=["OwnerOccupied","Tenant","Vacant"];function e3(t){const a=gT(t,X$);if(a)return a;const s=Sg(String(t??""));return s?/owner/.test(s)?"OwnerOccupied":/tenant|renter|rented/.test(s)?"Tenant":/vacant|empty/.test(s)?"Vacant":null:null}const t3=["ExteriorAccessOnly","InteriorAccessOnly","InteriorAndExteriorAccess"],a3=["Inferior","Similar","Superior"];function s3(t){const a=String(t??"").trim();return a?a.slice(0,3):null}const r3=["Highrise","Lowrise","Midrise","Other","RowhouseTownhouse","SemiDetached"];function n3(t){const a=Sg(String(t??""));if(!a)return null;for(const s of r3)if(Sg(s)===a)return s;return/rowhouse|townhouse|townhome|rowhome/.test(a)?"RowhouseTownhouse":/semidetached|semi/.test(a)?"SemiDetached":/highrise/.test(a)?"Highrise":/midrise/.test(a)?"Midrise":/lowrise/.test(a)?"Lowrise":null}function i3(t){const a=String(t??"").toLowerCase();return a.trim()?/central|centralized/.test(a)?"Centralized":/window|wall\s*unit|individual|mini[\s-]*split|ductless|room\s*(ac|air)/.test(a)?"Individual":null:null}const wN={"0300.0011":{read:t=>t.yearBuilt,map:W$,apply:(t,a)=>({...t,yearBuilt:Number(a)})},"0300.0064":{read:t=>t.storiesCount,map:K$,apply:(t,a)=>({...t,storiesCount:Number(a)})},"0300.0030":{read:t=>t.architecturalDesignCategoryType,map:Z$,apply:(t,a)=>({...t,architecturalDesignCategoryType:String(a)})},"0300.0088":{read:t=>t.heatingSystems.find(a=>Lc(a.type))?.type??null,map:J$,apply:(t,a)=>({...t,heatingSystems:[{type:String(a),fuelType:null}]})},"0300.0084":{read:t=>t.coolingSystemTypes.find(a=>Lc(a))??null,map:i3,apply:(t,a)=>({...t,coolingSystemTypes:[String(a)],coolingSystemExistsIndicator:!0})},"0300.0032":{read:t=>t.structuralDesignType,map:n3,apply:(t,a)=>({...t,structuralDesignType:String(a)})},"0700.0066":{read:t=>t.units[0]?.interiorConditionRatingCode??null,map:t=>nS(t,"C"),apply:(t,a)=>JE(t,"interiorConditionRatingCode",String(a))},"0700.0067":{read:t=>t.units[0]?.interiorQualityRatingCode??null,map:t=>nS(t,"Q"),apply:(t,a)=>JE(t,"interiorQualityRatingCode",String(a))},"1600.0004":{read:t=>t.exteriorConditionRatingCode,map:t=>nS(t,"C"),apply:(t,a)=>({...t,exteriorConditionRatingCode:String(a)})},"1600.0005":{read:t=>t.exteriorQualityRatingCode,map:t=>nS(t,"Q"),apply:(t,a)=>({...t,exteriorQualityRatingCode:String(a)})},"0300.0098":UA("ExteriorWallsAndTrim","wallMaterials",bL.map(t=>t.value)),"0300.0044":UA("Foundation","foundationMaterials",xL.map(t=>t.value)),"0300.0050":UA("Roof","roofMaterials",gL.map(t=>t.value)),"0700.0070":gh("unitOccupancyType",e3),"0700.0058":gh("cornerUnitIndicator",rS),"0700.0060":gh("floorIdentifier",s3),"0700.0091":gh("aduAccessType",t=>gT(t,t3)),"0700.0100":gh("allowableLiveWorkSpaceIndicator",rS),"0700.0090":gh("aduSeparatePostalAddress",rS),"0700.0064":gh("unitBelowGradeFinishComparisonType",t=>gT(t,a3)),"0700.0130":gh("unitMixedUsageIndicator",rS)};function gh(t,a){return{read:s=>s.units?.[0]?.[t]??null,map:a,apply:(s,r)=>o3(s,t,r)}}function o3(t,a,s){const r=Array.isArray(t.units)?t.units:[];return r.length===0?{...t,units:[yL({[a]:s})]}:{...t,units:r.map((n,i)=>i===0?{...n,[a]:s}:n)}}function l3(t){return{id:i_("extc"),componentType:t,componentTypeOtherDescription:null,componentTypeAdditionalDescription:null,wallMaterials:[],foundationMaterials:[],foundationEntries:[],roofMaterials:[],roofObservableIndicator:null,roofEstimatedAgeRangeType:null,windowSurfaceAreaMeasure:null,conditionStatusType:null,conditionDescription:null,qualityDescription:null}}function UA(t,a,s){return{read:r=>
2(r.exteriorComponents??[]).find(i=>i.componentType===t)?.[a]?.find(i=>Lc(i))??null,map:r=>typeof r=="string"&&s.includes(r.trim())?r.trim():null,apply:(r,n)=>{const i=String(n),l=Array.isArray(r.exteriorComponents)?r.exteriorComponents:[],c=l.findIndex(d=>d.componentType===t);return c===-1?{...r,exteriorComponents:[...l,{...l3(t),[a]:[i]}]}:{...r,exteriorComponents:l.map((d,p)=>p===c?{...d,[a]:[i]}:d)}}}}function nS(t,a){const s=typeof t=="string"?t.trim().toUpperCase():"";return new RegExp(`^${a}[1-6]$`).test(s)?s:null}function JE(t,a,s){return!Array.isArray(t.units)||t.units.length===0?t:{...t,units:t.units.map((r,n)=>n===0?{...r,[a]:s}:r)}}const xD=new Set(["0300.0032"]),bD=new Set(["0700.0070","0700.0058","0700.0060","0700.0091","0700.0100","0700.0090","0700.0064","0700.0130"]);function yD(t){const a=VI(Array.isArray(t)?t:[]);return Array.isArray(a?.units)?a.units.length:0}function Ev(t){return(Array.isArray(t)?t:[]).filter(a=>a.improvementType==="Dwelling").length}function SD(t,a){return!(!(t in wN)||xD.has(t)&&Ev(a)>1||bD.has(t)&&(Ev(a)>1||yD(a)>1))}function VI(t){return t.find(a=>a.improvementType==="Dwelling")??null}function c3(t,a){const s=wN[a],r=VI(t);return!s||!r?null:s.read(r)}function vD(t,a,s,r){const n=wN[a];if(!n)return{buildings:t,applied:!1,skippedReason:"unknown-field"};const i=Array.isArray(t)?t:[];if(xD.has(a)&&Ev(i)>1)return{buildings:i,applied:!1,skippedReason:"multiple-dwellings"};if(bD.has(a)){if(Ev(i)>1)return{buildings:i,applied:!1,skippedReason:"multiple-dwellings"};if(yD(i)>1)return{buildings:i,applied:!1,skippedReason:"multiple-units"}}const l=VI(i);if(!l){const d=n.apply(fL({improvementType:"Dwelling"}),s);return{buildings:[...i,d],applied:!0,skippedReason:null}}return!r?.overwrite&&Lc(n.read(l))?{buildings:i,applied:!1,skippedReason:"existing-value"}:{buildings:i.map(d=>d===l?n.apply(d,s):d),applied:!0,skippedReason:null}}function d3(t){const a=String(t??"").toLowerCase();return a?a.includes("boxli")?"boxli":a.includes("public")||a.includes("propmix")||a.includes("record")?"publicrecord":a.includes("mls")?"mls":a.includes("manual")||a.includes("user")?"manual":null:null}function XE(t,a){return xT(t,a)}function xT(t,a){if(t===a)return!0;const s=Number(t),r=Number(a);return Number.isFinite(s)&&Number.isFinite(r)?s===r:String(t??"").trim().toLowerCase()===String(a??"").trim().toLowerCase()}function u3(t,a,s,r,n){const i=!t.home&&SD(t.uid,n??[]),l=t.home?a(t.home.section,t.home.field):i?c3(n??[],t.uid):null,c=Lc(l),d=iT(t);let p=null;if(d){const h=s?.find(f=>f.fieldKey===d);if(h&&Lc(h.value)&&(p={value:h.value,source:"boxli",displayValue:h.displayValue}),!p&&r){const f=r[d];if(f&&typeof f=="object"){const v=d3(f.source);if(Lc(f.value)&&(v==="publicrecord"||v==="mls"||v==="boxli"))p={value:f.value,source:v};else{const S=f.alternatives??{},N=S.propmix??S.publicRecord??S.publicrecord,x=S.mls;Lc(N)?p={value:N,source:"publicrecord"}:Lc(x)?p={value:x,source:"mls"}:Lc(f.value)&&v==="manual"&&!c&&(p={value:f.value,source:"manual"})}}}}if(p&&i){const h=wN[t.uid].map(p.value);h===null?p=null:p={...p,value:h,displayValue:p.displayValue??String(p.value)}}const u=c&&!!d&&!!r&&String(r[d]?.source??"").toLowerCase().includes("default")&&xT(r[d]?.value,l);let m=null;return p&&c&&xT(p.value,l)&&(m=p,p=null),{entry:t,currentValue:l,filled:c,suggestion:p,conflict:!!p&&c&&!u,agreedSuggestion:m,defaultTagged:u,buildingScoped:i}}
2function p3(t,a,s,r,n){return t.map(i=>u3(i,a,s,r,n))}const m3={boxli:.95,manual:.9,publicrecord:.85,mls:.7,image:.65,voice:.6},h3=.8;function f3(t){return typeof t.confidence=="number"&&Number.isFinite(t.confidence)?Math.min(1,Math.max(0,t.confidence)):m3[t.source]??0}function bT(t){const a=t.filled&&!t.defaultTagged;return t.suggestion?a?t.conflict?"conflict":"confirmed":"suggested":a&&t.agreedSuggestion?"confirmed":"blank"}function VA(t,a,s){const r={items:[],skippedConflicts:0,skippedLowConfidence:0,skippedUnwritable:0},n=new Set;for(const i of t){if(n.has(i.entry.uid))continue;n.add(i.entry.uid);const l=bT(i);if(l==="conflict"){r.skippedConflicts++;continue}if(l!=="suggested"||!i.suggestion)continue;const c=i.suggestion,d=i.buildingScoped&&SD(i.entry.uid,a);if(!i.entry.home&&!d){r.skippedUnwritable++;continue}const p=f3(c);if(s?.minConfidence!==void 0&&p<s.minConfidence){r.skippedLowConfidence++;continue}r.items.push({status:i,value:c.value,source:c.source,confidence:p})}return r}function g3(t,a){let s=Array.isArray(t)?t:[];const r=[],n=[];for(const i of a){if(!i.status.buildingScoped)continue;const l=vD(s,i.status.entry.uid,i.value);l.applied?(s=l.buildings,r.push(i.status.entry.uid)):n.push(i.status.entry.uid)}return{buildings:s,appliedUids:r,skippedUids:n,changed:r.length>0}}function ND(t){const a=String(t??"").toLowerCase();
2return a?/half\s*bath|powder/.test(a)?"HalfBathroom":/full\s*bath|bath/.test(a)?"FullBathroom":/bed/.test(a)?"Bedroom":/kitchen/.test(a)?"Kitchen":/dining/.test(a)?"DiningRoom":/living|family|great/.test(a)?"LivingRoom":/laundry|utility/.test(a)?"LaundryRoom":/office|study|den/.test(a)?"Den":/recreation|rec\b|game/.test(a)?"RecreationRoom":null:null}const ew=["LevelOne","LevelTwo","LevelThree","LevelFour","LevelFive","LevelSix","LevelSeven","LevelEight","LevelNine","LevelTen"],tw=["BelowGradeOne","BelowGradeTwo","BelowGradeThree","BelowGradeFour","BelowGradeFive"];function $A(t){return typeof t=="number"&&Number.isFinite(t)?Math.round(t):null}function x3(t){const a=ND(t.roomType??t.name);return l_({roomType:a})}function b3(t,a,s){const r=t.isBasement?tw[Math.min(s,tw.length-1)]:ew[Math.min(a,ew.length-1)],n=$A(t.finishedAreaSqFt),i=$A(t.unfinishedAreaSqFt)??(n!==null&&t.areaSqFt!=null?Math.max(0,Math.round(t.areaSqFt-n)):null);return o_({levelType:r,gradeLevelType:t.isBasement?"FullyBelowGrade":"AboveGrade",finishedAreaMeasure:n??(t.isBasement?null:$A(t.areaSqFt)),unfinishedAreaMeasure:i,rooms:t.rooms.map(x3)})}function AD(t){if(!Array.isArray(t)||t.length===0)return null;const a=[...t].sort((d,p)=>(d.floorNumber??0)-(p.floorNumber??0));let s=0,r=0;const n=a.map(d=>{const p=b3(d,s,r);return d.isBasement?r++:s++,p}),i=yL({label:"Unit 1",levels:n}),l=Sv(i);return fL({improvementType:"Dwelling",units:[{...i,...l}]})}const Db={bedroomCount:"0700.0118",fullBathroomCount:"0700.0119",halfBathroomCount:"0700.0120",levelCount:"0700.0063",totalRoomCount:"0300.0020"};function y3(t){const a=t?.units?.[0];if(!a)return{};const s=Sv(a),r={};return s.bedroomCount!==null&&(r[Db.bedroomCount]=s.bedroomCount),s.fullBathroomCount!==null&&(r[Db.fullBathroomCount]=s.fullBathroomCount),s.halfBathroomCount!==null&&(r[Db.halfBathroomCount]=s.halfBathroomCount),s.totalRoomCount!==null&&(r[Db.totalRoomCount]=s.totalRoomCount),a.levels.length>0&&(r[Db.levelCount]=a.levels.length),r}function S3(t,a){const s=a?.units?.[0];if(!s)return!1;const n=(t??[]).find(c=>c.improvementType==="Dwelling")?.units?.[0];if(!n)return!1;const i=Sv(n),l=Sv(s);return n.levels.length===s.levels.length&&i.bedroomCount===l.bedroomCount&&i.fullBathroomCount===l.fullBathroomCount&&i.halfBathroomCount===l.halfBathroomCount}function jD(t,a){return a?Array.isArray(t)&&t.length>0?{buildings:t,applied:!1,skippedReason:"existing-buildings"}:{buildings:[a],applied:!0,skippedReason:null}:{buildings:t,applied:!1,skippedReason:"no-suggestion"}}const ig={boxli:{label:"Boxli",cls:"bg-violet-100 text-violet-700 border-violet-200"},publicrecord:{label:"Public Record",cls:"bg-sky-100 text-sky-700 border-sky-200"},mls:{label:"MLS",cls:"bg-amber-100 text-amber-700 border-amber-200"},manual:{label:"Manual",cls:"bg-slate-100 text-slate-600 border-slate-200"},image:{label:"Image",cls:"bg-emerald-100 text-emerald-700 border-emerald-200"},voice:{label:"Voice",cls:"bg-rose-100 text-rose-700 border-rose-200"}};function v3(t){return t&&typeof t=="object"&&"value"in t?t.value:t}function TD(t){const a=t.trim().toLowerCase();return a.startsWith("subject property")||a.startsWith("ownership rights")||a.startsWith("legal description")||a.startsWith("site")||a.startsWith("utilities")||a.startsWith("view")?"subjectProperty":a.startsWith("invoice")?"assignmentInfo":"improvements"}const N3={subjectProperty:"subjectProperty",site:"subjectProperty",vehicleStorage:"vehicleStorage",propertyAmenities:"amenities",sketch:"improvements"};function A3(t){if(t.scope==="building")return`improvements.${t.name}`;if(t.home){const r=N3[t.home.section];if(r)return`${r}.${t.home.field}`}return`${t.section.trim().toLowerCase().startsWith("subject property amenities")?"amenities":TD(t.section)}.${t.name}`}function j3(t,a,s){const r=`/3.6/${encodeURIComponent(t)}?section=${encodeURIComponent(TD(a))}`,n=s?A3(s):null;return n?`${r}&field=${encodeURIComponent(n)}`:r}const aw=t=>t.replace(/\s+/g,"-").toLowerCase();function T3({orderId:t,boxliFields:a,floors:s,subjectBag:r,bagReady:n,onAcceptBagFields:i,imageSuggestions:l,voiceSuggestions:c,readOnly:d}){const{toast:p}=hc(),u=ku(),m=[`/api/uad36/prefill/${t}`,"inspection-manifest"],{data:h,isLoading:f,isError:v}=Vr({queryKey:m,queryFn:()=>Zn(`/api/uad36/prefill/${t}`),enabled:!!t,staleTime:3e4}),S=h?.sections??{},N=o.useCallback((ce,Pe)=>v3(S?.[ce]?.[Pe]),[S]),x=o.useMemo(()=>{const ce=N("subjectProperty","HomeownerResponsibleForExteriorMaintenanceIndicator");return ce===!0||String(ce??"").toLowerCase()==="true"},[N]),y=o.useMemo(()=>
2{if(!h?.conditionality)return[];const ce=OL(S,h.conditionality);return A2(ce,{homeownerResponsibleExterior:x})},[h?.conditionality,S,x]),b=o.useMemo(()=>E0(S??{}),[S]),j=o.useMemo(()=>AD(s),[s]),T=o.useMemo(()=>jD(b,j),[b,j]),O=o.useMemo(()=>T.applied?y3(j):{},[T.applied,j]),E=o.useMemo(()=>{const ce=new Map;for(const Pe of y)for(const We of Pe.subsections)for(const Re of p3(We.entries,N,a,n?r:void 0,b)){const ne=O[Re.entry.uid];if(ne!==void 0&&!Re.filled&&!Re.suggestion&&!Re.agreedSuggestion){ce.set(Re.entry.uid,{...Re,suggestion:{value:ne,source:"boxli"}});continue}const Me=l?.[Re.entry.name];if(Me&&!Re.suggestion&&!Re.agreedSuggestion){const Tt={value:Me.value,source:"image",photoUrls:Me.photoUrls},je=Re.filled&&XE(Re.currentValue,Me.value);ce.set(Re.entry.uid,{...Re,suggestion:je?null:Tt,agreedSuggestion:je?Tt:null,conflict:!je&&Re.filled&&!Re.defaultTagged});continue}const lt=c?.[Re.entry.name];if(lt&&!Re.suggestion&&!Re.agreedSuggestion&&!Me){const Tt={value:lt.value,source:"voice",snippet:lt.snippet??void 0},je=Re.filled&&XE(Re.currentValue,lt.value);ce.set(Re.entry.uid,{...Re,suggestion:je?null:Tt,agreedSuggestion:je?Tt:null,conflict:!je&&Re.filled&&!Re.defaultTagged});continue}ce.set(Re.entry.uid,Re)}return ce},[y,N,a,n,r,b,l,c,O]),[R,G]=o.useState({}
2),[U,C]=o.useState(null),[F,A]=o.useState(!1),[M,B]=o.useState(new Set),[oe,ae]=o.useState(!1),[D,_]=o.useState(null),[$,z]=o.useState(!1),[V,le]=o.useState(!1),W=o.useCallback(async ce=>{if(!d)try{await Zn(`/api/uad36/section-attachments/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({patches:ce}),retryTransientErrors:!0}),await u.invalidateQueries({queryKey:m})}catch(Pe){throw u.invalidateQueries({queryKey:m}),Pe}},[t,u]),me=o.useCallback(async ce=>{if(d)return{written:0,bridgeSkipped:0};const Pe=ce.filter(Me=>Me.status.entry.home),We=ce.filter(Me=>!Me.status.entry.home&&Me.status.buildingScoped),Re=Pe.map(Me=>({section:Me.status.entry.home.section,field:Me.status.entry.home.field,value:Me.value,source:Me.source})),ne=g3(b,We);if(ne.changed&&Re.push({section:"improvements",field:"buildings",value:ne.buildings}),Re.length===0)return{written:0,bridgeSkipped:ne.skippedUids.length};if(await W(Re),n){const Me=Pe.map(lt=>{const Tt=iT(lt.status.entry);return Tt?{fieldKey:Tt,value:lt.value}:null}).filter(lt=>!!lt);Me.length>0&&await i(Me)}return{written:Pe.length+ne.appliedUids.length,bridgeSkipped:ne.skippedUids.length}},[b,W,n,i,d]),Z=o.useCallback(async(ce,Pe,We,Re)=>{if(!d&&ce.home){C(ce.uid);try{await W([{section:ce.home.section,field:ce.home.field,value:Pe,source:Re}]);const ne=iT(ce);ne&&n&&await i([{fieldKey:ne,value:Pe}]),p({title:"Field saved",description:`${h0(ce)} ${We}.`})}catch(ne){throw p({title:"Save failed",description:ne instanceof Error?ne.message:"Could not save.",variant:"destructive"}),ne}finally{C(null)}}},[W,n,i,p,d]),pe=o.useCallback(async()=>{if(!d&&!(!T.applied&&T.skippedReason!==null)){A(!0);try{await W([{section:"improvements",field:"buildings",value:T.buildings}]),p({title:"Structure applied",description:"Scanned floors and rooms were written to the Improvements model."})}catch(ce){p({title:"Save failed",description:ce instanceof Error?ce.message:"Could not save.",variant:"destructive"})}finally{A(!1)}}},[T,W,p,d]),se=o.useCallback(async ce=>{const{entry:Pe,suggestion:We}=ce;if(We){if(O[Pe.uid]!==void 0){C(Pe.uid);try{await pe()}finally{C(null)}return}if(!(!Pe.home&&!ce.buildingScoped)){C(Pe.uid);try{const Re=await me([{status:ce,value:We.value,source:We.source,confidence:1}]);if(Re.written===0){p({title:"Not applied",description:Re.bridgeSkipped>0?"The structure already has a value for this field — edit it in the report editor.":"This field can't be accepted automatically."});return}p({title:"Field saved",description:`${h0(Pe)} set from ${ig[We.source].label}${ce.buildingScoped?" on the subject structure":""}.`})}catch(Re){p({title:"Save failed",description:Re instanceof Error?Re.message:"Could not save.",variant:"destructive"})}finally{C(null)}}}},[me,p,O,pe]),fe=o.useCallback((ce,Pe)=>{const We=VA(Pe,b);_({title:`Accept all in ${ce}`,plan:We})},[b]),ue=o.useMemo(()=>{const ce=[];for(const Pe of y)if(Pe.active){for(const We of Pe.subsections)if(We.active)for(const Re of We.entries){const ne=E.get(Re.uid);ne&&ce.push(ne)}}return ce},[y,E]),be=o.useMemo(()=>VA(ue,b,{minConfidence:h3}),[ue,b]),H=o.useCallback(ce=>{let Pe=0;const We=new Set;for(const Re of ce){if(We.has(Re.entry.uid))continue;We.add(Re.entry.uid);const ne=bT(Re);(ne==="suggested"||ne==="conflict"&&!M.has(Re.entry.uid))&&Pe++}return Pe},[M]),ye=o.useCallback(async()=>{if(!d&&D){z(!0);try{const ce=await me(D.plan.items);p({title:"Suggestions applied",description:`${ce.written} field(s) written.`+(D.plan.skippedConflicts>0?` ${D.plan.skippedConflicts} conflict(s) skipped — resolve them individually.`:"")+(ce.bridgeSkipped>0?` ${ce.bridgeSkipped} structure field(s) already had values and were left unchanged.`:"")}),_(null)}catch(ce){p({title:"Save failed",description:ce instanceof Error?ce.message:"Could not save.",variant:"destructive"})}finally{z(!1)}}},[D,me,p,d]),de=o.useCallback(async(ce,Pe)=>{if(d)return;const{entry:We}=ce;if(ce.buildingScoped){if(!Lc(Pe)){p({title:"Edit in the report",description:"This structure detail can be changed but not cleared from the checklist — use the report editor to remove it."});return}const Re=vD(b,We.uid,Pe,{overwrite:!0});if(!Re.applied)throw p({title:"Save failed",description:"This field can't be edited from the checklist.",variant:"destructive"}),new Error("building manifest value not applied");C(We.uid);try{await W([{section:"improvements",field:"buildings",value:Re.buildings}]),p({title:"Field saved",description:`${h0(We)} updated on the subject structure.`})}catch(ne){throw p({title:"Save failed",description:ne instanceof Error?ne.message:"Could not save.",variant:"destructive"}),ne}finally{C(null)}return}await Z(We,Pe,"updated","manual")},[Z,b,W,p,d]),ge=o.useCallback(async()=>
2{if(!d&&j){A(!0);try{await W([{section:"improvements",field:"buildings",value:[j]}]),le(!1),p({title:"Structure re-applied",description:"The report's Improvements model now matches the Boxli scan."})}catch(ce){p({title:"Save failed",description:ce instanceof Error?ce.message:"Could not save.",variant:"destructive"})}finally{A(!1)}}},[j,W,p,d]),Be=o.useRef(null),He=o.useCallback(ce=>{requestAnimationFrame(()=>{const Pe=Be.current;if(!Pe)return;const We=Array.from(Pe.querySelectorAll('[data-testid^="manifest-row-"]')),Re=We.findIndex(ne=>ne.getAttribute("data-testid")===`manifest-row-${ce}`);for(let ne=Re+1;ne<We.length;ne++){const Me=We[ne].querySelector('[data-testid^="select-value-"], [data-testid^="input-value-"]');if(Me){Me.focus(),Me.scrollIntoView({block:"nearest"});return}}})},[]),Ie=o.useCallback(ce=>{G(Pe=>({...Pe,[ce]:!0})),requestAnimationFrame(()=>{Be.current?.querySelector(`[data-testid="manifest-section-${aw(ce)}"]`)?.scrollIntoView({behavior:"smooth",block:"start"})})},[]);return f?e.jsxs("div",{className:"flex items-center gap-2 p-6 text-sm text-muted-foreground","data-testid":"manifest-loading",children:[e.jsx(za,{className:"h-4 w-4 animate-spin"})," Loading 3.6 report fields…"]}):v?e.jsx("div",{className:"p-6 text-sm text-muted-foreground","data-testid":"manifest-error",children:"Could not load the 3.6 report data for this order."}):e.jsxs("div",{ref:Be,className:"space-y-3 p-1","data-testid":"inspection-subject-manifest",children:[j&&(()=>{const ce=T.skippedReason==="existing-buildings"&&S3(b,j);return e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 flex items-start gap-3","data-testid":"manifest-structure-bridge",children:[e.jsx(Hh,{className:`h-4 w-4 mt-0.5 ${ce?"text-emerald-600":"text-violet-600"}`}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[ce?"Scanned structure applied":"Scanned structure available",ce&&e.jsx(kt,{variant:"outline",className:"text-[10px] bg-emerald-50 text-emerald-700 border-emerald-200","data-testid":"badge-structure-applied",children:"Applied"}),T.applied&&e.jsx(kt,{variant:"outline",className:"text-[10px] bg-violet-50 text-violet-700 border-violet-200","data-testid":"badge-structure-pending",children:"Not applied yet"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[s.length," level(s), ",s.reduce((Pe,We)=>Pe+We.rooms.length,0)," room(s) from the Boxli scan",ce?" are in the report's Improvements model (levels, rooms, bed/bath counts).":" can populate the Improvements model (levels, rooms, bed/bath counts)."]}),T.skippedReason==="existing-buildings"&&!ce&&e.jsx("div",{className:"text-xs text-amber-700 mt-1","data-testid":"manifest-structure-existing",children:"This report already has a structure in Improvements — merging never replaces it. Re-applying from the scan will replace the existing structure after you confirm."})]}),T.applied?e.jsx(De,{size:"sm",onClick:pe,disabled:F||d,title:d?"Edit lock held by another user":void 0,"data-testid":"button-apply-structure",children:F?e.jsx(za,{className:"h-3.5 w-3.5 animate-spin"}):"Apply to report"}):e.jsx(De,{size:"sm",variant:"outline",onClick:()=>le(!0),disabled:F||d,title:d?"Edit lock held by another user":void 0,"data-testid":"button-reapply-structure",children:"Re-apply from scan"})]})})(),e.jsx(xi,{open:V,onOpenChange:ce=>{F||le(ce)},children:e.jsxs(bi,{className:"max-w-md","data-testid":"dialog-reapply-structure",children:[e.jsxs($i,{children:[e.jsx(si,{children:"Re-apply scanned structure?"}),e.jsxs(pl,{children:["This replaces the structure currently in the report's Improvements model with the Boxli scan (",s.length," level(s), ",s.reduce((ce,Pe)=>ce+Pe.rooms.length,0)," room(s)). Any levels, rooms, or counts you edited in the report editor will be overwritten."]})]}),e.jsxs(eb,{children:[e.jsx(De,{variant:"outline",onClick:()=>le(!1),disabled:F,"data-testid":"button-cancel-reapply",children:"Cancel"}),e.jsx(De,{onClick:ge,disabled:F||d,"data-testid":"button-confirm-reapply",children:F?e.jsx(za,{className:"h-3.5 w-3.5 animate-spin"}):"Replace with scan"})]})]})}),e.jsxs("div",{className:"flex items-center gap-2","data-testid":"manifest-review-toolbar",children:[e.jsx(De,{size:"sm",variant:oe?"default":"outline",className:"h-7 px-2.5 text-xs",onClick:()=>ae(ce=>!ce),"data-testid":"button-toggle-attention-filter",children:oe?"Showing: needs my attention":"Show only what needs my attention"}),e.jsx("div",{className:"flex-1"}),be.items.length>0&&e.jsxs(De,{size:"sm",className:"h-7 px-2.5 text-xs",onClick:()=>_({title:"Accept all high-confidence suggestions",plan:be}),disabled:d,title:d?"Edit lock held by another user":void 0,"data-testid":"button-accept-all-high-confidence",children:["Accept all high-confidence (",be.items.length,")"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"manifest-jumper",children:y.map(ce=>e.jsx("button",{type:"button",className:`rounded-full border px-2 py-0.5 text-[11px] ${ce.active?"text-foreground
2/80 hover:bg-muted":"text-muted-foreground/50"}`,onClick:()=>Ie(ce.section),"data-testid":`button-jump-${aw(ce.section)}`,children:ce.section},ce.section))}),y.map(ce=>{const Pe=ce.subsections.flatMap(Le=>Le.entries.map(ut=>E.get(ut.uid)).filter(Boolean)),We=Pe.filter(Le=>Le.entry.home||Le.buildingScoped),Re=We.filter(Le=>Le.filled).length,ne=H(Pe),Me=ce.active?ce.subsections.filter(Le=>Le.active).flatMap(Le=>Le.entries.map(ut=>E.get(ut.uid)).filter(Boolean)):[],lt=VA(Me,b),Tt=ce.section===j2,je=R[ce.section]??Tt;return oe&&!Tt&&ne===0?null:e.jsxs("div",{className:`rounded-md border ${Tt?"border-violet-300 bg-violet-50/40":""}`,"data-testid":`manifest-section-${ce.section.replace(/\s+/g,"-").toLowerCase()}`,children:[e.jsxs("div",{className:`w-full flex items-center gap-2 px-3 py-2 sticky top-0 z-10 rounded-t-md ${Tt?"bg-violet-50":"bg-background"}`,children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 text-left flex-1 min-w-0",onClick:()=>G(Le=>({...Le,[ce.section]:!je})),"data-testid":`button-toggle-section-${ce.section.replace(/\s+/g,"-").toLowerCase()}`,children:[je?e.jsx(Rr,{className:"h-4 w-4"}):e.jsx(fo,{className:"h-4 w-4"}),e.jsxs("span",{className:"text-sm font-medium flex-1",children:[ce.section,Tt&&e.jsx("span",{className:"ml-2 text-[11px] font-normal text-muted-foreground",children:"These answers unlock other report questions"})]})]}),!ce.active&&e.jsx(kt,{variant:"outline",className:"text-[10px]","data-testid":`badge-na-${ce.section.replace(/\s+/g,"-").toLowerCase()}`,children:"Not applicable"}),ce.active&&ne>0&&e.jsxs(kt,{className:"text-[10px] bg-violet-100 text-violet-700 border-violet-200",variant:"outline","data-testid":`badge-attention-${ce.section.replace(/\s+/g,"-").toLowerCase()}`,children:[ne," to review"]}),ce.active&&lt.items.length>0&&e.jsxs(De,{size:"sm",variant:"outline",className:"h-6 px-2 text-[11px] shrink-0",onClick:()=>!d&&fe(ce.section,Me),disabled:d,title:d?"Edit lock held by another user":void 0,"data-testid":`button-accept-all-${ce.section.replace(/\s+/g,"-").toLowerCase()}`,children:["Accept all (",lt.items.length,")"]}),ce.active&&We.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground","data-testid":`text-fill-count-${ce.section.replace(/\s+/g,"-").toLowerCase()}`,children:[Re,"/",We.length," filled"]}),e.jsxs("span",{className:"text-xs text-muted-foreground/70",children:[Pe.length," fields"]})]}),je&&e.jsx("div",{className:"border-t divide-y",children:ce.subsections.map(Le=>e.jsxs("div",{children:[Le.subsection&&e.jsxs("div",{className:"px-3 py-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground bg-muted/40 flex items-center gap-2",children:[Le.subsection,!Le.active&&e.jsx(kt,{variant:"outline",className:"text-[10px] normal-case tracking-normal",children:"Not applicable"})]}),Le.entries.map(ut=>{const st=E.get(ut.uid);if(!st)return null;const Xt=bT(st),ua=M.has(ut.uid);return oe&&!Tt&&!(Xt==="suggested"||Xt==="conflict"&&!ua)?null:e.jsx(C3,{status:st,state:Xt,kept:ua,onKeep:()=>B(Oa=>new Set(Oa).add(ut.uid)),dimmed:!ce.active||!Le.active,accepting:U===ut.uid,structureAccept:O[ut.uid]!==void 0,inlineEditor:ce.active&&Le.active,reportHref:j3(t,ce.section,ut),onAccept:d?()=>{}:()=>se(st),onSave:d?()=>Promise.resolve():Oa=>de(st,Oa),readOnly:d,onAdvance:()=>He(ut.uid)},ut.uid)})]},Le.subsection||"__main"))})]},ce.section)}),e.jsx(xi,{open:!!D,onOpenChange:ce=>{!ce&&!$&&_(null)},children:e.jsxs(bi,{className:"max-w-lg","data-testid":"dialog-batch-accept-summary",children:[e.jsxs($i,{children:[e.jsx(si,{children:D?.title}),e.jsx(pl,{children:D&&D.plan.items.length>0?`${D.plan.items.length} field(s) will be filled from suggestions. Fields you already filled are never overwritten.`:"Nothing to apply — every suggestion is either a conflict or below the confidence bar."})]}),D&&D.plan.items.length>0&&e.jsx("div",{className:"max-h-72 overflow-y-auto space-y-1 pr-1",children:D.plan.items.map(ce=>e.jsxs("div",{className:"flex items-center gap-2 rounded border px-2 py-1.5 text-xs","data-testid":`row-batch-item-${ce.status.entry.uid}`,children:[e.jsx("span",{className:"flex-1 min-w-0 truncate font-medium",children:h0(ce.status.entry)}),e.jsx("span",{className:"truncate text-muted-foreground max-w-[10rem]",children:yT(ce.status.entry,ce.value)}),e.jsx(kt,{variant:"outline",className:`text-[10px] shrink-0 ${ig[ce.source].cls}`,children:ig[ce.source].label})]},ce.status.entry.uid))}),D&&(D.plan.skippedConflicts>0||D.plan.skippedLowConfidence>0)&&e.jsxs("div",{className:"text-xs text-muted-foreground","data-testid":"text-batch-skips",children:["Skipped: ",D.plan.skippedConflicts>0?`${D.plan.skippedConflicts} conflict(s) (resolve individually)`:null,D.plan.skippedConflicts>0&&D.plan.skippedLowConfidence>0?", ":null,D.plan.skippedLowConfidence>0?`${D.plan.skippedLowConfidence} below the confidence bar`:null,"."]}),e.jsxs(eb,{children:[e.jsx(De,{variant:"outline",onClick:()=>_(null),disabled:$,"data-testid":"button-cancel-batch-accept",children:"Cancel"}),e.jsx(De,{onClick:ye,disabled:$||d||!D||D.plan.items.length===0,"data-testid":"button-confirm-batch-accept",children:$?e.jsx(za,{className:"h-3.5 w-3.5 animate-spin"}):`Apply ${D?.plan.items.length??0} field(s)`})]})]})})]})}function I3(t){if(/Indicator$/.test(t.name))return{kind:"boolean"};const a=t.options&&t.options.length>0?t.options:Pr(t.name);return a&&a.length>0?{kind:"enum",options:a.map(s=>({token:s,label:Hs(t.name,s)}))}
2:/(Count|Measure|Year|Amount|Number|Percent)$/.test(t.name)?{kind:"number"}:{kind:"text"}}function yT(t,a){if(a==null||a==="")return"";if(typeof a=="boolean")return a?"Yes":"No";const s=String(a);return s==="true"?"Yes":s==="false"?"No":Hs(t.name,s)}function C3({status:t,state:a,kept:s,onKeep:r,dimmed:n,accepting:i,structureAccept:l,inlineEditor:c,reportHref:d,onAccept:p,onSave:u,onAdvance:m,readOnly:h}){const{entry:f,filled:v,currentValue:S,suggestion:N,agreedSuggestion:x}=t,y=!!f.home||t.buildingScoped,[b,j]=o.useState(!1),[T,O]=o.useState(""),E=o.useMemo(()=>I3(f),[f]),R=!!c&&y&&!N&&!Lc(S),G=()=>{const C=S??"";O(typeof C=="boolean"?C?"true":"false":String(C)),j(!0)},U=async C=>{let F=C.trim();if(F==="")F=null;else if(E.kind==="boolean")F=C==="true";else if(E.kind==="number"){const A=Number(C);F=Number.isFinite(A)?A:C.trim()}try{await u(F),j(!1),m?.()}catch{}};return e.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 text-xs hover:bg-muted/30 group ${n?"opacity-50":""}`,"data-testid":`manifest-row-${f.uid}`,children:[v?e.jsx(Bs,{className:"h-3.5 w-3.5 text-emerald-600 shrink-0"}):e.jsx(x5,{className:"h-3.5 w-3.5 text-muted-foreground/40 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-1.5",children:[e.jsx("span",{className:"truncate font-medium text-foreground/90",children:h0(f)}),f.requirement==="R"&&e.jsx("span",{className:"text-[10px] text-rose-500 shrink-0",title:"Required",children:"*"}),e.jsx(gr,{delayDuration:200,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(on,{className:"h-3 w-3 text-muted-foreground/40 shrink-0 cursor-help","data-testid":`info-${f.uid}`})}),e.jsxs(Wa,{side:"top",className:"max-w-[340px] text-xs",children:[e.jsx("div",{className:"font-mono text-[10px]",children:f.name}),f.conditionalityDetails&&e.jsxs("div",{className:"mt-1 text-muted-foreground",children:["Applies when: ",f.conditionalityDetails.replace(/^IF\s*/i,"")]}),!y&&e.jsx("div",{className:"mt-1 text-muted-foreground",children:"This detail is recorded on each structure or unit of the property, so it's answered in the report editor rather than this checklist."})]})]})}),a==="confirmed"&&e.jsxs(kt,{variant:"outline",className:"text-[10px] shrink-0 bg-emerald-50 text-emerald-700 border-emerald-200","data-testid":`badge-state-confirmed-${f.uid}`,title:x?`${ig[x.source].label} agrees with this value`:void 0,children:["Confirmed",x?` · ${ig[x.source].label}`:""]}),a==="suggested"&&e.jsx(kt,{variant:"outline",className:"text-[10px] shrink-0 bg-violet-50 text-violet-700 border-violet-200","data-testid":`badge-state-suggested-${f.uid}`,children:"Suggested"}),a==="conflict"&&e.jsx(kt,{variant:"outline",className:`text-[10px] shrink-0 ${s?"bg-muted text-muted-foreground":"bg-amber-50 text-amber-700 border-amber-200"}`,"data-testid":`badge-state-conflict-${f.uid}`,children:s?"Kept your value":"Conflict"})]}),(b||R)&&!h?e.jsxs("div",{className:"flex items-center gap-1.5","data-testid":`editor-${f.uid}`,children:[E.kind==="enum"?e.jsxs(sr,{value:T,onValueChange:C=>{O(C),U(C)},children:[e.jsx(rr,{className:"h-7 w-[190px] text-xs","data-testid":`select-value-${f.uid}`,children:e.jsx(or,{placeholder:"Choose…"})}),e.jsx(nr,{children:E.options.map(C=>e.jsx(vs,{value:C.token,className:"text-xs",children:C.label},C.token))})]}):E.kind==="boolean"?e.jsxs(sr,{value:T,onValueChange:C=>{O(C),U(C)},children:[e.jsx(rr,{className:"h-7 w-[110px] text-xs","data-testid":`select-value-${f.uid}`,children:e.jsx(or,{placeholder:"Choose…"})}),e.jsxs(nr,{children:[e.jsx(vs,{value:"true",className:"text-xs",children:"Yes"}),e.jsx(vs,{value:"false",className:"text-xs",children:"No"})]})]}):e.jsx(ze,{autoFocus:b,type:E.kind==="number"?"number":"text",className:"h-7 w-[190px] text-xs",value:T,onChange:C=>O(C.target.value),onKeyDown:C=>{C.key==="Enter"&&U(T),C.key==="Escape"&&j(!1)},"data-testid":`input-value-${f.uid}`}),E.kind!=="enum"&&E.kind!=="boolean"&&e.jsx(De,{size:"sm",className:"h-7 px-2 text-[11px]",disabled:i||h,onClick:()=>U(T),"data-testid":`button-save-${f.uid}`,children:i?e.jsx(za,{className:"h-3 w-3 animate-spin"}):"Save"}),b&&e.jsx(De,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>j(!1),"data-testid":`button-cancel-${f.uid}`,children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]}):e.jsxs(e.Fragment,{children:[Lc(S)?y&&!h?e.jsx("button",{type:"button",className:"max-w-[200px] truncate text-foreground
2/80 hover:underline decoration-dotted underline-offset-2 text-left",onClick:G,title:"Click to edit","data-testid":`text-current-${f.uid}`,children:yT(f,S)}):e.jsx("span",{className:"max-w-[200px] truncate text-muted-foreground","data-testid":`text-current-${f.uid}`,children:yT(f,S)}):y&&!h?!N&&e.jsx("button",{type:"button",className:"text-muted-foreground/50 hover:text-foreground",onClick:G,"data-testid":`button-edit-${f.uid}`,children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ru,{className:"h-3 w-3"})," Add"]})}):null,!y&&!n&&e.jsxs("a",{href:d,className:"inline-flex items-center gap-1 text-[10px] text-muted-foreground/70 hover:text-foreground shrink-0 underline decoration-dotted underline-offset-2",title:"Recorded on each structure or unit — open the report editor to answer it","data-testid":`text-report-only-${f.uid}`,children:[e.jsx(rf,{className:"h-3 w-3"}),"Open in report editor"]}),y&&!h&&Lc(S)&&e.jsx("button",{type:"button",className:"text-muted-foreground/60 hover:text-foreground",onClick:G,title:"Edit value","data-testid":`button-edit-${f.uid}`,children:e.jsx(Ru,{className:"h-3 w-3"})}),N&&e.jsxs(e.Fragment,{children:[e.jsx(kt,{variant:"outline",className:`text-[10px] shrink-0 ${ig[N.source].cls}`,children:ig[N.source].label}),e.jsx("span",{className:"max-w-[140px] truncate","data-testid":`text-suggestion-${f.uid}`,children:N.displayValue??String(N.value)}),(N.photoUrls?.length??0)>0&&e.jsx("span",{className:"inline-flex items-center gap-1 shrink-0",children:Array.from(new Set(N.photoUrls)).slice(0,4).map((C,F)=>e.jsx("a",{href:C,target:"_blank",rel:"noreferrer",className:"text-muted-foreground/50 hover:text-foreground",title:`Evidence photo ${F+1}`,"data-testid":`link-evidence-${f.uid}-${F}`,children:e.jsx(rf,{className:"h-3 w-3"})},C))}),N.snippet&&e.jsx(gr,{delayDuration:200,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(on,{className:"h-3 w-3 text-rose-400/70 shrink-0 cursor-help","data-testid":`snippet-${f.uid}`})}),e.jsx(Wa,{side:"top",className:"max-w-[340px] text-xs",children:e.jsxs("span",{className:"italic",children:["“",N.snippet,"”"]})})]})}),t.buildingScoped&&t.conflict?e.jsx(kt,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-50 text-amber-700 border-amber-200","data-testid":`badge-conflict-${f.uid}`,children:"Differs from structure"}):t.conflict&&s?null:t.conflict?e.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[e.jsx(De,{size:"sm",variant:"outline",className:"h-6 px-2 text-[11px]",disabled:i||h||!f.home&&!t.buildingScoped&&!l,title:h?"Edit lock held by another user":void 0,onClick:p,"data-testid":`button-use-suggested-${f.uid}`,children:i?e.jsx(za,{className:"h-3 w-3 animate-spin"}):"Use suggested"}),e.jsx(De,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[11px] text-muted-foreground",disabled:i||h,title:h?"Edit lock held by another user":void 0,onClick:r,"data-testid":`button-keep-mine-${f.uid}`,children:"Keep mine"})]}):e.jsx(De,{size:"sm",variant:"outline",className:"h-6 px-2 text-[11px]",disabled:i||h||!f.home&&!t.buildingScoped&&!l,title:h?"Edit lock held by another user":void 0,onClick:p,"data-testid":`button-accept-${f.uid}`,children:i?e.jsx(za,{className:"h-3 w-3 animate-spin"}):"Accept"}),y&&!h&&!Lc(S)&&e.jsx("button",{type:"button",className:"text-muted-foreground/60 hover:text-foreground",onClick:G,title:"Enter a different value","data-testid":`button-edit-${f.uid}`,children:e.jsx(Ru,{className:"h-3 w-3"})})]})]})]})}async function R3(t,a,s){const r=AD(a??[]);if(!r)return"no-structure";try{const n=await Zn(`/api/uad36/prefill/${t}`),i=E0(n?.sections??{}),l=jD(i,r);return l.applied?(await Zn(`/api/uad36/section-attachments/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({patches:[{section:"improvements",field:"buildings",value:l.buildings}]}),retryTransientErrors:!0}),s?.invalidateQueries({queryKey:[`/api/uad36/prefill/${t}`,"inspection-manifest"]}),"applied"):"skipped-existing"}catch{return s?.invalidateQueries({queryKey:[`/api/uad36/prefill/${t}`,"inspection-manifest"]}),"failed"}}const E3=["TotalSalesConcessionAmount","SalesContractDate"],w3=new Set(["water","dwelling","units","quality","outbuilding"]);function $I(t){return t!==void 0&&w3.has(t)}const hd=[{id:"generalInfo",title:"General Information",fields:["proximity","listPrice","listingStatus","daysOnMarket","attachedDetached"]},{id:"siteInfo",title:"Site",fields:[],uad36Only:!0},{id:"general",title:"General Information — Existing",fields:["dataSource","mlsNumber","salePrice","salePricePerGLA","saleType","financing","concessions","financingConcessions","dateOfSale","leaseholdFeeSimple"]},{id:"project",title:"Project Information",fields:[],optional:!0,uad36Only:!0},{id:"site",title:"Site — Existing",fields:["neighborhoodName","location","site","view"]},{id:"water",title:"Water Frontage",fields:[],optional:!0,autoOnly:!0},{id:"dwelling",title:"Dwelling(s)",fields:["yearBuilt","constructionMethod","design","functionalUtility","heatingCooling"]},{id:"energy",title:"Energy Efficient and Green Features",fields:["energyEfficient"],optional:!0},{id:"units",title:"Unit(s)",fields:["aboveGrade","gla","basement","belowGrade"]},{id:"quality",title:"Quality and Condition",fields:["interiorQuality","exteriorQuality"]},{id:"overallQc",title:"Overall Quality and Condition",caption:"(Ratings: 1-6, 1 is highest)",fields:["qualityCondition"]},{id:"amenities",title:"Property Amenities",fields:["porchPatioDeck"],optional:!0},{id:"vehicle",title:"Vehicle Storage",fields:["garageCarport"]},{id:"outbuilding",title:"Outbuilding",fields:[],optional:!0,autoOnly:!0}],ID=hd.filter(t=>t.id!=="general"&&t.id!=="site"&&!$I(t.id)).map(t=>
2t.id==="generalInfo"?{...t,fields:["dataSource","proximity","listPrice","listingStatus","salePrice","saleType","dateOfSale","daysOnMarket","attachedDetached"]}:t),P3=hd.map(t=>t.id==="generalInfo"?{...t,fields:t.fields.filter(a=>a!=="attachedDetached")}:t.id==="dwelling"?{...t,fields:["attachedDetached",...t.fields]}:t);hd.filter(t=>t.optional).map(t=>t.id);const CD=[{id:"dataSourceMls",label:"Data Source · MLS #",fields:["dataSource","mlsNumber"]},{id:"dwellingType",label:"Constr · Design",fields:["constructionMethod","design"],adjustmentOwner:"design"}],O3=(()=>{const t={};for(const a of CD)for(const s of a.fields)t[s]=a;return t})(),RD=(()=>{const t={};for(const a of hd)for(const s of a.fields)t[s]=a.id;return t})();function L3(t){return $I(RD[t])}function D3(t,a="legacy"){if(a==="urar36"){if(L3(t))return;if(ID.find(s=>s.id==="generalInfo")?.fields.includes(t))return"generalInfo";if(t==="location"||t==="view"||hd.find(s=>s.id==="general")?.fields.includes(t)||hd.find(s=>s.id==="site")?.fields.includes(t))return}return RD[t]}function ED(t,a){if(Xh(t,a)||a&&$I(ST[a]))return!0;if(!t)return!1;if(II(t)||Nv(t)||/^(?:Dwelling|Unit|Adu)\d*_/.test(t)||/^(?:wizard_qc_(?:ext|int|adu|other|kitchen)_|(?:Structure|Unit|Adu)\d*_)/.test(t)||/^(?:Interior|Exterior)(?:Quality|Condition)RatingCode$/.test(t))return!0;const s=vv[t];return s!==void 0&&(s.sectionId==="Dwelling(s)"||s.sectionId==="Unit(s)"||s.sectionId==="Quality and Condition"||s.sectionId==="Outbuildings")}const k3=new Set(["PrivateAccessIndicator","BodyOfWaterType","BodyOfWaterTypeOtherDescription","BodyOfWaterName","WaterAccessDepthType","WaterAccessDepthTypeOtherDescription","WaterFrontageTotalLengthLinearMeasure","WaterfrontFeatureType","WaterfrontFeatureTypeOtherDescription","WaterfrontDevelopmentRightsIndicator"]);function M3(t){return/^AmenityType_/.test(t)||/^AmenityCount_/.test(t)||t==="AmenityTypeOtherDescription"||t==="SwimmingPoolFeatureType"||t==="SwimmingPoolFeatureTypeOtherDescription"}const ST={"General Information":"general",Site:"site","Water Frontage":"water","Dwelling(s)":"dwelling","Energy Efficient and Green Features":"energy","Unit(s)":"units","Quality and Condition":"quality","Property Amenities":"amenities","Project Information":"project","Vehicle Storage":"vehicle",Outbuilding:"outbuilding"};function Dh(t,a,s="legacy"){if(t&&!(s==="urar36"&&Xh(t,a))){if(s==="urar36"&&E3.includes(t))return"generalInfo";if(s==="urar36"&&a==="General Information"){const r=vv[t];return r&&r.inclusion!=="ALW"&&r.inclusion!=="ALW_REL"?"generalInfo":void 0}if(!(s==="urar36"&&ED(t,a))){if(II(t)||Nv(t))return"outbuilding";if(k3.has(t))return"water";if(M3(t))return"amenities";if(/(?:Interior|Exterior)(?:Quality|Condition)RatingCode$/.test(t)||t.startsWith("wizard_qc_ext_")||t.startsWith("wizard_qc_int_")||t.startsWith("wizard_qc_adu_qual_")||t.startsWith("wizard_qc_adu_cond_")||t.startsWith("wizard_qc_other_")||t.startsWith("wizard_qc_kitchen_"))return"quality";if(a==="General Information")return s==="urar36"?void 0:"general";if(a==="Site")return s==="urar36"?"siteInfo":"site";if(a&&ST[a])return ST[a]}}}const F3=new Set(["ExteriorQualityRatingCode","ExteriorConditionRatingCode","InteriorQualityRatingCode","InteriorConditionRatingCode","SiteInfluenceType","BodyOfWaterType","BodyOfWaterName","WaterAccessDepthType","WaterFrontageTotalLengthLinearMeasure","WaterfrontFeatureType","SwimmingPoolFeatureType","RenewableEnergyComponentType","GreenCertificationName","GreenCertificationLevelName","EfficiencyRatingName","EfficiencyRatingScoreValue"]);function kb(t){return t?/Indicator$/.test(t)||/OtherDescription$/.test(t)?!0:F3.has(t):!1}function _3(t){return t?c_(t):!1}const U3=new Set(["ViewType","ViewRangeType","ViewTypeOtherDescription","Vie
2wRangeTypeOtherDescription","HeatingFuelType","HeatingSystemTypeOtherDescription","HeatingFuelTypeOtherDescription","CoolingSystemTypeOtherDescription","HeatingSystemExistsIndicator","CoolingSystemExistsIndicator","AmenityType","AmenityTypeOtherDescription","AmenityCount","PropertyStructureBuiltYear","PropertyStructureBuiltYearEstimatedIndicator","OverallQualityRatingCode","OverallConditionRatingCode","ExteriorQualityRatingCode","ExteriorConditionRatingCode","InteriorQualityRatingCode","InteriorConditionRatingCode","ImprovementComponentQualitySummaryDescription","ImprovementComponentConditionSummaryDescription","OverallBathroomsQualityDescription","RoomQualitySummaryDescription","ImprovementComponentConditionStatusType","CarStorageType","CarStorageAreaMeasure","CarStorageAttachmentType","CarStorageTypeOtherDescription","ParkingSpacesCount","ProjectParkingSpaceAssignmentType","TenOrMoreParkingSpacesIndicator","ImprovedSurfaceMaterialType","ImprovedSurfaceMaterialTypeOtherDescription","TotalRoomCount","RoomType","RoomUpdateStatusType","UnitStandardAboveGradeFinishedAreaMeasure","UnitStandardBelowGradeFinishedAreaMeasure","UnitBelowGradeUnfinishedAreaMeasure","FunctionalIssueType","FunctionalIssueTypeOtherDescription","ImprovementType","ArchitecturalDesignCategoryType","ArchitecturalDesignCategoryTypeOtherDescription","StructuralDesignType","StructuralDesignTypeOtherDescription","MortgageType","MortgageTypeOtherDescription","NoFinancingTransactionIndicator","SalesConcessionIndicator","TotalSalesConcessionAmount","SalesConcessionAmountKnownIndicator","SaleType","SaleTypeOtherDescription","ContractAmountUnknownIndicator","ContractDateUnknownIndicator","PropertyEstateTypeOtherDescription","AppraisedIndicator","OwnershipTransferTransactionAmount","SalePriceNetTotalAdjustmentAmount"]),wD=[{rowId:"catalog_neighborhood_name",label:"Neighborhood Name",inputType:"text",group:"General Information",uad36Element:"NeighborhoodName"},{rowId:"catalog_parcel_number",label:"Parcel Number",inputType:"text",group:"General Information",uad36Element:"AssessorParcelIdentifier"},{rowId:"catalog_subdivision",label:"Subdivision",inputType:"text",group:"General Information"},{rowId:"catalog_school_district",label:"School District",inputType:"text",group:"General Information"},{rowId:"catalog_zoning",label:"Zoning",inputType:"text",group:"Site",uad36Element:"SiteZoningComplianceType"},{rowId:"catalog_census_tract",label:"Census Tract",inputType:"text",group:"General Information",uad36Element:"CensusTractIdentifier"},{rowId:"catalog_map_reference",label:"Map Reference",inputType:"text",group:"General Information",uad36Element:"MapReferenceIdentifier"},{rowId:"catalog_view",label:"View",inputType:"text",group:"Site",builtInKey:"view",uad36Element:"ViewType"},{rowId:"catalog_topography",label:"Topography",inputType:"text",group:"Site",uad36Element:"TopographyType"},{rowId:"catalog_hazard_zone",label:"Hazard Zone",inputType:"text",group:"Site",uad36Element:"HazardZoneType"},{rowId:"catalog_flood_zone",label:"Flood Zone",inputType:"text",group:"Site",uad36Element:"SiteFeatureType"},{rowId:"catalog_easements",label:"Easements",inputType:"text",group:"Site",uad36Element:"EasementType"},{rowId:"catalog_lot_size",label:"Lot Size",inputType:"number",group:"Site",builtInKey:"site",uad36Element:"LotSizeAreaMeasure"},{rowId:"catalog_utilities",label:"Utilities",inputType:"text",group:"Site",uad36Element:"UtilityType"},{rowId:"catalog_site_influences",label:"Site Influences",inputType:"text",group:"Site",uad36Element:"SiteInfluenceType"},{rowId:"catalog_street_access",label:"Street Access",inputType:"text",group:"Site",uad36Element:"StreetAccessType"},{rowId:"catalog_waterfront",label:"Waterfront Features",inputType:"text",group:"Water Frontage",uad36Element:"WaterfrontFeatureType"},{rowId:"catalog_body_of_water",label:"Body of Water",inputType:"text",group:"Water Frontage",uad36Element:"BodyOfWaterType"},{rowId:"catalog_roof_type",label:"Roof Type",inputType:"text",group:"Dwelling(s)",uad36Element:"RoofMaterialType"},{rowId:"catalog_exterior_walls",label:"Exterior Walls",inputType:"text",group:"Dwelling(s)",uad36Element:"WallMaterialType"},{rowId:"catalog_foundation",label:"Foundation",inputType:"text",group:"Dwelling(s)",uad36Element:"FoundationType"},{rowId:"catalog_heating_cooling",label:"Heating / Cooling",inputType:"text",group:"Dwelling(s)",builtInKey:"heatingCooling",uad36Element:"HeatingSystemType"},{rowId:"catalog_porch_deck",label:"Porch / Deck / Patio",inputType:"text",group:"Property Amenities",builtInKey:"porchPatioDeck",uad36Element:"AmenityType"},{rowId:"catalog_fireplace",label:"Fireplace",inputType:"text",group:"Property Amenities",uad36Element:"AmenityType"},{rowId:"catalog_pool_spa",label:"Pool / Spa",inputType:"text",group:"Property Amenities",uad36Element:"SwimmingPoolFeatureType"},{rowId:"catalog_outbuilding",label:"Outbuilding / ADU",inputType:"text",group:"Outbuilding",uad36Element:"OutbuildingType"},{rowId:"catalog_construction_method",label:"Construction Method",inputType:"text",group:"Dwelling(s)",uad36Element:"ConstructionMethodType"},{rowId:"catalog_architectural_design",label:"Architectural Design",inputType:"text",group:"Dwelling(s)",builtInKey:"design",uad36Element:"ArchitecturalDesignCategoryType"},{rowId:"catalog_attachment_type",label:"Attachment Type",inputType:"text",group:"Dwelling(s)",uad36Element:"AttachmentType"},{rowId:"catalog_amenities",label:"Amenities",inputType:"text",group:"Property Amenities",uad36Element:"AmenityType"},{rowId:"catalog_manufactured_home",label:"Manufactured Home Type",inputType:"text",group:"Dwelling(s)",uad36Element:"ManufacturedHomeWidthType"},{rowId:"catalog_energy_features",label:"Energy Efficient Features",inputType:"text",group:"Energy Efficient and Green Features",builtInKey:"energyEfficient",uad36Element:"EfficiencyRatingName"},{rowId:"catalog_solar",label:"Solar / Renewable Energy",inputType:"text",group:"Energy Efficient and Green Features",uad36Element:"RenewableEnergyComponentType"},{rowId:"catalog_green_cert",label:"Green Certification",inputType:"text",group:"Energy Efficient and Green Features",uad36Element:"GreenCertificationName"},{rowId:"catalog_disaster_mitigation",label:"Disaster Mitigation Features",inputType:"text",group:"Quality and Condition",uad36Element:"DisasterMitigationFeatureType"},{rowId:"catalog_accessibility",label:"Accessibility Features",inputType:"text",group:"Quality and Condition",uad36Element:"Acce
2ssibilityFeatureType"},{rowId:"catalog_environmental_conditions",label:"Environmental Conditions",inputType:"text",group:"Site",uad36Element:"EnvironmentalConditionType"},{rowId:"catalog_functional_issues",label:"Functional Issues",inputType:"text",group:"Quality and Condition",builtInKey:"functionalUtility",uad36Element:"FunctionalIssueType"},{rowId:"catalog_restrictions",label:"Deed Restrictions",inputType:"text",group:"Site",uad36Element:"RestrictionType"},{rowId:"catalog_concessions",label:"Concessions",inputType:"text",group:"General Information",builtInKey:"financingConcessions",uad36Element:"TotalSalesConcessionAmount"},{rowId:"catalog_financing_type",label:"Financing Type",inputType:"text",group:"General Information",builtInKey:"financingConcessions",uad36Element:"MortgageType"},{rowId:"catalog_days_on_market",label:"Days on Market",inputType:"number",group:"General Information",uad36Element:"DaysOnMarketCount"},{rowId:"catalog_list_price",label:"List Price",inputType:"number",group:"General Information",uad36Element:"FinalListPriceAmount"},{rowId:"catalog_listing_date",label:"Listing Date",inputType:"date",group:"General Information",uad36Element:"ListingStatusType"},{rowId:"catalog_prior_sale_price",label:"Prior Sale Price",inputType:"number",group:"General Information",builtInKey:"dateOfSale",uad36Element:"OwnershipTransferTransactionAmount"},{rowId:"catalog_prior_sale_date",label:"Prior Sale Date",inputType:"date",group:"General Information",builtInKey:"dateOfSale",uad36Element:"OwnershipTransferDate"},{rowId:"catalog_sale_price_per_gla",label:"Sale Price / GLA",inputType:"number",group:"General Information",uad36Element:"PricePerTotalStandardAboveGradeFinishedAreaAmount"},{rowId:"catalog_property_rights",label:"Property Rights / Estate",inputType:"text",group:"General Information",builtInKey:"leaseholdFeeSimple",uad36Element:"PropertyEstateType"},{rowId:"catalog_notes",label:"Notes",inputType:"text",group:"General Information",uad36Element:"SalesComparisonCommentDescription"}],mb=wD.filter(t=>!t.builtInKey),BI=[{rowId:"HomeownerResponsibleForExteriorMaintenanceIndicator",label:"Homeowner Responsible for Exterior Maintenance",group:"Quality and Condition",inputType:"boolean"},{rowId:"ProjectName",label:"Project Name | Same Project as Subject",group:"Project Information",inputType:"text"},{rowId:"AssociationChargeAmount",label:"Monthly Fee",group:"Project Information",inputType:"number"},{rowId:"ProjectCommonAmenityType",label:"Common Amenities/Services",group:"Project Information",inputType:"text"},{rowId:"AssociationSpecialAssessmentStatusType",label:"Special Assessments",group:"Project Information",inputType:"text"}],PD=[],xh=new Map([["RenewableEnergyComponentType","RenewableEnergyComponentType"],["GreenCertificationName","GreenCertificationName"],["EfficiencyRatingName","EfficiencyRatingName"],["catalog_solar","RenewableEnergyComponentType"],["catalog_green_cert","GreenCertificationName"],["catalog_energy_features","EfficiencyRatingName"]]),V3=["RenewableEnergyComponentExistsIndicator","RenewableEnergyComponentTypeOtherDescription","GreenCertificationExistsIndicator","GreenCertificationLevelName","EfficiencyRatingExistsIndicator","EfficiencyRatingScoreValue"],OD=["BodyOfWaterType","BodyOfWaterTypeOtherDescription","PrivateAccessIndicator","BodyOfWaterName","WaterAccessDepthType","WaterAccessDepthTypeOtherDescription","WaterFrontageTotalLengthLinearMeasure","WaterfrontFeatureType","WaterfrontFeatureTypeOtherDescription","WaterfrontDevelopmentRightsIndicator"],L
2D=[...cd.map(t=>d_(t)),"SwimmingPoolFeatureType","SwimmingPoolFeatureTypeOtherDescription"],ag=["BedroomCount","FullBathroomCount","HalfBathroomCount","LivingUnitFloorNumber"],PN=["NoFinancingTransactionIndicator","MortgageType"],zI=["SalesContractAmount","SalesContractDate","TotalSalesConcessionAmount"],DD=[...PN,"ContractPrice","TotalSalesConcessionAmount","SalesContractDate","PropertyEstateType"],$3="General Information",X0=["LotSizeAreaMeasure","HazardZoneType"],kD=["HeatingSystemType"],B3=new Set([...PD,...V3,...OD,...LD,...ag,...PN,...zI,...X0,...kD,"ProjectName","AssociationChargeAmount","ProjectCommonAmenityType","AssociationSpecialAssessmentStatusType"]);function MD(t,a=!1,s=!1,r=!1){const n=new Set(["LandOwnedInCommonIndicator","NeighborhoodName","SiteZoningComplianceType","LotSizeAreaMeasure","HazardZoneType"]);return(t?[...ab.filter(l=>!l.pickerHidden&&!Xh(l.rowId,l.group)&&!U3.has(l.rowId)&&l.rowId!=="AttachmentType"&&(!B3.has(l.rowId)||l.rowId==="LotSizeAreaMeasure"||l.rowId==="HazardZoneType")),...BI]:mb).filter(l=>!(t&&Xh(l.rowId,l.group))&&!(r&&!n.has(l.rowId)&&ED(l.rowId,l.group))&&!(a&&l.group===$3)&&!(s&&l.group==="Site"&&l.rowId!=="LandOwnedInCommonIndicator"&&l.rowId!=="NeighborhoodName"&&l.rowId!=="SiteZoningComplianceType"&&l.rowId!=="LotSizeAreaMeasure"&&l.rowId!=="HazardZoneType"))}function og(t){const a=ab.find(r=>r.rowId===t);if(a)return a.group;const s=BI.find(r=>r.rowId===t);return s?s.group:wD.find(r=>r.rowId===t)?.group}const FD=/^(no|none|n\/a|na|false|0)\.?$/i;function mo(t){if(t==null)return null;const a=String(t).trim();return!a||FD.test(a)?null:a}function Vf(t){return t===!0||t==="Y"||t==="Yes"||t==="yes"||t==="true"}function z3(t){if(t==null||t==="")return null;const a=typeof t=="number"?t:parseFloat(String(t).replace(/[^0-9.]/g,""));return Number.isFinite(a)&&a>0?a:null}const q3=/\b(barn|shed|sheds|workshop|outbuilding|out building|guest house|guesthouse|carriage house|detached studio|pole barn|stable|greenhouse)\b/i,sw=/\b(waterfront|water front|lakefront|lake front|riverfront|river front|oceanfront|ocean front|beachfront|beach front|canal front|bayfront|bay front)\b/i,wx=/\b(porch|deck|decks|patio|balcony|lanai|veranda|pergola|gazebo|cabana|outdoor kitchen|outdoor living|summer kitchen|fire pit|firepit|fireplace|hot tub|sauna|sport court|tennis court|basketball court|pickleball|boat dock|dock|boat slip|boat lift|outdoor shower|bbq|built-in barbecue|barbecue)\b/i;function Y3(...t){const a=new Set,s=[],r=new RegExp(wx.source,"gi");for(const n of t)if(n)for(const i of String(n).matchAll(r)){const l=i[0].toLowerCase();a.has(l)||(a.add(l),s.push(l))}return s}function _D(t,a,s){const r=t??{},n=a??{},i=G3(s),l={};{const c=mo(r.waterfront)??mo(n.waterfront)??(Vf(r.waterfrontYN)||Vf(n.waterfrontYN)?"Yes":null),d=mo(r.lotFeatures)&&sw.test(String(r.lotFeatures))||mo(r.exteriorFeatures)&&sw.test(String(r.exteriorFeatures));(c||d)&&(l.water={source:mo(r.waterfront)||Vf(r.waterfrontYN)||d?"MLS":"PublicRecord",reason:"Waterfront flagged in MLS listing",detail:["waterfront"],seeds:{}})}{const c=mo(r.greenFeatures)??mo(n.greenFeatures),d=Vf(r.solarPanelYN)||(mo(r.solarPanelYN)?/^y/i.test(String(r.solarPanelYN)):!1),p=z3(r.hersIndex);if(c||d||p!=null){const u={};d&&(u.RenewableEnergyComponentExistsIndicator="Yes"),p!=null&&(u.EfficiencyRatingExistsIndicator="Yes",u.EfficiencyRatingScoreValue=String(p));const m=[];d&&m.push("solar panels"),p!=null&&m.push("HERS score"),c&&m.length===0&&m.push("green features"),l.energy={source:"MLS",reason:d?"Solar panels in MLS listing":p!=null?"HERS score in MLS listing":"Green features in MLS listing",detail:m,seeds:u}}}{const c=mo(r.pool)??mo(r.poolFeatures)??(Vf(r.poolYN)?"Yes":null)??mo(n.pool),d=Vf(r.spaYN)||!!mo(r.spaFeatures),p=mo(r.exteriorFeatures)&&wx.test(String(r.exteriorFeatures))||mo(r.patioAndPorchFeatures)&&wx.test(String(r.patioAndPorchFeatures))||mo(n.exteriorFeatures)&&wx.test(String(n.exteriorFeatures));if(c||d||p){const u=!!c||d||mo(r.exteriorFeatures)&&wx.test(String(r.exteriorFeatures))||mo(r.patioAndPorchFeatures)&&wx.test(String(r.patioAndPorchFeatures)),m=[];c&&m.push("pool"),d&&m.push("spa");for(const h of Y3(mo(r.exteriorFeatures),mo(r.patioAndPorchFeatures),mo(n.exteriorFeatures)))m.includes(h)||m.push(h);l.amenities={source:u?"MLS":"PublicRecord",reason:c?"Pool in MLS listing":d?"Spa in MLS listing":"Outdoor amenity in exterior features",detail
2:m,seeds:{}}}}{const c=mo(r.otherStructures),d=mo(n.otherStructures),p=c??d,u=mo(r.exteriorFeatures)&&q3.test(String(r.exteriorFeatures));if(p||u){const m=p?Q3(p):[],h={};m.forEach((v,S)=>{v.type&&(h[SL(S+1)]=v.type),v.otherDescription&&(h[u_(S+1)]=v.otherDescription)});const f=m.length?m.map(v=>v.type==="Other"&&v.otherDescription?v.otherDescription:v.type??"outbuilding"):["outbuilding"];l.outbuilding={source:c||u?"MLS":"PublicRecord",seeds:h,instances:m,detail:f,reason:p?`Other structures in ${c?"MLS listing":"public record"} (${p})`:"Outbuilding mentioned in MLS exterior features"}}else Vf(i?.detachedStructures)&&(l.outbuilding={source:"Inspection",reason:"Detached structure reported by inspection",detail:["detached structure"],seeds:{},instances:[{type:null}]})}return l}function G3(t){if(!t)return null;const a=t.payload??t,s=a?.boxli?.normalized?.fields??a?.normalized?.fields??null;if(!Array.isArray(s)||s.length===0)return null;const r={};for(const n of s)n&&typeof n.fieldKey=="string"&&(r[n.fieldKey]=n.value);return Object.keys(r).length>0?r:null}const H3={barn:"Barn",polebarn:"Barn",boathouse:"Boathouse",bunkhouse:"Bunkhouse",kennel:"EnclosedKennel",kenneldogrun:"EnclosedKennel",greenhouse:"Greenhouse",guesthouse:"GuestHouse",carriagehouse:"GuestHouse",ridingarena:"IndoorRidingArena",indoorridingarena:"IndoorRidingArena",arena:"IndoorRidingArena",poolhouse:"PoolHouse",cabana:"PoolHouse",shed:"Shed",storageshed:"Shed",storage:"Shed",silo:"Silo",grainstorage:"Silo",stable:"Stable",corral:"Stable",studio:"Studio",workshop:"Workshop",shop:"Workshop"},W3=/\b(garage|carport|rv|boat\s*port|none|n\/a)\b/i;function K3(t){return t.toLowerCase().replace(/\(s\)/g,"").replace(/[^a-z]/g,"").replace(/s$/,"")}function Q3(t){const a=[];for(const s of String(t).split(/[,;]/)){const r=s.trim();if(!r||FD.test(r)||W3.test(r))continue;const n=H3[K3(r)];n?a.push({type:n}):a.push({type:"Other",otherDescription:r})}return a}function UD(t){return t==="PublicRecord"?"Public Record":t==="Inspection"?"Inspection":"MLS"}const rw=2;function Z3(t){const a=t.detail??[];if(a.length===0)return"";const s=a.slice(0,rw).join(", "),r=a.length-rw;return r>0?`${s} +${r} more`:s}function VD(t){const a=Z3(t),s=`found in ${UD(t.source)}`;return a?`${a} ${s}`:s}function $D(t){const a=t.detail??[];return a.length===0?t.reason:`Found in ${UD(t.source)}: ${a.join(", ")}`}function Mb(t,a){if(!a)return t;const s=Object.values(a).flatMap(i=>i?Object.entries(i.seeds??{}).map(([l,c])=>[l,c,i.source]):[]);if(s.length===0)return t;const r=i=>i!=null&&i.value!=null&&i.value!==""&&i.value!=="–";let n=null;for(const[i,l,c]of s){const d=l!=null?String(l).trim():"";if(!d)continue;const p=`catalog_${i}_auto`,u=n??t.fields;if(r(u[i])||r(u[p]))continue;n||(n={...t.fields});const m={value:d,source:c,hasConflict:!1,isVerified:!1};n[i]=m,n[p]={...m}}return n?{...t,fields:n}:t}const Fb="__add__";function $f(t){return t==null?"":String(t).trim()}function J3({getValue:t,setValue:a,subjectMode:s=!1,disabled:r,testIdPrefix:n}){const i=Rm(t("ViewType")),l=o.useMemo(()=>Pr("ViewType")??[],[]),c=o.useMemo(()=>Pr("ViewRangeType")??[],[]),d=o.useMemo(()=>Pr("ViewValueMarketabilityImpactType")??[],[]),p=$f(t(uT)),u=h=>{for(const f of MU(i,h,t))a(f.key,f.value);!h.includes("Other")&&$f(t("ViewTypeOtherDescription"))&&a("ViewTypeOtherDescription",""),a("ViewType",h.join("|"))},m=l.filter(h=>!i.includes(h));return e.jsxs("div",{className:"space-y-1.5",children:[i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:i.map(h=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-slate-100 px-1.5 py-0.5 text-[11px] text-slate-700","data-testid":`${n}-chip-${h}`,children:[Dc("ViewType",h),!r&&e.jsx("button",{type:"button",className:"text-slate-400 hover:text-slate-700",onClick:()=>u(i.filter(f=>f!==h)),"data-testid":`${n}-chip-remove-${h}`,"aria-label":`Remove ${h}`,children:e.jsx(ur,{className:"h-3 w-3"})})]},h))}),!r&&m.length>0&&e.jsxs(sr,{value:void 0,onValueChange:h=>{h!==Fb&&!i.includes(h)&&u([...i,h])},children:[e.jsx(rr,{className:"h-7 text-xs","data-testid":`${n}-add-view`,children:e.jsx(or,{placeholder:"Add view…"})}),e.jsx(nr,{children:m.map(h=>e.jsx(vs,{value:h,children:Dc("ViewType",h)},h))})]},`add-${i.length}`),i.includes("Other")&&e.jsx(ze,{type:"text",value:$f(t("ViewTypeOtherDescription")),onChange:h=>a("ViewTypeOtherDescription",h.target.value),maxLength:LL,readOnly:r,disabled:r,placeholder:"Describe view (Other)…",className:"h-7 text-xs","data-testid":`${n}-view-other-desc`}),i.map((h,f)=>{const v=FU(f),S=$f(t(v.range)),N=$f(t(v.impact)),x=p&&i.includes(p)?h===p:i.length===1;return e.jsxs("div",{className:"rounded border border-slate-200 p-1.5 space-y-1","data-testid":`${n}-detail-${f}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsx("span",{className:"text-[10px] font-medium text-slate-500",children:Dc("ViewType",h)}),s&&e.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-slate-500 cursor-pointer",children:[e.jsx("input",{type:"radio",name:`${n}-primary`,checked:!!x,onChange:()=>a(uT,h),disabled:r,"data-testid":`${n}-primary-${f}`}),"Primary"]})]}),e.jsxs(sr,{value:S===""?void 0:S,onValueChange:y=>{a(v.range,y===Fb?"":y),y!=="Other"&&$f(t(v.rangeOther))&&a(v.rangeOther,"")},disabled:r,children:[e.jsx(rr,{className:"h-7 text-xs","data-testid":`${n}-range-${f}`,children:e.jsx(or,{placeholder:"View range…"})}),e.jsxs(nr,{children:[e.jsx(vs,{value:Fb,children:e.jsx("span",{className:"text-muted-foreground",children:"— Clear —"})}),c.map(y=>e.jsx(vs,{value:y,children:Dc("ViewRangeType",y)},y))]})]}),S==="Other"&&e.jsx(ze,{type:"text",value:$f(t(v.rangeOther)),onChange:y=>a(v.rangeOther,y.target.value),maxLength:DL,readOnly:r,disabled:r,placeholder:"Describe range…",className:"h-7 text-xs","data-testid":`${n}-range-other-${f}`}),s&&e.jsxs(sr,{value:N===""?void 0:N,onValueChange:y=>a(v.impact,y===Fb?"":y),disabled:r,children:[e.jsx(rr,{className:"h-7 text-xs","data-testid":`${n}-impact-${f}`,children:e.jsx(or,{placeholder:"Impact to value/marketability…"})}),e.jsxs(nr,{children:[e.jsx(vs,{value:Fb,children:e.jsx("span",{className:"text-muted-foreground",children:"— Clear —"})}),d.map(y=>e.jsx(vs,{value:y,children:Dc("ViewValueMarketabilityImpactType",y)},y))]})]})]},h)})]})}const $p=t=>t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim(),X3={distance:"Proximity to Subject","distance to subject":"Proximity to Subject","distance from subject":"Proximity to Subject",proximity:"Proximity to Subject","date of sale":"Date of Sale","sale date":"Date of Sale","sales price":"Sale Price",price:"Sale Price",gla:"Gross Living Area","square footage":"Gross Living Area","living area":"Gross Living Area",address:"Address","year built":"Year Built",view:"View",location:"Location"};function BD(t){const a=$p(t);if(!a||a===$p(ug))return null;const s=X3[a];if(s)return`"${t}" duplicates the standard "${s}" row — use that row instead so the value exports as UAD 3.6 data.`;for(const r of vL)if($p(r.label)===a||$p(r.schemaDataElement||r.rowId)===a)return`"${t}" duplicates the standard "${r.label}" row, which is already on every grid — enter the values there instead.`;for(const r of ab)if($p(r.label)===a||$p(r.schemaDataElement)===a)return`"${t}" duplicates the standard "${r.label}" row — add it from the UAD 3.6 fields tab instead so the value exports as UAD 3.6 data.`;for(const r of lT)if($p(r.label)===a||$p(r.schemaDataElement)===a)return`"${t}" is already covered: ${r.hint}`;return null}const eB=[],iS=80;function tB(t=[]){return f_.filter(a=>!t.includes(a))}function aB({open:t,onOpenChange:a,entries:s,onApply:r,onDelete:n,disabled:i=!1}
2){const l=o.useRef(null),c=o.useRef(null),[d,p]=o.useState(""),[u,m]=o.useState(null),[h,f]=o.useState(null),v=s.filter(E=>E.kind==="custom"&&E.group==="Vehicle Storage"&&typeof E.customId=="string"&&E.customId.trim()!==""),S=v.length<oE,[N,x]=o.useState(null),y=o.useRef("after");o.useEffect(()=>{t&&(p(""),m(null))},[t]),o.useEffect(()=>{if(!t)return;const E=R=>{h||R.key==="Escape"&&a(!1)};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[t,a,h]),o.useEffect(()=>{if(!t)return;const E=R=>{if(h)return;const G=R.target;G instanceof Element&&G.closest("[data-vehicle-storage-picker-trigger]")||(!G||!l.current?.contains(G))&&a(!1)};return document.addEventListener("click",E,!0),()=>document.removeEventListener("click",E,!0)},[t,a,h]);const b=(E,R,G)=>{if(i||E===R)return;const U=v.map(M=>M.customId),C=U.indexOf(E),F=U.indexOf(R);if(C<0||F<0)return;U.splice(C,1);const A=U.indexOf(R);U.splice(G==="after"?A+1:A,0,E),r(g_(s,U))},j=(E,R)=>{const G=v.findIndex(C=>C.customId===E),U=v[G+R];U?.customId&&b(E,U.customId,R<0?"before":"after")},T=E=>{const R=E.trim();if(!R)return"Enter a label before adding it.";if(R.length>iS)return`Labels must be ${iS} characters or fewer.`;const G=new Set(s.filter(C=>C.group==="Vehicle Storage").map(C=>$p(C.label||""))),U=$p(R);return U&&G.has(U)?`Duplicate label: "${R}" already exists.`:S?null:`Vehicle Storage supports at most ${oE} Additional Rows.`},O=()=>{const E=d.trim(),R=T(E);if(R){m(R);return}const G=cT();r([...s,{rowId:`custom_${G}`,kind:"custom",label:E,customId:G,group:"Vehicle Storage",relevant:!0}]),p(""),m(null)};return t?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40 bg-black/50","aria-hidden":"true","data-testid":"vehicle-storage-row-picker-backdrop",onClick:()=>{h||a(!1)}}),e.jsx("div",{ref:l,role:"dialog","aria-label":"+ Additional row",className:"absolute left-0 top-full z-50 mt-1 w-80 rounded-md bg-white text-left text-xs normal-case font-normal tracking-normal text-slate-700 shadow-lg ring-1 ring-slate-200","data-testid":"dialog-vehicle-storage-row-picker",children:e.jsxs("div",{className:"space-y-2 p-3",children:[e.jsx("h3",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:"Vehicle Storage"}),v.length>0&&e.jsx("div",{className:"space-y-0.5","aria-label":"Vehicle Storage custom rows",role:"list","data-testid":"vehicle-storage-custom-row-list",children:v.map((E,R)=>{const G=E.customId,U=E.label||"Additional Row";return e.jsxs("div",{draggable:!i,tabIndex:i?-1:0,role:"listitem","aria-label":`${U}${E.relevant===!1?", not relevant":""}. Use arrow keys to reorder.`,"aria-roledescription":"sortable row",className:Q("flex items-center gap-1 rounded px-1 py-1 text-xs outline-none hover:bg-blue-50 focus-visible:ring-2 focus-visible:ring-blue-400",N===G&&"border-t-2 border-blue-400"),"data-testid":`vehicle-storage-row-${G}`,onDragStart:C=>{i||(c.current=G,C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",G))},onDragOver:C=>{if(i||!c.current)return;C.preventDefault(),C.dataTransfer.dropEffect="move";const F=C.currentTarget.getBoundingClientRect();y.current=R===0||F.height>0&&C.clientY<F.top+F.height/2?"before":"after",x(G)},onDrop:C=>{C.preventDefault();const F=c.current||C.dataTransfer.getData("text/plain");F&&b(F,G,y.current),c.current=null,x(null)},onDragEnd:()=>{c.current=null,x(null),y.current="after"},onKeyDown:C=>{i||C.target!==C.currentTarget||(C.key==="ArrowUp"||C.key==="ArrowDown")&&(C.preventDefault(),j(G,C.key==="ArrowUp"?-1:1))},children:[e.jsx("span",{className:"flex h-6 w-5 shrink-0 cursor-grab items-center justify-center text-slate-400","aria-hidden":"true",title:"Drag to reorder","data-testid":`vehicle-storage-drag-handle-${G}`,children:e.jsx(pN,{className:"h-3.5 w-3.5"})}),e.jsxs("label",{className:"flex min-w-0 flex-1 cursor-pointer items-center gap-2",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 shrink-0 rounded border-slate-300 accent-blue-600",checked:E.relevant!==!1,disabled:i,onChange:C=>r(s.map(F=>F.customId===G?{...F,relevant:C.target.checked}:F))}),e.jsx("span",{className:"truncate",children:U})]}),n&&e.jsx(De,{type:"button",variant:"ghost",size:"icon",disabled:i,className:"h-7 w-7 shrink-0 text-muted-foreground hover:bg-red-50 hover:text-red-600",onClick:()=>f(E),"aria-label":`Delete ${U} permanently`,title:"Delete custom row permanently","data-testid":`vehicle-storage-delete-${G}`,children:e.jsx(Ci,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},G)})}),S&&e.jsxs("div",{className:"space-y-1 border-t border-slate-200 pt-2",children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:"Add custom row"}),e.jsx(Ja,{htmlFor:"vehicle-storage-additional-labels",children:"Label"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ze,{id:"vehicle-storage-additional-labels",value:d,onChange:E=>{p(E.target.value),m(null)},onKeyDown:E=>
2{E.key==="Enter"&&(E.preventDefault(),O())},maxLength:iS,placeholder:"e.g. Covered parking notes",className:"placeholder-hint",disabled:i}),e.jsx(De,{type:"button",variant:"outline",size:"icon",onClick:O,disabled:i,"aria-label":"Add label","data-testid":"vehicle-storage-stage-label",children:e.jsx(un,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[d.length,"/",iS]})]}),u&&e.jsx("p",{className:"text-xs text-destructive","data-testid":"vehicle-storage-row-picker-error",children:u}),e.jsx(WL,{open:!!h,onOpenChange:E=>{E||f(null)},children:e.jsxs(KL,{"data-testid":"dialog-delete-vehicle-storage-row",children:[e.jsxs(QL,{children:[e.jsx(ZL,{children:"Delete this custom row permanently?"}),e.jsxs(JL,{children:[h?.label||"This row"," will be removed from the picker and grid. All retained Subject and comparable values for this row will also be deleted. This cannot be undone."]})]}),e.jsxs(XL,{children:[e.jsx(eD,{children:"Cancel"}),e.jsx(tD,{onClick:()=>{const E=h?.customId;f(null),E&&n?.(E)},"data-testid":"confirm-delete-vehicle-storage-row",children:"Delete permanently"})]})]})})]})})]}):null}function sB({open:t,onOpenChange:a,existingRowIds:s,onAdd:r,totalUnitsRowExists:n,initialGroup:i,visibilityCtx:l,vehicleStorageMode:c,vehicleStorageEntries:d=[],onApplyVehicleStorage:p,onDeleteVehicleStorage:u,vehicleStorageDisabled:m=!1,excludedCustomGroups:h=eB}){const[f,v]=o.useState("uad"),[S,N]=o.useState(""),[x,y]=o.useState(""),[b,j]=o.useState(Ky),[T,O]=o.useState(null),[E,R]=o.useState(null);o.useEffect(()=>{t&&(O(i??null),j(i&&iE(i)&&!h.includes(i)?i:Ky),R(null),N(""),v("uad"))},[t,i,h]);const G=o.useMemo(()=>{const ae=S.trim().toLowerCase(),D=new Map;for(const _ of ab){if(s.has(_.rowId)||Xh(_.rowId,_.group)||_.pickerHidden||T&&_.group!==T||!p_(_.rowId,s)||ae&&!_.label.toLowerCase().includes(ae)&&!_.schemaDataElement.toLowerCase().includes(ae)&&!(_.description??"").toLowerCase().includes(ae))continue;const $=D.get(_.group)??[];$.push(_),D.set(_.group,$)}return Array.from(D.entries())},[S,s,T]),U=o.useMemo(()=>{const ae=S.trim().toLowerCase();if(!ae){const $=lT.find(z=>z.schemaDataElement==="PropertyEstateType");return $?[{key:$.schemaDataElement,label:$.label,hint:$.hint}]:[]}const D=[],_=new Set;for(const $ of lT)_.has($.schemaDataElement)||($.label.toLowerCase().includes(ae)||$.schemaDataElement.toLowerCase().includes(ae))&&(_.add($.schemaDataElement),D.push({key:$.schemaDataElement,label:$.label,hint:$.hint}));for(const $ of ab){if(_.has($.rowId))continue;const z=s.has($.rowId);!z&&!$.pickerHidden||($.label.toLowerCase().includes(ae)||$.schemaDataElement.toLowerCase().includes(ae))&&(_.add($.rowId),D.push({key:$.rowId,label:$.label,hint:z?"Already added to this grid.":$.rowId==="NativeAmericanLandsType"?"Covered by the Native American Lands row — pick the land type there.":'Captured automatically — the free-text box appears in the cell when "Other" is selected on its parent row.'}))}return D.slice(0,8)},[S,s]),C=ae=>{r({rowId:ae,kind:"optional"}),a(!1),N("")},F=()=>{const ae=x.trim();if(!ae)return;if(h.includes(b)){R(`${b} rows must be added from their section-specific Additional Row action.`);return}const D=BD(ae);if(D){R(D);return}R(null);const _=cT();r({rowId:`custom_${_}`,kind:"custom",label:ae,customId:_,...iE(b)?{group:b}:{}}),y(""),j(Ky),a(!1)},A=S.trim().toLowerCase(),M=!n&&(!A||ug.toLowerCase().includes(A)||"unit count".includes(A)),B=()=>{const ae=cT();r({rowId:`custom_${ae}`,kind:"custom",label:ug,customId:ae,group:sg}),a(!1),N("")},oe=e.jsxs("button",{type:"button",onClick:B,className:"w-full text-left px-3 py-2 hover:bg-blue-50 flex items-center justify-between gap-2 text-sm","data-testid":"button-pick-row-total-units",children:[e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:ug}),e.jsx("span",{className:"text-[11px] text-muted-foreground truncate",children:"Per Fannie Mae: report a unit-count difference (and its adjustment) on this row inside Dwelling(s) — not in the Unit(s) subsection."})]}),e.jsx(kt,{variant:"secondary",className:"text-[10px] shrink-0",children:"suggested custom row"})]});return c?e.jsx(aB,{open:t,onOpenChange:a,entries:d,onApply:ae=>p?.(ae),onDelete:u,disabled:m}):e.jsx(xi,{open:t,onOpenChange:a,children:e.jsxs(bi,{className:"max-w-2xl","data-testid":"dialog-row-picker","data-excluded-custom-groups":h.join(","),children:[e.jsxs($i,{children:[e.jsx(si,{children:"Add additional row"}),e.jsx(pl,{children:"The grid starts with the rows most reports need. Add another UAD 3.6 field only when this property calls for it, or add a custom row. Custom rows export as AdditionalComparisonLineItem entries."})]}),e.jsxs(up,{value:f,onValueChange:ae=>v(ae),children:[e.jsxs(pp,{className:"grid grid-cols-2 w-full",children:[e.jsx($n,{value:"uad","data-testid":"tab-uad-fields",children:"UAD 3.6 fields"}),e.jsx($n,{value:"custom","data-testid":"tab-custom-row",children:"Custom row"})]}),e.jsxs(Bd,{value:"uad",className:"space-y-3",children:[T&&e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md border bg-muted/40 px-3 py-1.5 text-xs","data-testid":"banner-group-filter",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Showing fields for"," ",e.jsx("span",{className:"font-semibold text-foreground",children:T})]}),e.jsx("button",{type:"button",className:"text-blue-600 hover:underline shrink-0",onClick:()=>O(null),"data-testid":"button-show-all-sections",children:"Show all sections"})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Eu,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ze,{value:S,onChange:ae=>N(ae.target.value),placeholder:"Search 200+ fields by name…",className:"pl-8 placeholder-hint","data-testid":"input-row-picker-search"})]}),e.jsxs(Qd,{className:"h-80 border rounded-md",children:[G.length===0&&U.length===0&&e.jsx("div",{className:"p-4 text-sm text-muted-foreground","data-testid":"text-row-picker-empty",children:"No fields match. Try a different search term, or add it as a custom row."}),G.map(([ae,D])=>e.jsxs("div",{className:"border-b last:border-b-0",children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-semibold uppercase tracking-wide bg-gray-50 text-muted-foreground",children:ae}),ae===sg&&M&&oe,e.jsx("ul",{children:D.map(_=>{const $=m_(_.rowId)??(l?h_(_.rowId,l):null);return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:$?void 0:()=>C(_.rowId),disabled:!!$,className:["w-full text-left px-3 py-2 flex items-center justify-between gap-2 text-sm",$?"opacity-50 cursor-not-allowed":"hover:bg-blue-50"].join(" "),"data-testid":`button-pick-row-${_.rowId}`,title:$??void 0,children:[e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:_.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground truncate",children:$?`Not available: ${$}`:_.description??_.schemaDataElement})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[NL[_.schemaDataElement]&&e.jsx(kt,{variant:"secondary",className:"text-[10px]",title:"This row only displays on the grid when the UAD 3.6 condition for it applies (e.g. the matching property type or feature is present).","data-testid":`badge-when-applicable-${_.rowId}`,children:"shows when it applies"}),$&&e.jsx(kt,{variant:"secondary",className:"text-[10px] bg-amber-100 text-amber-700","data-testid":`badge-gated-${_.rowId}`,children:"not yet applicable"}),e.jsx(kt,{variant:"outline",className:"text-[10px]",children:_.inputType})]})]})},_.rowId)})})]},ae)),M&&!G.some(([ae])=>ae===sg)&&e.jsxs("div",{className:"border-b last:border-b-0",children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-semibold uppercase tracking-wide bg-gray-50 text-muted-foreground",children:sg}),oe]}),U.length>0&&e.jsxs("div",{className:"border-t bg-muted/40","data-testid":"section-already-covered",children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Already covered"}),e.jsx("ul",{children:U.map(ae=>e.jsxs("li",{className:"px-3 py-2 text-sm","data-testid":`text-covered-${ae.key}`,children:[e.jsx("span",{className:"font-medium text-muted-foreground",children:ae.label}),e.jsx("span",{className:"block text-[11px] text-muted-foreground",children:ae.hint})]},ae.key))})]})]})]}),e.jsxs(Bd,{value:"custom",className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"text-custom-tab-guidance",children:"Check the UAD 3.6 fields tab first — a standard field exports cleanly to the GSEs, while a custom row travels as a free-form line item. Use a custom row only when no standard field fits."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{htmlFor:"custom-row-label",children:"Row label"}),e.jsx(ze,{id:"custom-row-label",value:x,onChange:ae=>{y(ae.target.value),E&&R(null)},placeholder:"e.g. HOA Notes, View Premium, Lot Premium",className:"placeholder-hint","data-testid":"input-custom-row-label",onKeyDown:ae=>
2{ae.key==="Enter"&&(ae.preventDefault(),F())}}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custom rows accept free-form text per comp. Numeric values export as AdditionalComparisonLineItem adjustments; text-only values stay in the form for reviewer reference."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{htmlFor:"custom-row-group",children:"Grid section"}),e.jsxs(sr,{value:b,onValueChange:j,children:[e.jsx(rr,{id:"custom-row-group",className:"placeholder-hint","data-testid":"select-custom-row-group",children:e.jsx(or,{placeholder:"Custom rows"})}),e.jsx(nr,{children:tB(h).map(ae=>e.jsx(vs,{value:ae,children:ae===Ky?"Custom rows (bottom of grid)":ae},ae))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:`Where the row appears on the grid. Example: Fannie Mae's Q1 2026 update places a "Total Units" row inside Dwelling(s).`})]}),E&&e.jsx("p",{className:"text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded-md px-3 py-2","data-testid":"text-custom-row-duplicate-block",children:E}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(De,{type:"button",onClick:F,disabled:!x.trim(),"data-testid":"button-add-custom-row",children:[e.jsx(un,{className:"h-4 w-4 mr-1"})," Add custom row"]})})]})]})]})})}function Fx(t){const{enabled:a,delayMs:s=400}=t,r=o.useRef(t);r.current=t,o.useEffect(()=>{if(!a||!r.current.isHydrated())return;const n=window.setTimeout(()=>{let i;try{i=r.current.persist()}catch(l){console.warn(`${r.current.label}: persist failed:`,l);return}if(i&&typeof i.then=="function"){const l=r.current.scopeId??"unscoped";Go(l,i).catch(c=>{console.warn(`${r.current.label}: persist failed:`,c)})}},s);return()=>window.clearTimeout(n)},[a,s,...t.deps])}const vT=new EventTarget,NT="sales-grid-ui-state-change";function zD(t,a){vT.dispatchEvent(new CustomEvent(NT,{detail:{orderId:t,sourceId:a}}))}function qD(t,a,s){const r=n=>{const i=n.detail;i.orderId===t&&i.sourceId!==a&&s()};return vT.addEventListener(NT,r),()=>vT.removeEventListener(NT,r)}function YD(t,a){const s=Object.keys(t),r=Object.keys(a);if(s.length!==r.length)return!1;for(const n of s)if(t[n]!==a[n])return!1;return!0}function Lm(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}function rB(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").trim()}function nB(t,a,s){if(Math.abs(t.length-a.length)>s)return s+1;const r=new Array(a.length+1).fill(0).map((n,i)=>i);for(let n=1;n<=t.length;n++){let i=[n],l=n;for(let c=1;c<=a.length;c++){const d=t[n-1]===a[c-1]?0:1;i[c]=Math.min(r[c]+1,i[c-1]+1,r[c-1]+d),l=Math.min(l,i[c])}if(l>s)return s+1;for(let c=0;c<=a.length;c++)r[c]=i[c]}return r[a.length]}function iB(t,a){const s=t.trim();if(!s||s.length<3||!a||a.length===0)return null;const r=Lm(s);if(!r)return null;for(const n of a){if(n==="Other")continue;const i=Lm(n);if(i){if(r===i)return n;if(r.length>=5&&i.length>=5){const l=r.length>=8?2:1;if(nB(r,i,l)<=l)return n}}}return null}function GD(t){return t&&(/\bGLA\b/.test(t)||/gross\s+living\s+area/i.test(t))?'UAD 3.6 replaced "GLA / Gross Living Area" with "Finished Area Above Grade".':null}const oB=[{pattern:/\b(pool|spa|hot\s*tub|swim)/i,keyword:"water"},{pattern:/\b(gla|living\s*area|above\s*grade)/i,keyword:"finished area"},{pattern:/\b(garage|carport|parking)/i,keyword:"storage"},{pattern:/\b(porch|patio|deck|balcony)/i,keyword:"porch"},{pattern:/\b(fireplace|wood\s*stove)/i,keyword:"fireplace"},{pattern:/\b(fence|fencing)/i,keyword:"fence"},{pattern:/\bview\b/i,keyword:"view"}];function lB(t,a){const s=t.trim();if(!s||a.length===0)return null;const r=Lm(s);if(!r)return null;for(const n of a){const i=Lm(n.label);if(i&&r===i)return n}if(r.length>=4)for(const n of a){const i=Lm(n.label);if(i&&(i.includes(r)||r.includes(i)))return n}for(const n of oB){if(!n.pattern.test(s))continue;const i=Lm(n.keyword),l=a.find(c=>Lm(c.label).includes(i));if(l)return l}return null}function cB(t,a){const s=Lm(t);return s?a.some(r=>Lm(r)===s):!1}function wv(t){return t?t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").trim():""}const dB={ArmLth:"TypicallyMotivated",REO:"REOSale",Short:"ShortSale",Estate:"EstateSale",Relo:"RelocationSale",CrtOrd:"CourtOrderedNonForeclosureSale",NonArm:"SaleBetweenRelatedParties",Listing:"TypicallyMotivated"};function cp(t){const a=String(t??"").trim();return a?dB[a]??a:""}const nb="Cash",HD=" · ";function ib(t){if(t==null)return null;if(typeof t=="number")return t>0?t:null;const a=String(t).trim();if(!a||a.toLowerCase()==="none"||a==="null")return null;const s=parseInt(a.replace(/[^0-9]/g,""),10);return isNaN(s)||s<=0?null:s}function Pv(t,a,s,r){const n=s?nb:a||"",i=r&&r>0?String(r):"0";return[t||"",n,i].join(HD)}function qI(t){const a={saleType:"",financing:"",noFinancing:!1,
2concession:null},s=String(t??"").trim();if(!s)return a;if(s.includes("·")){const r=s.split("·").map(i=>i.trim()),n=r[1]??"";return{saleType:cp(r[0]),financing:n&&n!==nb?n:"",noFinancing:n===nb,concession:ib(r[2])}}if(s.includes("/")){const r=s.split("/").map(c=>c.trim()),n=r[0]??"",i=new Set(Pr("MortgageType")??[]),l={...a,concession:ib(r[1])};return i.has(n)?l.financing=n:n&&(l.saleType=cp(n)),l}return a}function WD(t){const a=qI(t);return{saleType:a.saleType||"TypicallyMotivated",financing:a.noFinancing?"":a.financing,concessions:a.concession!=null?String(a.concession):"0"}}function dx(t){const a=String(t??"").trim().toLowerCase();return a?/\bfha\b/.test(a)?{financing:"FHA",noFinancing:!1,hasData:!0}:/\bva\b|veteran/.test(a)?{financing:"VA",noFinancing:!1,hasData:!0}:/\busda\b|rural/.test(a)?{financing:"USDARuralDevelopment",noFinancing:!1,hasData:!0}:/conventional|\bconv\b/.test(a)?{financing:"Conventional",noFinancing:!1,hasData:!0}:/private|owner financ|seller financ|land contract|contract for deed/.test(a)?{financing:"Private",noFinancing:!1,hasData:!0}:/\bcash\b|no financing|no loan/.test(a)?{financing:"",noFinancing:!0,hasData:!0}:{financing:"Other",noFinancing:!1,hasData:!0}:{financing:"",noFinancing:!1,hasData:!1}}function uB(t){const a=qI(t),s=[];return a.saleType&&s.push(wv(a.saleType)),a.noFinancing?s.push(nb):a.financing&&s.push(wv(a.financing)),s.push(a.concession&&a.concession>0?cf(a.concession):cf(0)),s.join(HD)}function pB(t){const a=String(t??"").trim();return a?a===nb?nb:wv(a):""}function mB(t){const a=ib(t);return a&&a>0?cf(a):cf(0)}function hB(t){const a=cp(t);return a?wv(a):""}function fB(t){return t?t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").trim():""}const gB=["Porch","Patio","Deck","Balcony","Portico","Gazebo","None","Other"],KD=["Inferior","Similar","Superior"],xB={op:"Porch",cp:"Porch",ep:"Porch",sp:"Porch",pt:"Patio",patio:"Patio",dk:"Deck",deck:"Deck",porch:"Porch",balcony:"Balcony",portico:"Portico",gazebo:"Gazebo"};function bB(t){const a=String(t??"").trim();return a?xB[a.toLowerCase()]??a:""}const QD=" · ",L0="|";function D0(t){const a=[];for(const s of t){const r=bB(s);!r||a.includes(r)||a.push(r)}return a.length>1?a.filter(s=>s!=="None"):a}function BA(t,a){const s=D0(Array.isArray(t)?t:[String(t??"")]);if(s.length===0)return"";if(s.length===1&&s[0]==="None")return"None";const r=String(a??"").trim(),n=s.join(L0);return r?[n,r].join(QD):n}function YI(t){const a={amenityTypes:[],comparison:""},s=String(t??"").trim();if(!s)return a;if(s.toLowerCase()==="none"||s==="–")return{amenityTypes:["None"],comparison:""};if(s.includes("·")){const l=s.split("·").map(d=>d.trim()),c=l[1]??"";return{amenityTypes:D0((l[0]??"").split(L0)),comparison:KD.includes(c)?c:""}}if(s.includes(L0))return{amenityTypes:D0(s.split(L0)),comparison:""};const n=s.replace(/;\s*\d[\d,]*\s*sf\s*$/i,"").split(/[;,]/).map(l=>l.trim()).filter(Boolean),i=D0(n);return i.length>0?{amenityTypes:i,comparison:""}:a}function yB(t){const a=YI(t);return{amenityType:a.amenityTypes.join(L0),amenityComparison:a.comparison}}function SB(t){const a=YI(t);if(a.amenityTypes.length===0)return"";if(a.amenityTypes.length===1&&a.amenityTypes[0]==="None")return"None";const s=a.amenityTypes.map(fB).join(", ");return a.comparison?[s,a.comparison].join(QD):s}const Mo={autoComplete:"off",name:"uad-grid-field-entry","data-1p-ignore":!0,"data-lpignore":"true","data-form-type":"other"};function Mc({descFieldName:t,value:a,onCommit:s,testId:r,label:n='Describe "Other"',maxLength:i}){const[l,c]=o.useState(a??""),[d,p]=o.useState(null);o.useEffect(()=>{c(a??"")},[a]);const u=()=>{const S=l.trim();S!==(a??"")&&s(t,S)},m=o.useMemo(()=>{if(!t.endsWith("OtherDescription"))return null;const S=t.slice(0,-16);return Pr(S)},[t]),h=iB(l,m),f=GD(l),v=h?`"${l.trim()}" matches the standard option "${rB(h)}" — consider selecting it from the list instead of Other.`:f;return e.jsxs("div",{className:"mt-2 pt-2 border-t border-slate-100 space-y-1",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:n}
2),e.jsx(ze,{...Mo,value:l,onChange:S=>c(S.target.value),onBlur:u,onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),u())},placeholder:"Free-text description",className:"h-7 text-xs placeholder-hint",maxLength:i,"data-testid":r}),v&&d!==v&&e.jsxs("div",{className:"flex items-start gap-1 rounded bg-amber-50 px-1.5 py-1 text-[10px] text-amber-800 ring-1 ring-amber-200","data-testid":`${r}-hint`,children:[e.jsx("span",{className:"min-w-0 flex-1",children:v}),e.jsx("button",{type:"button",onClick:()=>p(v),className:"shrink-0 font-semibold text-amber-500 hover:text-amber-700","aria-label":"Dismiss suggestion","data-testid":`${r}-hint-dismiss`,children:"✕"})]})]})}function Fc(t,a,s,r){o.useEffect(()=>{!t&&r&&(s??"")!==""&&r(a,"")},[t,a,s,r])}const vB=new Set(["dataSourceIdentifier","locationBodyOfWater","viewRange","heatingFuel","garageAttachment","garageArea","garageSurface","garageTenOrMore","GreenCertificationLevelName","EfficiencyRatingScoreValue","RenewableEnergyComponentTypeOtherDescription","interiorCondition","exteriorCondition"]),NB=/^garage(Attachment|Area|Surface|TenOrMore)\d+$/;function ZD(t){return vB.has(t)||NB.test(t)||_U(t)}function Ov(t){const a=t.split("-").pop()||t;switch(a){case"quality":return"quality";case"condition":return"condition";case"location":return"location";case"view":return"view";case"functionalUtility":return"functionalUtility";case"heatingCooling":return"heatingCooling";case"garageCarport":return"garageCarport";case"design":return"design";case"saleType":return"saleType";case"financing":return"financing";case"concessions":return"concessions";case"financingConcessions":return"financingConcessions";case"leaseholdFeeSimple":return"leaseholdFeeSimple";case"dateOfSale":return"dateOfSale";case"basement":return"basement";case"belowGrade":return"belowGrade";case"aboveGrade":return"aboveGrade";case"porchPatioDeck":return"porchPatioDeck";case"site":return"site";case"dataSource":return"dataSource";case"constructionMethod":return"constructionMethod";case"listingStatus":return"listingStatus";case"attachedDetached":return"attachedDetached";case"RenewableEnergyComponentType":return"renewableEnergyComponents";case"GreenCertificationName":return"greenCertifications";case"EfficiencyRatingName":return"efficiencyRatings";case"interiorQuality":case"exteriorQuality":return"quality";case"interiorCondition":case"exteriorCondition":return"condition";default:return/^basementUnit\d+$/.test(a)?"basement":null}}const AB=new Set(["location","view","heatingCooling","garageCarport","concessions","financingConcessions","dateOfSale","basement","belowGrade","aboveGrade","porchPatioDeck","site","dataSource","renewableEnergyComponents","greenCertifications","efficiencyRatings"]);function lg(t){return t!=null&&AB.has(t)}function $h({fieldType:t,currentValue:a,onSelect:s,onCopyToAllComps:r,onCopyCompanionToAllComps:n,onClose:i,otherDescriptions:l,onOtherDescriptionChange:c,uad36:d,subjectMode:p,basementHint:u}){if(!t)return null;const m={otherDescriptions:l,onOtherDescriptionChange:c};switch(t){case"quality":return e.jsx(wB,{currentValue:a,onSelect:s,onCopyToAllComps:r});case"condition":return e.jsx(PB,{currentValue:a,onSelect:s,onCopyToAllComps:r});case"location":return e.jsx(nw,{type:"location",currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"view":return e.jsx(nw,{type:"view",currentValue:a,onSelect:s,onCopyToAllComps:r,subjectMode:p,...m});case"functionalUtility":return e.jsx(LB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"heatingCooling":return e.jsx(DB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"garageCarport":return e.jsx(JD,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"design":return e.jsx(kB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"saleType":return e.jsx(MB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"financing":return e.jsx(FB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"concessions":return e.jsx(_B,{currentValue:a,onSelect:s,onCopyToAllComps:r});case"financingConcessions":return e.jsx(UB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"leaseholdFeeSimple":return e.jsx(VB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"listingStatus":return e.jsx($B,{currentValue:a,onSelect:s,onCopyToAllComps:r});case"attachedDetached":return e.jsx(BB,{currentValue:a,onSelect:s,onCopyToAllComps:r});case"dateOfSale":return e.jsx(zB,{currentValue:a,onSelect:s,onCopyToAllComps:r,uad36:d});case"basement":return e.jsx(qB,{currentValue:a,onSelect:s,onCopyToAllComps:r,uad36:d,basementHint:u});case"belowGrade":return e.jsx(YB,{currentValue:a,onSelect:s,onCopyToAllComps:r});case"aboveGrade":return e.jsx(GB,{currentValue:a,onSelect:s,onCopyToAllComps:r});case"porchPatioDeck":return e.jsx(HB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"site":return e.jsx(WB,{currentValue:a,onSelect:s,onCopyToAllComps:r});case"dataSource":return e.jsx(KB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"constructionMethod":return e.jsx(QB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});
2case"renewableEnergyComponents":return e.jsx(TB,{currentValue:a,onSelect:s,onCopyToAllComps:r,...m});case"greenCertifications":return e.jsx(CB,{currentValue:a,onSelect:s,onCopyToAllComps:r,onCopyCompanionToAllComps:n,...m});case"efficiencyRatings":return e.jsx(EB,{currentValue:a,onSelect:s,onCopyToAllComps:r,onCopyCompanionToAllComps:n,...m});default:return null}}const jB=["Solar","Geothermal","WindTurbine"];function TB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=o.useMemo(()=>{const x=String(t??"").trim();return!x||x==="null"||x==="undefined"?[]:x.split("|").map(y=>y.trim()).filter(Boolean)},[t]),l=i.includes("None"),c=o.useMemo(()=>{const x=r?.RenewableEnergyComponentTypeOtherDescription??"";return x?x.split("|").map(y=>y.trim()).filter(Boolean):[]},[r]),[d,p]=o.useState(""),u=x=>{let y;if(x==="None")y=l?[]:["None"],!l&&c.length>0&&n?.("RenewableEnergyComponentTypeOtherDescription","");else{const b=i.filter(j=>j!=="None");b.includes(x)?y=b.filter(j=>j!==x):y=[...b,x]}a(y.join("|"),"User")},m=8,f=i.filter(x=>x!=="None"&&x!=="Other").length+c.length,v=f>=m,S=x=>{const y=x.trim();if(!y||c.includes(y)||v){p("");return}const b=[...c,y];n?.("RenewableEnergyComponentTypeOtherDescription",b.join("|"));const j=i.filter(T=>T!=="None"&&T!=="Other");a([...j,"Other"].join("|"),"User"),p("")},N=x=>{const y=c.filter(b=>b!==x);n?.("RenewableEnergyComponentTypeOtherDescription",y.join("|")),y.length===0&&a(i.filter(b=>b!=="Other").join("|"),"User")};return!l&&(i.filter(x=>x!=="None"&&x!=="Other").length>0||c.length>0),e.jsxs("div",{className:"space-y-2","data-testid":"uad-renewable-energy-selector",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Renewable Energy Component"}),f>0&&e.jsxs("span",{className:Q("text-[10px] tabular-nums",v?"text-amber-600 font-semibold":"text-slate-400"),children:[f," / ",m]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsx("button",{onClick:()=>u("None"),className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all",l?"bg-slate-100 border-slate-400 text-slate-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":"uad-renewable-none",children:"None"}),jB.map(x=>{const y=!l&&i.includes(x),b=v&&!y;return e.jsx("button",{onClick:()=>!b&&u(x),disabled:b,className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all",y?"bg-blue-50 border-blue-300 text-blue-700":b?"bg-white border-slate-100 text-slate-300 cursor-not-allowed":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":`uad-renewable-${x}`,children:x==="WindTurbine"?"Wind Turbine":x},x)})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1","data-testid":"uad-renewable-custom-tags",children:c.map(x=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 text-xs rounded border bg-blue-50 border-blue-300 text-blue-700",children:[x,e.jsx("button",{type:"button",onClick:()=>N(x),className:"ml-0.5 text-blue-400 hover:text-red-500 transition-colors leading-none","data-testid":`uad-renewable-remove-custom-${x}`,"aria-label":`Remove ${x}`,children:"×"})]},x))}),!l&&e.jsxs("div",{className:"flex gap-1",children:[e.jsx("input",{type:"text",value:d,onChange:x=>!v&&p(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),S(d))},placeholder:v?`Max ${m} reached`:"Add custom type…",disabled:v,className:Q("flex-1 min-w-0 px-2 py-1 text-xs border rounded focus:outline-none focus:ring-1 focus:ring-blue-300 placeholder-hint",v?"border-slate-100 bg-slate-50 text-slate-300 cursor-not-allowed":"border-slate-200"),"data-testid":"uad-renewable-custom-input",...Mo}),e.jsx("button",{type:"button",onClick:()=>S(d),disabled:!d.trim()||v,className:"px-2 py-1 text-xs font-medium rounded border border-slate-200 bg-white text-slate-600 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors","data-testid":"uad-renewable-add-custom",children:"Add"})]}),s&&(i.length>0||c.length>0)&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:()=>s?.(i.join("|"),"User"),"data-testid":"uad-renewable-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function IB(t,a){const s=String(t??"").split("|").map(n=>
2n.trim()).filter(Boolean);if(s.length===0)return[];const r=String(a).split("|").map(n=>n.trim());return s.map((n,i)=>({name:n,level:r[i]??""}))}function CB({currentValue:t,onSelect:a,onCopyToAllComps:s,onCopyCompanionToAllComps:r,otherDescriptions:n,onOtherDescriptionChange:i}){const l=n?.GreenCertificationLevelName??"",[c,d]=o.useState(()=>IB(t,l)),p=S=>{const N=S.filter(b=>b.name.trim()!==""||b.level.trim()!==""),x=N.map(b=>b.name.trim()).join("|"),y=N.map(b=>b.level.trim()).join("|");a(x,"User"),i?.("GreenCertificationLevelName",y)},u=()=>{c.length>=8||d(S=>[...S,{name:"",level:""}])},m=S=>{const N=c.filter((x,y)=>y!==S);d(N),p(N)},h=(S,N,x)=>{d(y=>y.map((b,j)=>j===S?{...b,[N]:x}:b))},f=()=>p(c),v=S=>{S.key==="Enter"&&(S.preventDefault(),f())};return e.jsxs("div",{className:"space-y-2","data-testid":"uad-green-cert-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Building Certification (max 8)"}),c.length===0&&e.jsx("p",{className:"text-[11px] text-slate-400 italic",children:"None added — click below to add."}),c.map((S,N)=>e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx(ze,{...Mo,value:S.name,onChange:x=>h(N,"name",x.target.value),onBlur:f,onKeyDown:v,placeholder:"Name (e.g. LEED)",className:"h-7 text-[11px] flex-1 placeholder-hint","data-testid":`uad-cert-name-${N}`}),e.jsx(ze,{...Mo,value:S.level,onChange:x=>h(N,"level",x.target.value),onBlur:f,onKeyDown:v,placeholder:"Rating (e.g. Gold)",className:"h-7 text-[11px] flex-1 placeholder-hint","data-testid":`uad-cert-level-${N}`}),e.jsx("button",{type:"button",onClick:()=>m(N),className:"shrink-0 p-1 text-slate-400 hover:text-rose-500 transition-colors rounded","data-testid":`uad-cert-remove-${N}`,"aria-label":"Remove certification",children:e.jsx(Ci,{className:"w-3.5 h-3.5"})})]},N)),c.length<8&&e.jsxs("button",{type:"button",onClick:u,className:"w-full h-7 border border-dashed border-slate-300 rounded text-xs text-slate-500 hover:border-slate-400 hover:bg-slate-50 transition-colors flex items-center justify-center gap-1","data-testid":"uad-cert-add",children:[e.jsx(un,{className:"w-3 h-3"}),"Add certification"]}),s&&c.some(S=>S.name.trim())&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:()=>{const S=c.map(x=>x.name.trim()).join("|"),N=c.map(x=>x.level.trim()).join("|");s(S,"User"),r?.("GreenCertificationLevelName",N,"User")},"data-testid":"uad-cert-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function RB(t,a){const s=String(t??"").split("|").map(n=>n.trim()).filter(Boolean);if(s.length===0)return[];const r=String(a).split("|").map(n=>n.trim());return s.map((n,i)=>({name:n,score:r[i]??""}))}function EB({currentValue:t,onSelect:a,onCopyToAllComps:s,onCopyCompanionToAllComps:r,otherDescriptions:n,onOtherDescriptionChange:i}){const l=n?.EfficiencyRatingScoreValue??"",[c,d]=o.useState(()=>RB(t,l)),p=S=>{const N=S.filter(b=>b.name.trim()!==""||b.score.trim()!==""),x=N.map(b=>b.name.trim()).join("|"),y=N.map(b=>b.score.trim()).join("|");a(x,"User"),i?.("EfficiencyRatingScoreValue",y)},u=()=>{c.length>=8||d(S=>[...S,{name:"",score:""}])},m=S=>{const N=c.filter((x,y)=>y!==S);d(N),p(N)},h=(S,N,x)=>{d(y=>y.map((b,j)=>j===S?{...b,[N]:x}:b))},f=()=>p(c),v=S=>{S.key==="Enter"&&(S.preventDefault(),f())};return e.jsxs("div",{className:"space-y-2","data-testid":"uad-efficiency-rating-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Efficiency Rating (max 8)"}),c.length===0&&e.jsx("p",{className:"text-[11px] text-slate-400 italic",children:"None added — click below to add."}),c.map((S,N)=>e.jsxs("div",{className:"flex gap-1 items-center",children:[e.jsx(ze,{...Mo,value:S.name,onChange:x=>h(N,"name",x.target.value),onBlur:f,onKeyDown:v,placeholder:"Name (e.g. HERS)",className:"h-7 text-[11px] flex-1 placeholder-hint","data-testid":`uad-rating-name-${N}`}),e.jsx(ze,{...Mo,value:S.score,onChange:x=>h(N,"score",x.target.value),onBlur:f,onKeyDown:v,placeholder:"Score (e.g. 45)",className:"h-7 text-[11px] flex-1 placeholder-hint","data-testid":`uad-rating-score-${N}`}),e.jsx("button",{type:"button",onClick:()=>m(N),className:"shrink-0 p-1 text-slate-400 hover:text-rose-500 transition-colors rounded","data-testid":`uad-rating-remove-${N}`,"aria-label":"Remove rating",children:e.jsx(Ci,{className:"w-3.5 h-3.5"})})]},N)),c.length<8&&e.jsxs("button",{type:"button",onClick:u,className:"w-full h-7 border border-dashed border-slate-300 rounded text-xs text-slate-500 hover:border-slate-400 hover:bg-slate-50 transition-colors flex items-center justify-center gap-1","data-testid":"uad-rating-ad
2d",children:[e.jsx(un,{className:"w-3 h-3"}),"Add rating"]}),s&&c.some(S=>S.name.trim())&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:()=>{const S=c.map(x=>x.name.trim()).join("|"),N=c.map(x=>x.score.trim()).join("|");s(S,"User"),r?.("EfficiencyRatingScoreValue",N,"User")},"data-testid":"uad-rating-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function wB({currentValue:t,onSelect:a,onCopyToAllComps:s}){const r=String(t||"").toUpperCase(),n=P0.find(i=>i.code===r);return e.jsxs("div",{className:"space-y-1.5","data-testid":"uad-quality-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Quality Rating (Q1-Q6)"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:P0.map(i=>e.jsx("button",{onClick:()=>a(i.code,"User"),className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all",r===i.code?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),title:i.description,"data-testid":`uad-quality-${i.code}`,children:i.code},i.code))}),n?.description&&e.jsxs("p",{className:"text-[10px] text-slate-500 mt-1",children:[n.description.slice(0,80),"..."]}),s&&r&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(r,"User"),"data-testid":"uad-quality-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy ",r," to all comps"]})}),e.jsx(Wa,{children:"Apply this rating to all comparable properties"})]})]})}function PB({currentValue:t,onSelect:a,onCopyToAllComps:s}){const r=String(t||"").toUpperCase(),n=w0.find(i=>i.code===r);return e.jsxs("div",{className:"space-y-1.5","data-testid":"uad-condition-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Condition Rating (C1-C6)"}),e.jsx("div",{className:"grid grid-cols-3 gap-1",children:w0.map(i=>e.jsx("button",{onClick:()=>a(i.code,"User"),className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all",r===i.code?"bg-green-50 border-green-300 text-green-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),title:i.description,"data-testid":`uad-condition-${i.code}`,children:i.code},i.code))}),n?.description&&e.jsxs("p",{className:"text-[10px] text-slate-500 mt-1",children:[n.description.slice(0,80),"..."]}),s&&r&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(r,"User"),"data-testid":"uad-condition-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy ",r," to all comps"]})}),e.jsx(Wa,{children:"Apply this rating to all comparable properties"})]})]})}function Lv(t){const a=String(t??"").trim();return!a||a==="null"||a==="undefined"?[]:a.split("|").map(s=>s.trim()).filter(s=>s.length>0)}function OB(t,a){return a==="None"?["None"]:[...t.filter(s=>s!=="None"),a]}function Dv({schemaElement:t,tokens:a,options:s,onChange:r,placeholder:n,selectTestId:i,chipTestIdPrefix:l}){const c=s.filter(m=>!a.includes(m)),[d,p]=o.useState(0),u=m=>{p(h=>h+1),r(OB(a,m))};return e.jsxs("div",{className:"space-y-1",children:[a.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:a.map(m=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded border border-slate-200 bg-slate-50 px-1.5 py-0.5 text-xs text-slate-700","data-testid":`${l}-chip-${m}`,children:[Hs(t,m),e.jsx("button",{type:"button","aria-label":`Remove ${Hs(t,m)}`,onClick:()=>r(a.filter(h=>h!==m)),className:"text-slate-400 hover:text-slate-700","data-testid":`${l}-remove-${m}`,children:e.jsx(ur,{className:"h-3 w-3"})})]},m))}),c.length>0&&e.jsxs(sr,{onValueChange:u,children:[e.jsx(rr,{className:"h-8 text-xs","data-testid":i,children:e.jsx(or,{placeholder:n})}),e.jsx(nr,{children:c.map(m=>e.jsx(vs,{value:m,className:"text-xs",children:Hs(t,m)},m))})]},`${a.join("|")}#${d}`)]})}function nw({type:t,currentValue:a,onSelect:s,onCopyToAllComps:r,otherDescriptions:n,onOtherDescriptionChange:i,subjectMode:l}){const c=t==="location",d=c?"SiteInfluenceType":"ViewType",p=o.useMemo(()=>Pr(d)??[],[d]),u=o.useMemo(()=>c?Pr("BodyOfWaterType")??[]:[],[c]),m=o.useMemo(()=>c?[]:Pr("ViewRangeType")??[],[c]),h=o.useMemo(()=>c?[]:Pr("ValueMarketabilityImpactType")??[],[c]),f=o.useMemo(()=>Lv(a),[a]),v=f.join("|"),S=n?.locationBodyOfWater??"",N=f.includes("Other"),x=c&&f.includes("BodyOfWater"),y=T=>n?.[T],b=o.useMemo(()=>c?[]:UU(f,y),[c,f,n]),j=T=>{if(!c&&i)for(const O of VU(f,T,y))i(O.key,O.value);s(T.join("|"),"User")};return Fc(!c&&N,"viewOtherDescription",n?.viewOtherDescription,c?void 0:i),Fc(c&&N,"locationOtherDescription",n?.locationOtherDescription,c?i:void 0),Fc(x,"locationBodyOfWater",S,c?i:void 0),e.jsxs("div",{className:"space-y-2","data-testid":`uad-${t}-selector`,children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:c?"Site Influence (Location)":"View"}),e.jsx(Dv,{schemaElement:d,tokens:f,options:p,onChange:j,placeholder:c?"Add site influence...":"Add view...",selectTestId:`uad-${t}-type-select`,chipTestIdPrefix:`uad-${t}`}),x&&i&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Body of Water"}),e.jsxs(sr,{value:S||void 0,onValueChange:T=>i("locationBodyOfWater",T),children:[e.jsx(rr,{className:"h-8 text-xs","data-testid":"uad-location-water-select",children:e.jsx(or,{placeholder:"Select body of water..."})}),e.jsx(nr,{children:u.map(T=>e.jsx(vs,{value:T,className:"text-xs",children:Hs("BodyOfWaterType",T)},T))})]})]}),c&&N&&i&&e.jsx(Mc,{descFieldName:"locationOtherDescription",value:n?.locationOtherDescription??"",onCommit:i,testId:"uad-location-other-desc"}),!c&&b.length>0&&i&&e.jsx("div",{className:"space-y-2",children:b.map((T,O)=>{const E=kL(O);return e.jsxs("div",{className:"rounded border border-slate-200 bg-slate-50/50 p-1.5 space-y-1.5","data-testid":`uad-view-detail-${O}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:Hs("ViewType",T.viewType)}),l&&e.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-slate-600 cursor-pointer",children:[e.jsx("input",{type:"radio",name:"uad-view-primary",className:"h-3 w-3",checked:T.primary,onChange:()=>i(Av,T.viewType),"data-testid":`uad-view-primary-${O}`}),"Primary"]})]}),e.jsxs(sr,{value:T.viewRange||void 0,onValueChange:R=>{i(E.range,R),R!=="Other"&&(n?.[E.rangeOther]??"")!==""&&i(E.rangeOther,"")},children:[e.jsx(rr,{className:"h-8 text-xs","data-testid":`uad-view-range-select-${O}`,children:e.jsx(or,{placeholder:"Select range..."})}),e.jsx(nr,{children:m.map(R=>e.jsx(vs,{value:R,className:"text-xs",children:Hs("ViewRangeType",R)},R))})]}),T.viewRange==="Other"&&e.jsx(Mc,{descFieldName:E.rangeOther,value:n?.[E.rangeOther]??"",onCommit:i,testId:`uad-view-range-other-desc-${O}`,label:'Describe range "Other"',maxLength:DL}),l&&e.jsxs(sr,{value:T.impact||void 0,onValueChange:R=>i(E.impact,R),children:[e.jsx(rr,{className:"h-8 text-xs","data-testid":`uad-view-impact-select-${O}`,children:e.jsx(or,{placeholder:"Impact to value / marketability..."})}),e.jsx(nr,{children:h.map(R=>e.jsx(vs,{value:R,className:"text-xs",children:Hs("ValueMarketabilityImpactType",R)},R))})]})]},`${T.viewType}-${O}`)})}),!c&&N&&i&&e.jsx(Mc,{descFieldName:"viewOtherDescription",value:n?.viewOtherDescription??"",onCommit:i,testId:"uad-view-other-desc",maxLength:LL}),r&&v&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>r(v,"User"),"data-testid":`uad-${t}-copy-all`,children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function LB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=String(t||""),l=o.useMemo(()=>Pr("FunctionalIssueType")??[],[]);return Fc(i==="Other","functionalUtilityOtherDescription",r?.functionalUtilityOtherDescription,n),e.jsxs("div",{className:"space-y-1.5","data-testid":"uad-functional-utility-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Functional Utility"}),e.jsx("div",{className:"grid grid-cols-2 gap-1",children:l.map(c=>e.jsx("button",{onClick:()=>a(c,"User"),className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all text-left",i===c?"bg-amber-50 border-amber-300 text-amber-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":`uad-fu-${c}`,children:Hs("FunctionalIssueType",c)},c))}),i==="Other"&&n&&e.jsx(Mc,{descFieldName:"functionalUtilityOtherDescription",value:r?.functionalUtilityOtherDescription??"",onCommit:n,testId:"uad-fu-other-desc"}),s&&i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(i,"User"),"data-testid":"uad-fu-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function DB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=o.useMemo(()=>{const x=String(t||"");if(!x||x==="null"||x==="undefined")return{heating:[],cooling:[]};const y=x.split(";");return{heating:Lv(y[0]),cooling:Lv(y[1])}},[t]),l=o.useMemo(()=>Pr("HeatingSystemType")??[],[]),c=o.useMemo(()=>Pr("CoolingSystemType")??[],[]),d=o.useMemo(()=>Pr("HeatingFuelType")??[],[]),p=i.heating,u=i.cooling,[m,h]=o.use
2State(r?.heatingFuel??""),f=x=>{a(`${x.join("|")};${u.join("|")}`,"User")},v=x=>{a(`${p.join("|")};${x.join("|")}`,"User")},S=x=>{h(x),n?.("heatingFuel",x)},N=()=>{s?.(`${p.join("|")};${u.join("|")}`,"User")};return Fc(p.includes("Other"),"heatingOtherDescription",r?.heatingOtherDescription,n),Fc(u.includes("Other"),"coolingOtherDescription",r?.coolingOtherDescription,n),Fc(m==="Other","heatingFuelOtherDescription",r?.heatingFuelOtherDescription,n),e.jsxs("div",{className:"space-y-2","data-testid":"uad-heating-cooling-selector",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Heating Type"}),e.jsx(Dv,{schemaElement:"HeatingSystemType",tokens:p,options:l,onChange:f,placeholder:"Add heating...",selectTestId:"uad-heating-select",chipTestIdPrefix:"uad-heating"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Cooling Type"}),e.jsx(Dv,{schemaElement:"CoolingSystemType",tokens:u,options:c,onChange:v,placeholder:"Add cooling...",selectTestId:"uad-cooling-select",chipTestIdPrefix:"uad-cooling"})]}),n&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Heating Fuel"}),e.jsxs(sr,{value:m||void 0,onValueChange:S,children:[e.jsx(rr,{className:"h-8 text-xs","data-testid":"uad-heating-fuel-select",children:e.jsx(or,{placeholder:"Select fuel..."})}),e.jsx(nr,{children:d.map(x=>e.jsx(vs,{value:x,className:"text-xs",children:Hs("HeatingFuelType",x)},x))})]})]}),p.includes("Other")&&n&&e.jsx(Mc,{descFieldName:"heatingOtherDescription",value:r?.heatingOtherDescription??"",onCommit:n,testId:"uad-heating-other-desc",label:'Describe heating "Other"'}),m==="Other"&&n&&e.jsx(Mc,{descFieldName:"heatingFuelOtherDescription",value:r?.heatingFuelOtherDescription??"",onCommit:n,testId:"uad-heating-fuel-other-desc",label:'Describe fuel "Other"'}),u.includes("Other")&&n&&e.jsx(Mc,{descFieldName:"coolingOtherDescription",value:r?.coolingOtherDescription??"",onCommit:n,testId:"uad-cooling-other-desc",label:'Describe cooling "Other"'}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:N,"data-testid":"uad-hvac-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}const x0=4,Bp=(t,a)=>a===0?t:`${t}${a+1}`,Wf=(t,a)=>a===0?`${t}OtherDescription`:`${t}${a+1}OtherDescription`;function JD({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=o.useMemo(()=>(Pr("CarStorageType")??[]).filter(O=>O!=="None"),[]),l=o.useMemo(()=>Pr("CarStorageAttachmentType")??[],[]),c=o.useMemo(()=>Pr("ImprovedSurfaceMaterialType")??[],[]),[d,p]=o.useState(()=>{const O=String(t||"").trim(),E=G=>r?.[G]??"";return(!O||O==="null"||O==="undefined"||O==="None"?["0"]:O.split(";").map(G=>G.trim()).filter(G=>G!=="")).slice(0,x0).map((G,U)=>{const C=G.match(/^(\d+)\s*(.*)$/);return{count:C?C[1]:G==="0"?"0":"1",type:(C?C[2]:G).trim(),attachment:E(Bp("garageAttachment",U)),area:E(Bp("garageArea",U)),surface:E(Bp("garageSurface",U)),tenOrMore:E(Bp("garageTenOrMore",U))==="true",otherDesc:E(Wf("garageCarport",U)),surfaceOtherDesc:E(Wf("garageSurface",U))}})}),u=O=>O==="Garage"||O==="Carport",m=O=>/Driveway/i.test(O),h=O=>{const E=O.filter(R=>R.count!=="0").map(R=>R.type?`${R.count} ${R.type}`:R.count);return E.length?E.join("; "):"None"},f=O=>{if(!n)return;const E=(R,G)=>{(r?.[R]??"")!==G&&n(R,G)};for(let R=0;R<x0;R++){const G=O[R],U=!!G&&G.count!=="0",C=U&&u(G.type),F=U&&m(G.type);E(Bp("garageAttachment",R),C?G.attachment:""),E(Bp("garageArea",R),C?G.area.trim():""),E(Bp("garageSurface",R),F?G.surface:""),E(Bp("garageTenOrMore",R),F&&G.tenOrMore?"true":""),E(Wf("garageCarport",R),U&&G.type==="Other"?G.otherDesc:""),E(Wf("garageSurface",R),F&&G.surface==="Other"?G.surfaceOtherDesc:"")}},v=O=>{p(O),a(h(O),"User"),f(O)},S=(O,E,R=!0)=>{const G=d.map((U,C)=>C===O?{...U,...E}:U);R?v(G):p(G)},N=()=>{d.length>=x0||v([...d,{count:"1",type:"",attachment:"",area:"",surface:"",tenOrMore:!1,otherDesc:"",surfaceOtherDesc:""}])},x=O=>{const E=d.filter((R,G)=>G!==O);v(E.length?E:[{count:"0",type:"",attachment:"",area:"",surface:"",tenOrMore:!1,otherDesc:"",surfaceOtherDesc:""}])},y=O=>{f(d)},b=(O,E)=>(R,G)=>{p(U=>U.map((C,F)=>F===O?{...C,[E]:G}:C)),n?.(R,G)},j=()=>{s?.(h(d),"User"),f(d)},T=(O,E)=>E===0?`uad-garage-${O}`:`uad-garage-${O}-i${E+1}`;return e.jsxs("div",{className:"space-y-2","data-testid":"uad-garage-selector",children:[d.map((O,E)=>{const R=O.count!=="0",G=R&&u(O.type),U=R&&m(O.type);return e.jsxs("div",{className:Q("space-y-2",E>0&&"border-t border-slate-200 pt-2"),children:[d.length>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-[10px] uppercase text-slate-500 font-semibold",children:["Vehicle Storage ",E+1]}),e.jsx("button",{onClick:()=>x(E),className:"text-[10px] text-slate-400 hover:text-rose-500 font-medium","data-testid":T("remove",E),children:"Remove"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Number of Spaces"}),e.jsx("div",{className:"flex gap-1",children:["0","1","2","3","4"].map(C=>e.jsx("button",{onClick:()=>S(E,{count:C}),className:Q("flex-1 px-2 py-1.5 text-xs font-medium rounded border transition-all",O.count===C?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":T(`count-${C}`,E),children:C},C))})]}),R&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Vehicle Storage Type"}),e.jsxs(sr,{value:O.type||void 0,onValueChange:C=>S(E,{type:C}),children:[e.jsx(rr,{className:"h-8 text-xs","data-testid":T("type-select",E),children:e.jsx(or,{placeholder:"Select type..."})}),e.jsx(nr,{children:i.map(C=>e.jsx(vs,{value:C,className:"text-xs",children:Hs("CarStorageType",C)},C))})]})]}),R&&O.type==="Other"&&n&&e.jsx(Mc,{descFieldName:Wf("garageCarport",E),value:O.otherDesc,onCommit:b(E,"otherDesc"),testId:T("other-desc",E)}),G&&n&&e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Attachment"}),e.jsxs(sr,{value:O.attachment||void 0,onValueChange:C=>S(E,{attachment:C}),children:[e.jsx(rr,{className:"h-8 text-xs","data-testid":T("attachment-select",E),children:e.jsx(or,{placeholder:"Select..."})}),e.jsx(nr,{children:l.map(C=>e.jsx(vs,{value:C,className:"text-xs",children:Hs("CarStorageAttachmentType",C)},C))})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Area (sq ft)"}),e.jsx(ze,{...Mo,type:"number",value:O.area,onChange:C=>S(E,{area:C.target.value},!1),onBlur:()=>y(),onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),y())},placeholder:"e.g. 440",className:"h-8 text-xs","data-testid":T("area-input",E)}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-0.5",children:"Optional for comps — include if known"})]})]}),U&&n&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Surface"}),e.jsxs(sr,{value:O.surface||void 0,onValueChange:C=>S(E,{surface:C}),children:[e.jsx(rr,{className:"h-8 text-xs","data-testid":T("surface-select",E),children:e.jsx(or,{placeholder:"Select surface..."})}),e.jsx(nr,{children:c.map(C=>e.jsx(vs,{value:C,className:"text-xs",children:Hs("ImprovedSurfaceMaterialType",C)},C))})]}),O.surface==="Other"&&e.jsx(Mc,{descFieldName:Wf("garageSurface",E),value:O.surfaceOtherDesc,onCommit:b(E,"surfaceOtherDesc"),testId:T("surface-other
2-desc",E),label:'Describe surface "Other"'}),e.jsxs("label",{className:"flex items-center gap-1.5 mt-2 text-xs text-slate-700 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:O.tenOrMore,onChange:C=>S(E,{tenOrMore:C.target.checked}),"data-testid":T("ten-or-more",E)}),"Ten or more parking spaces"]})]})]},E)}),d.length<x0&&e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs border-dashed",onClick:N,"data-testid":"uad-garage-add-instance",children:[e.jsx(un,{className:"w-3 h-3 mr-1.5"}),"Add vehicle storage"]}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:j,"data-testid":"uad-garage-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy ",h(d)," to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function kB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=String(t??""),l=o.useMemo(()=>Pr("ArchitecturalDesignCategoryType")??[],[]);return Fc(i==="Other","designOtherDescription",r?.designOtherDescription,n),e.jsxs("div",{className:"space-y-2","data-testid":"uad-design-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Design (Style)"}),e.jsx("div",{className:"grid grid-cols-2 gap-1",children:l.map(c=>e.jsx("button",{onClick:()=>a(c,"User"),className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all text-left",i===c?"bg-indigo-50 border-indigo-300 text-indigo-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":`uad-design-${c}`,children:Hs("ArchitecturalDesignCategoryType",c)},c))}),i==="Other"&&n&&e.jsx(Mc,{descFieldName:"designOtherDescription",value:r?.designOtherDescription??"",onCommit:n,testId:"uad-design-other-desc"}),s&&i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(i,"User"),"data-testid":"uad-design-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function MB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=cp(String(t||"")),l=o.useMemo(()=>(Pr("SaleType")??[]).filter(c=>c!=="Other"),[]);return Fc(i==="Other","saleTypeOtherDescription",r?.saleTypeOtherDescription,n),e.jsxs("div",{className:"space-y-1.5","data-testid":"uad-sale-type-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Transfer Terms"}),e.jsx(Kd,{value:i==="Other"?r?.saleTypeOtherDescription??"":i?Hs("SaleType",i):"",suggestions:l.map(c=>Hs("SaleType",c)),compact:!0,maxLength:33,testId:"uad-sale-type-select",ariaLabel:"Transfer Terms",onChange:c=>{const d=c.trim(),p=l.find(u=>u.toLowerCase()===d.toLowerCase()||Hs("SaleType",u).toLowerCase()===d.toLowerCase());a(d?p??"Other":"","User"),n?.("saleTypeOtherDescription",p||!d?"":d.slice(0,33))}}),s&&i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(i,"User"),"data-testid":"uad-sale-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function FB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=String(t||""),l=o.useMemo(()=>(Pr("MortgageType")??[]).filter(c=>c!=="Other"),[]);return e.jsxs("div",{className:"space-y-1.5","data-testid":"uad-financing-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Financing Type"}),e.jsx(Kd,{value:i==="Other"?r?.financingOtherDescription??"":i==="Cash"?"Cash":i?Hs("MortgageType",i):"",suggestions:["Cash",...l.map(c=>Hs("MortgageType",c))],compact:!0,maxLength:21,testId:"uad-financing-select",ariaLabel:"Financing Type",onChange:c=>{const d=c.trim(),p=d.toLowerCase(),u=p==="cash"||p==="cash / no financing",m=l.find(f=>f.toLowerCase()===p||Hs("MortgageType",f).toLowerCase()===p);a(d?u?"Cash":m??"Other":"","User"),n?.("financingOtherDescription",!d||u||m?"":d.slice(0,21))}}),s&&i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(i,"User"),"data-testid":"uad-fin-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function _B({currentValue:t,onSelect:a,onCopyToAllComps:s}){const r=o.useMemo(()=>{const m=String(t||"");return!m||m==="None"||m==="null"?{hasConc:!1,amount:""}:{hasConc:!0,amount:m.replace(/[^0-9]/g,"")}},[t]),[n,i]=o.useState(r.hasConc),[l,c]=o.useState(r.amount),d=(m,h)=>
2m&&h?`$${Number(h).toLocaleString()}`:"None",p=()=>{i(!1),c(""),a("None","User")},u=()=>{a(d(n,l),"User")};return e.jsxs("div",{className:"space-y-2","data-testid":"uad-concessions-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Concessions"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[e.jsx("button",{onClick:p,className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all",n?"bg-white border-slate-200 text-slate-700 hover:bg-slate-50":"bg-green-50 border-green-300 text-green-700"),"data-testid":"uad-conc-none",children:"None"}),e.jsx("button",{onClick:()=>i(!0),className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all",n?"bg-amber-50 border-amber-300 text-amber-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":"uad-conc-amount-toggle",children:"Concession"})]}),n&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Dollar Amount"}),e.jsx(ze,{...Mo,type:"number",value:l,onChange:m=>c(m.target.value),onBlur:u,onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),u())},placeholder:"e.g. 5000",className:"h-8 text-xs","data-testid":"uad-conc-amount"})]}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:()=>s(d(n,l),"User"),"data-testid":"uad-conc-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function UB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=o.useMemo(()=>qI(t),[t]),l=o.useMemo(()=>(Pr("SaleType")??[]).filter(C=>C!=="Other"),[]),c=o.useMemo(()=>(Pr("MortgageType")??[]).filter(C=>C!=="Other"),[]),[d,p]=o.useState(i.saleType||"TypicallyMotivated"),[u,m]=o.useState(i.financing),[h,f]=o.useState(i.noFinancing),[v,S]=o.useState(i.concession!=null&&i.concession>0),[N,x]=o.useState(i.concession!=null&&i.concession>0?String(i.concession):""),y=v&&N&&Number(N)||null,b=d||"TypicallyMotivated",j=()=>Pv(b,u,h,y),T=C=>{const F=(C?.saleType??d)||"TypicallyMotivated",A=C?.noFinancing??h,M=C?.financing??u,B=C&&"conc"in C?C.conc??null:y;n&&(n("saleType",F),n("financing",A?"":M),n("concessions",B!=null?String(B):"0")),a(Pv(F,M,A,B),"User")},O=C=>{const F=C.trim(),A=l.find(B=>B.toLowerCase()===F.toLowerCase()||Hs("SaleType",B).toLowerCase()===F.toLowerCase()),M=F?A??"Other":"";p(M),n?.("saleTypeOtherDescription",!F||A?"":F.slice(0,33)),T({saleType:M})},E=C=>{const F=C.trim(),A=F.toLowerCase(),M=A==="cash"||A==="cash / no financing",B=c.find(ae=>ae.toLowerCase()===A||Hs("MortgageType",ae).toLowerCase()===A),oe=F?M?"":B??"Other":"";f(M),m(oe),n?.("financingOtherDescription",!F||M||B?"":F.slice(0,21)),T({financing:oe,noFinancing:M})},R=()=>{S(!1),x(""),T({conc:null})},G=()=>{T({conc:N&&Number(N)||null})},U=()=>{n&&(n("saleType",b),n("financing",h?"":u),n("concessions",y!=null?String(y):"0")),s?.(j(),"User")};return Fc(d==="Other","saleTypeOtherDescription",r?.saleTypeOtherDescription,n),Fc(!h&&u==="Other","financingOtherDescription",r?.financingOtherDescription,n),e.jsxs("div",{className:"space-y-2","data-testid":"uad-financing-concessions-selector",children:[e.jsx("p",{className:"text-[10px] text-slate-400 italic",children:"UAD 3.6: sale type · financing · concession $"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Sale Type"}),e.jsx(Kd,{value:d==="Other"?r?.saleTypeOtherDescription??"":d?Hs("SaleType",d):"",suggestions:l.map(C=>Hs("SaleType",C)),compact:!0,maxLength:33,testId:"uad-fc-sale-type-select",ariaLabel:"Transfer Terms",onChange:O})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Financing Type"}),e.jsx(Kd,{value:h?"Cash":u==="Other"?r?.financingOtherDescription??"":u?Hs("MortgageType",u):"",suggestions:["Cash",...c.map(C=>Hs("MortgageType",C))],compact:!0,maxLength:21,testId:"uad-fc-fin-select",ariaLabel:"Financing Type",onChange:E})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Concession Amount ($)"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[e.jsx("button",{onClick:R,className:Q("px-2 py-1 text-[10px] font-medium rounded border transition-all",v?"bg-white border-slate-200 text-slate-700 hover:bg-slate-50":"bg-green-50 border-green-300 text-green-700"),"data-testid":"uad-fc-conc-none",children:"None"}),e.jsx("button",{onClick:()=>S(!0),className:Q("px-2 py-1 text-[10px] font-medium rounded border transition-all",v?"bg-amber-50 border-amber-300 text-amber-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":"uad-fc-conc-amount-toggle",children:"Concession"})]}),v&&e.jsx(ze,{...Mo,type:"number",value:N,onChange:C=>x(C.target.value),onBlur:G,onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),G())},placeholder:"$ Amount",className:"h-7 text-xs mt-1","data-testid":"uad-fc-conc-amount"})]}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:U,"data-testid":"uad-fc-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function VB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=String(t??""),l=o.useMemo(()=>Pr("PropertyEstateType")??[],[]);return Fc(i==="Other","leaseholdFeeSimpleOtherDescription",r?.leaseholdFeeSimpleOtherDescription,n),e.jsxs("div",{className:"space-y-1.5","data-testid":"uad-leasehold-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Property Rights"}),e.jsx("div",{className:"flex gap-1",children:l.map(c=>e.jsx("button",{onClick:()=>a(c,"User"),className:Q("flex-1 px-2 py-1.5 text-xs font-medium rounded border transition-all",i===c?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":`uad-lease-${c}`,children:Hs("PropertyEstateType",c)},c))}),i==="Other"&&n&&e.jsx(Mc,{descFieldName:"leaseholdFeeSimpleOtherDescription",value:r?.leaseholdFeeSimpleOtherDescription??"",onCommit:n,testId:"uad-lease-other
2-desc"}),s&&i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(i,"User"),"data-testid":"uad-lease-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function $B({currentValue:t,onSelect:a,onCopyToAllComps:s}){const r=String(t??""),n=o.useMemo(()=>Pr("ListingStatusType")??["Active","OffMarket","Pending","SettledSale"],[]);return e.jsxs("div",{className:"space-y-1.5","data-testid":"uad-listing-status-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Listing Status"}),e.jsx("div",{className:"grid grid-cols-2 gap-1",children:n.map(i=>e.jsx("button",{onClick:()=>a(i,"User"),className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all",r===i?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":`uad-listing-status-${i}`,children:Hs("ListingStatusType",i)},i))}),s&&r&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(r,"User"),"data-testid":"uad-listing-status-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function BB({currentValue:t,onSelect:a,onCopyToAllComps:s}){const r=String(t??""),n=o.useMemo(()=>Pr("AttachmentType")??["Attached","Detached"],[]);return e.jsxs("div",{className:"space-y-1.5","data-testid":"uad-attached-detached-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Attached / Detached"}),e.jsx("div",{className:"flex gap-1",children:n.map(i=>e.jsx("button",{onClick:()=>a(i,"User"),className:Q("flex-1 px-2 py-1.5 text-xs font-medium rounded border transition-all",r===i?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":`uad-attached-detached-${i}`,children:Hs("AttachmentType",i)},i))}),s&&r&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(r,"User"),"data-testid":"uad-attached-detached-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function zB({currentValue:t,onSelect:a,onCopyToAllComps:s,uad36:r}){const n=o.useMemo(()=>{const E=String(t||""),R=E.match(/s(\d{2}\/\d{2})/),G=E.match(/c(\d{2}\/\d{2})/);return{saleDate:R?.[1]||"",contractDate:G?.[1]||""}},[t]),[i,l]=o.useState(n.saleDate.split("/")[0]||""),[c,d]=o.useState(n.saleDate.split("/")[1]||""),[p,u]=o.useState(n.contractDate.split("/")[0]||""),[m,h]=o.useState(n.contractDate.split("/")[1]||""),f=["01","02","03","04","05","06","07","08","09","10","11","12"],v=new Date().getFullYear()%100,S=Array.from({length:6},(E,R)=>String(v-R).padStart(2,"0")),N=(E,R,G,U)=>{const C=[];return E&&R&&C.push(`s${E}/${R}`),G&&U&&C.push(`c${G}/${U}`),C.join(";")},x=(E,R,G,U)=>{const C=N(E,R,G,U);C&&a(C,"User")},y=E=>{l(E),x(E,c,p,m)},b=E=>{d(E),x(i,E,p,m)},j=E=>{u(E),x(i,c,E,m)},T=E=>{h(E),x(i,c,p,E)},O=()=>{const E=N(i,c,p,m);E&&s?.(E,"User")};return e.jsxs("div",{className:"space-y-2","data-testid":"uad-date-of-sale-selector",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Sale/Close Date (s mm/yy)"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(sr,{value:i,onValueChange:y,children:[e.jsx(rr,{className:"h-7 text-xs flex-1","data-testid":"uad-sale-month",children:e.jsx(or,{placeholder:"MM"})}),e.jsx(nr,{children:f.map(E=>e.jsx(vs,{value:E,className:"text-xs",children:E},E))})]}),e.jsxs(sr,{value:c,onValueChange:b,children:[e.jsx(rr,{className:"h-7 text-xs flex-1","data-testid":"uad-sale-year",children:e.jsx(or,{placeholder:"YY"})}),e.jsx(nr,{children:S.map(E=>e.jsx(vs,{value:E,className:"text-xs",children:E},E))})]})]})]}),r?e.jsx("p",{className:"text-[10px] text-slate-400 leading-snug","data-testid":"uad-date-contract-moved-note",children:"Contract date is edited on its own “Contract Date” row."}):e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Contract Date (c mm/yy)"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(sr,{value:p,onValueChange:j,children:[e.jsx(rr,{className:"h-7 text-xs flex-1","data-testid":"uad-contract-month",children:e.jsx(or,{placeholder:"MM"})}),e.jsx(nr,{children:f.map(E=>e.jsx(vs,{value:E,className:"text-xs",children:E},E))})]}),e.jsxs(sr,{value:m,onValueChange:T,children:[e.jsx(rr,{className:"h-7 text-xs flex-1","data-testid":"uad-contract-year",children:e.jsx(or,{placeholder:"YY"})}),e.jsx(nr,{children:S.map(E=>e.jsx(vs,{value:E,className:"text-xs",children:E},E))})]})]})]}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:O,"data-testid":"uad-date-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function qB({currentValue:t,onSelect:a,onCopyToAllComps:s,uad36:r,basementHint:n}){const i=o.useMemo(()=>{const B=String(t||"").trim();if(!B||B==="None"||B==="–"||B==="null")return{totalSf:"",finishedSf:""};let oe="",ae="";const D=B.match(/^(\d+)\s*\/\s*(\d+)\s*sf/i);
2if(D)oe=D[1],ae=D[2];else{const _=B.match(/^(\d+)\s*sf\s*;\s*(\d+)\s*sfin/i);_&&(oe=_[1],ae=_[2])}return{totalSf:oe,finishedSf:ae}},[t]),l=i.totalSf===""?null:Number(i.totalSf),c=i.finishedSf===""?null:Number(i.finishedSf),d=l!==null&&c!==null&&c>l,p=i.totalSf!==""&&Number(i.totalSf)===0&&Number(i.finishedSf||"0")===0,[u,m]=o.useState(n?.basementType===null&&n?.styleCategory==="bilevel"?!0:r?!p&&String(t||"")!=="None":i.totalSf!==""||String(t||"")!=="None"),[h,f]=o.useState(i.totalSf),[v,S]=o.useState(i.finishedSf),[N,x]=o.useState(null),[y,b]=o.useState(null),[j,T]=o.useState(()=>l===null||c===null||c>l?"":String(l-c)),[O,E]=o.useState(d),R=!r&&u&&Number(v||"0")>Number(h||"0"),G=Number(v||"0")+Number(j||"0"),U=r?"0/0 sf":"None",C=()=>{if(!u)return U;if(r){const B=Number(v||"0");return`${B+Number(j||"0")}/${B} sf`}return`${h||"0"}/${v||"0"} sf`},F=()=>{m(!1),f(r?"0":""),S(r?"0":""),T(r?"0":""),E(!1),a(U,"User")},A=()=>{u&&(R||(E(!1),a(C(),"User")))},M=B=>{B.key==="Enter"&&(B.preventDefault(),A())};return e.jsxs("div",{className:"space-y-2","data-testid":"uad-basement-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Below Grade Area"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:F,className:Q("flex-1 px-2 py-1.5 text-xs font-medium rounded border transition-all",u?"bg-white border-slate-200 text-slate-500 hover:bg-slate-50":"bg-slate-100 border-slate-400 text-slate-700"),"data-testid":"uad-bsmt-none",children:"No Below Grade"}),e.jsx("button",{onClick:()=>m(!0),className:Q("flex-1 px-2 py-1.5 text-xs font-medium rounded border transition-all",u?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-slate-200 text-slate-500 hover:bg-slate-50"),"data-testid":"uad-bsmt-yes",children:"Has Below Grade"})]}),u&&n&&e.jsxs("div",{className:"rounded border border-amber-200 bg-amber-50 p-2 space-y-1.5",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-amber-800 flex items-center gap-1",children:[e.jsx(ul,{className:"w-3 h-3 shrink-0"}),"Estimate Below Grade Area"]}),e.jsx("p",{className:"text-[10px] text-amber-700 leading-snug",children:n.basementType!==null?e.jsxs(e.Fragment,{children:["MLS: ",e.jsx("span",{className:"font-medium",children:n.basementType})," basement, no SF reported"]}):n.styleCategory==="bilevel"?"Bi-level — no basement listed; common to have one":"No basement reported — estimate if one exists"}),e.jsx("p",{className:"text-[10px] font-medium text-slate-600 pt-0.5",children:"Step 1 — Total size"}),e.jsx("div",{className:"space-y-0.5",children:[100,50,30].map(B=>{const oe=Math.round(n.gla*B/100),ae=N===oe;return e.jsxs("button",{type:"button",onClick:()=>{x(ae?null:oe),b(null)},className:Q("w-full flex items-center justify-between px-2 py-1 rounded border transition-colors text-left text-[11px]",ae?"bg-amber-200 border-amber-400 text-amber-900 font-semibold":"bg-white border-slate-200 text-slate-700 hover:bg-amber-100 hover:border-amber-300"),"data-testid":`bsmt-step1-${B}`,children:[e.jsxs("span",{children:[B,"% of GLA"]}),e.jsxs("span",{className:"tabular-nums text-slate-500",children:[oe.toLocaleString()," sf"]})]},B)})}),N!==null&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[10px] font-medium text-slate-600 pt-0.5",children:"Step 2 — Finished portion"}),e.jsx("div",{className:"space-y-0.5",children:[{label:"100% finished",finPct:100},{label:"50% finished",finPct:50},{label:"0% finished — all unfinished",finPct:0}].map(({label:B,finPct:oe})=>{const ae=Math.round(N*oe/100),D=N-ae;return e.jsxs("button",{type:"button",onClick:()=>{const _=`${N}/${ae} sf`;b(oe),r?(S(String(ae)),T(String(D))):(f(String(N)),S(String(ae))),a(_,"User")},className:Q("w-full flex items-center justify-between px-2 py-1 rounded border transition-colors text-left text-[11px]",y===oe?"bg-blue-100 border-blue-400 text-blue-900 font-semibold":"bg-white border-slate-200 text-slate-700 hover:bg-blue-50 hover:border-blue-300"),"data-testid":`bsmt-step2-${oe}`,children:[e.jsx("span",{children:B}),e.jsxs("span",{className:"tabular-nums text-slate-500",children:[N.toLocaleStr
2ing()," / ",ae.toLocaleString()," sf"]})]},oe)})})]}),e.jsx("p",{className:"text-[10px] text-slate-400 leading-snug pt-0.5",children:"Appraiser rule of thumb — verify before finalizing."})]}),u&&r&&e.jsxs(e.Fragment,{children:[O&&e.jsxs("p",{className:"text-[10px] text-amber-700 bg-amber-50 border border-amber-200 rounded px-1.5 py-1","data-testid":"uad-bsmt-bad-legacy-warning",children:["Stored value looks inconsistent: finished area (",(c??0).toLocaleString()," sf) exceeds the stored total (",(l??0).toLocaleString()," sf). Re-enter the areas below to correct it."]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Finished SF"}),e.jsx(ze,{...Mo,type:"number",value:v,onChange:B=>S(B.target.value),onBlur:A,onKeyDown:M,placeholder:"e.g. 400",className:"h-7 text-xs","data-testid":"uad-bsmt-finished"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Unfinished SF"}),e.jsx(ze,{...Mo,type:"number",value:j,onChange:B=>T(B.target.value),onBlur:A,onKeyDown:M,placeholder:"e.g. 400",className:"h-7 text-xs","data-testid":"uad-bsmt-unfinished"})]})]}),e.jsxs("p",{className:"text-[10px] text-slate-500","data-testid":"uad-bsmt-total-readout",children:["Total below grade: ",e.jsxs("span",{className:"font-medium text-slate-700",children:[G.toLocaleString()," sf"]})]})]}),u&&!r&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Total SF"}),e.jsx(ze,{...Mo,type:"number",value:h,onChange:B=>f(B.target.value),onBlur:A,onKeyDown:M,placeholder:"e.g. 800",className:"h-7 text-xs","data-testid":"uad-bsmt-total"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Finished SF"}),e.jsx(ze,{...Mo,type:"number",value:v,onChange:B=>S(B.target.value),onBlur:A,onKeyDown:M,placeholder:"e.g. 400",className:"h-7 text-xs","data-testid":"uad-bsmt-finished"})]})]}),R&&e.jsx("p",{className:"text-[10px] text-red-600 bg-red-50 border border-red-200 rounded px-1.5 py-1","data-testid":"uad-bsmt-error",children:"Finished area can't exceed total area — the value won't be saved until it's corrected."})]}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",disabled:R,onClick:()=>{R||s(C(),"User")},"data-testid":"uad-bsmt-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function YB({currentValue:t,onSelect:a,onCopyToAllComps:s}){const r=o.useMemo(()=>{const f=String(t||""),v=f.match(/(\d+)\s*rr/),S=f.match(/(\d+)\s*br/),N=f.match(/([\d.]+)\s*ba/);return{recRooms:v?.[1]||"0",bedrooms:S?.[1]||"0",bathrooms:N?.[1]||"0"}},[t]),[n,i]=o.useState(r.recRooms),[l,c]=o.useState(r.bedrooms),[d,p]=o.useState(r.bathrooms),u=()=>`${n||"0"}rr ${l||"0"}br ${d||"0"}ba`,m=()=>{a(u(),"User")},h=f=>{f.key==="Enter"&&(f.preventDefault(),m())};return e.jsxs("div",{className:"space-y-2","data-testid":"uad-below-grade-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Below Grade Rooms"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Rec Rooms"}),e.jsx(ze,{...Mo,type:"number",min:"0",value:n,onChange:f=>i(f.target.value),onBlur:m,onKeyDown:h,placeholder:"0",className:"h-7 text-xs","data-testid":"uad-bg-rr"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Bedrooms"}),e.jsx(ze,{...Mo,type:"number",min:"0",value:l,onChange:f=>c(f.target.value),onBlur:m,onKeyDown:h,placeholder:"0",className:"h-7 text-xs","data-testid":"uad-bg-br"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Baths"}),e.jsx(ze,{...Mo,value:d,onChange:f=>p(f.target.value),onBlur:m,onKeyDown:h,placeholder:"e.g. 1.1",className:"h-7 text-xs","data-testid":"uad-bg-ba"}),e.jsx("p",{className:"text-[9px] text-slate-400 mt-0.5",children:"Full.Half (e.g. 1.1)"})]})]}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:()=>s(`${n}rr ${l}br ${d}ba`,"User"),"data-testid":"uad-bg-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy ",n,"rr ",l,"br ",d,"ba to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function GB({currentValue:t,onSelect:a,onCopyToAllComps:s}){const r=o.useMemo(()=>{const v=String(t||"").split("|").map(S=>S.trim());return{totalRooms:v[0]||"",bedrooms:v[1]||"",bathrooms:v[2]||""}},[t]),[n,i]=o.useState(r.totalRooms),[l,c]=o.useState(r.bedrooms),[d,p]=o.use
2State(r.bathrooms),u=()=>`${n||"0"}|${l||"0"}|${d||"0"}`,m=()=>{a(u(),"User")},h=f=>{f.key==="Enter"&&(f.preventDefault(),m())};return e.jsxs("div",{className:"space-y-2","data-testid":"uad-above-grade-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Above Grade Room Count"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Total Rooms"}),e.jsx(ze,{...Mo,type:"number",min:"0",value:n,onChange:f=>i(f.target.value),onBlur:m,onKeyDown:h,placeholder:"Total",className:"h-7 text-xs","data-testid":"uad-ag-total"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Bedrooms"}),e.jsx(ze,{...Mo,type:"number",min:"0",value:l,onChange:f=>c(f.target.value),onBlur:m,onKeyDown:h,placeholder:"Beds",className:"h-7 text-xs","data-testid":"uad-ag-beds"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-slate-500 mb-0.5",children:"Bathrooms"}),e.jsx(ze,{...Mo,value:d,onChange:f=>p(f.target.value),onBlur:m,onKeyDown:h,placeholder:"e.g. 2.1",className:"h-7 text-xs","data-testid":"uad-ag-baths"}),e.jsx("p",{className:"text-[9px] text-slate-400 mt-0.5",children:"Full.Half (e.g. 2.1)"})]})]}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:()=>s(u(),"User"),"data-testid":"uad-ag-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy ",n||"0","|",l||"0","|",d||"0"," to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function HB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=o.useMemo(()=>YI(t),[t]),[l,c]=o.useState(i.amenityTypes),[d,p]=o.useState(i.comparison),u=l.length===1&&l[0]==="None",m=()=>BA(l,d),h=x=>{const y=D0(x),b=y.length===1&&y[0]==="None";c(y),n?.("amenityType",y.join("|")),a(BA(y,b?"":d),"User")},f=x=>{p(x),n?.("amenityType",l.join("|")),a(BA(l,x),"User")},v=()=>{n?.("amenityType",l.join("|")),s?.(m(),"User")};o.useEffect(()=>{u&&d&&p("")},[u,d]);const S=l.includes("Other");Fc(S,"amenityTypeOtherDescription",r?.amenityTypeOtherDescription,n);const N=l.length>0&&!u;return e.jsxs("div",{className:"space-y-2","data-testid":"uad-porch-selector",children:[e.jsx("p",{className:"text-[10px] text-slate-400 italic",children:"UAD 3.6: amenity types · comparison vs. subject"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Amenity Types"}),e.jsx(Dv,{schemaElement:"AmenityType",tokens:l,options:gB,onChange:h,placeholder:"Add amenity...",selectTestId:"uad-porch-type-select",chipTestIdPrefix:"uad-porch"}),S&&n&&e.jsx(Mc,{descFieldName:"amenityTypeOtherDescription",value:r?.amenityTypeOtherDescription??"",onCommit:n,testId:"uad-porch-other-desc"})]}),N&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:"Comparison vs. Subject"}),e.jsxs("div",{className:"grid grid-cols-4 gap-1",children:[e.jsx("button",{onClick:()=>f(""),className:Q("px-1.5 py-1 text-[10px] font-medium rounded border transition-all",d?"bg-white border-slate-200 text-slate-700 hover:bg-slate-50":"bg-slate-100 border-slate-400 text-slate-700"),"data-testid":"uad-porch-cmp-none",children:"—"}),KD.map(x=>e.jsx("button",{onClick:()=>f(x),className:Q("px-1.5 py-1 text-[10px] font-medium rounded border transition-all",d===x?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":`uad-porch-cmp-${x}`,children:x},x))]})]}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:v,"data-testid":"uad-porch-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function WB({currentValue:t,onSelect:a,onCopyToAllComps:s}){const r=o.useMemo(()=>{const h=String(t||""),f=h.match(/([\d.]+)\s*ac/i),v=h.match(/([\d,]+)\s*sf/i);return f?{size:f[1],unit:"ac"}:v?{size:v[1].replace(/,/g,""),unit:"sf"}:{size:h.match(/([\d,.]+)/)?.[1]?.replace(/,/g,"")||"",unit:"sf"}},[t]),[n,i]=o.useState(r.size),[l,c]=o.useState(r.unit),d=(h,f)=>{if(h==="")return"";const v=Number(h);return Number.isFinite(v)?f==="ac"?`${v.toFixed(2)}
2 ac`:`${v.toLocaleString()} sf`:""},p=h=>{if(h===l)return;let f=n;if(n&&Number(n)>0){const v=Number(n);h==="ac"?f=(v/43560).toFixed(4).replace(/0+$/,"").replace(/\.$/,""):f=String(Math.round(v*43560)),i(f)}c(h),f!==""&&a(d(f,h),"User")},u=()=>{a(d(n,l),"User")},m=()=>{s&&s(d(n,l),"User")};return e.jsxs("div",{className:"space-y-2","data-testid":"uad-site-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Site / Lot Size"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>p("sf"),className:Q("flex-1 px-2 py-1.5 text-xs font-medium rounded border transition-all",l==="sf"?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-slate-200 hover:bg-slate-50"),"data-testid":"uad-site-sf",children:"Square Feet"}),e.jsx("button",{onClick:()=>p("ac"),className:Q("flex-1 px-2 py-1.5 text-xs font-medium rounded border transition-all",l==="ac"?"bg-blue-50 border-blue-300 text-blue-700":"bg-white border-slate-200 hover:bg-slate-50"),"data-testid":"uad-site-ac",children:"Acres"})]}),e.jsx(ze,{...Mo,type:"number",value:n,onChange:h=>i(h.target.value),onBlur:u,onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),u())},placeholder:l==="ac"?"e.g. 0.25":"e.g. 8500",className:"h-8 text-xs","data-testid":"uad-site-size"}),s&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs",onClick:m,"data-testid":"uad-site-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy ",n===""?"":`${d(n,l)} `,"to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function KB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=String(t||""),l=o.useMemo(()=>Pr("DataSourceType")??[],[]);return Fc(i==="Other","dataSourceOtherDescription",r?.dataSourceOtherDescription,n),e.jsxs("div",{className:"space-y-2","data-testid":"uad-data-source-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Data Source"}),e.jsxs(sr,{value:i||void 0,onValueChange:c=>a(c,"User"),children:[e.jsx(rr,{className:"h-8 text-xs","data-testid":"uad-data-source-select",children:e.jsx(or,{placeholder:"Select data source..."})}),e.jsx(nr,{children:l.map(c=>e.jsx(vs,{value:c,className:"text-xs",children:Hs("DataSourceType",c)},c))})]}),i==="Other"&&n&&e.jsx(Mc,{descFieldName:"dataSourceOtherDescription",value:r?.dataSourceOtherDescription??"",onCommit:n,testId:"uad-data-source-other-desc"}),n&&e.jsx(Mc,{descFieldName:"dataSourceIdentifier",value:r?.dataSourceIdentifier??"",onCommit:n,testId:"uad-data-source-identifier",label:"Data source identifier (e.g. MLS #)"}),s&&i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(i,"User"),"data-testid":"uad-data-source-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}function QB({currentValue:t,onSelect:a,onCopyToAllComps:s,otherDescriptions:r,onOtherDescriptionChange:n}){const i=String(t||""),l=o.useMemo(()=>Pr("ConstructionMethodType")??[],[]);return Fc(i==="Other","constructionMethodOtherDescription",r?.constructionMethodOtherDescription,n),e.jsxs("div",{className:"space-y-1.5","data-testid":"uad-construction-method-selector",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium",children:"Construction Method"}),e.jsx("div",{className:"grid grid-cols-2 gap-1",children:l.map(c=>e.jsx("button",{onClick:()=>a(c,"User"),className:Q("px-2 py-1.5 text-xs font-medium rounded border transition-all text-left",i===c?"bg-teal-50 border-teal-300 text-teal-700":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":`uad-construction-method-${c}`,children:Hs("ConstructionMethodType",c)},c))}),i==="Other"&&n&&e.jsx(Mc,{descFieldName:"constructionMethodOtherDescription",value:r?.constructionMethodOtherDescription??"",onCommit:n,testId:"uad-construction-method-other-desc"}),s&&i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs mt-2",onClick:()=>s(i,"User"),"data-testid":"uad-construction-method-copy-all",children:[e.jsx(jr,{className:"w-3 h-3 mr-1.5"}),"Copy to all comps"]})}),e.jsx(Wa,{children:"Apply to all comparable properties"})]})]})}const ZB=[{value:"Q1",label:"Q1"},{value:"Q2",label:"Q2"},{value:"Q3",label:"Q3"},{value:"Q4",label:"Q4"},{value:"Q5",label:"Q5"},{value:"Q6",label:"Q6"}],JB=[{value:"C1",label:"C1"},{value:"C2",label:"C2"},{value:"C3",label:"C3"},{value:"C4",label:"C4"},{value:"C5",label:"C5"},{value:"C6",label:"C6"}],XB=["User","Manual","boxli"],Rc=t=>t&&XB.includes(t.source)?t.value:void 0,Op=t=>t?.source==="boxli",zp=t=>{if(t==null||t==="")return{full:null,half:null};const a=parseFloat(String(t));if(!Number.isFinite(a))return{full:null,half:null};const s=Math.floor(a);return{full:s,half:a-s>.01?1:0}},AT=(t,a)=>
2{const s=t==null?"":String(t).trim(),r=a==null?"":String(a).trim();return!s&&!r?null:`${s};${r}`},ON=[{id:"gla",label:"Finished Area Above Grade",icon:e.jsx(fI,{className:"w-3.5 h-3.5"}),getValues:(t,a,s,r,n)=>({mls:t?.squareFeet,pr:a?.squareFeet,ins:Rc(s?.gla),insBoxli:Op(s?.gla),ai:n?.subjectNormalizedGla??(s?.gla?.source==="Derived"?s.gla.value:void 0)}),formatter:t=>{const a=parseInt(String(t).replace(/,/g,""));return isNaN(a)?String(t):`${a.toLocaleString()} sf`}},{id:"beds",label:"Bedrooms",icon:e.jsx(Jj,{className:"w-3.5 h-3.5"}),getValues:(t,a,s)=>({mls:t?.bedrooms,pr:a?.bedrooms,ins:Rc(s?.bedrooms),insBoxli:Op(s?.bedrooms),ai:s?.bedrooms?.source==="Derived"?s.bedrooms.value:void 0})},{id:"bathsFull",label:"Full Bathrooms",icon:e.jsx(H0,{className:"w-3.5 h-3.5"}),getValues:(t,a,s)=>({mls:t?.fullBathrooms??zp(t?.bathrooms).full,pr:a?.fullBathrooms??zp(a?.bathrooms).full,ins:Rc(s?.bathrooms)!=null?zp(Rc(s?.bathrooms)).full:void 0,insBoxli:Op(s?.bathrooms),ai:s?.bathrooms?.source==="Derived"?zp(s.bathrooms.value).full:void 0})},{id:"bathsHalf",label:"Half Bathrooms",icon:e.jsx(H0,{className:"w-3.5 h-3.5"}),getValues:(t,a,s)=>({mls:t?.halfBathrooms??zp(t?.bathrooms).half,pr:a?.halfBathrooms??zp(a?.bathrooms).half,ins:Rc(s?.bathrooms)!=null?zp(Rc(s?.bathrooms)).half:void 0,insBoxli:Op(s?.bathrooms),ai:s?.bathrooms?.source==="Derived"?zp(s.bathrooms.value).half:void 0})},{id:"yearBuilt",label:"Year Built",icon:e.jsx(mc,{className:"w-3.5 h-3.5"}),getValues:(t,a,s)=>({mls:t?.yearBuilt,pr:a?.yearBuilt,ins:Rc(s?.yearBuilt),insBoxli:Op(s?.yearBuilt),ai:s?.yearBuilt?.source==="Derived"?s.yearBuilt.value:void 0})},{id:"lotSize",label:"Lot Size",icon:e.jsx(Um,{className:"w-3.5 h-3.5"}),getValues:(t,a,s)=>({mls:t?.lotSize||t?.lotSizeSquareFeet,pr:a?.lotSize||a?.lotSizeSquareFeet,ins:Rc(s?.lotSize),insBoxli:Op(s?.lotSize)}),formatter:t=>{const a=parseInt(String(t).replace(/[^0-9]/g,""));return a>0?`${a.toLocaleString()} sf`:String(t)}},{id:"garageCarport",label:"Vehicle Storage",icon:e.jsx(FO,{className:"w-3.5 h-3.5"}),getValues:(t,a,s)=>({mls:t?.garageSpaces?`${t.garageSpaces} ${EE(t?.garageType,t?.carStorageType,t?.parkingFeatures,t?.parking)||"Garage"}`:null,pr:a?.garageSpaces?`${a.garageSpaces} ${EE(a?.garageType,a?.carStorageType,a?.parkingFeatures,a?.parking)||"Garage"}`:null,ins:Rc(s?.garageCars)?`${Rc(s?.garageCars)} Garage`:void 0,insBoxli:Op(s?.garageCars)}),alwaysShow:!0},{id:"basement",label:"Finished / Unfinished Area Below Grade",icon:e.jsx(lp,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.basementSqft||t?.basementSquareFeet||t?.basement,pr:a?.basementSqft||a?.basementSquareFeet||a?.basement})},{id:"basementAccess",label:"Basement Access",icon:e.jsx(_O,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.basementAccess||t?.belowGradeAccess,pr:a?.basementAccess||a?.belowGradeAccess})},{id:"qualityCondition",label:"Overall Quality / Condition",icon:e.jsx(ul,{className:"w-3.5 h-3.5"}),getValues:(t,a,s)=>({ai:["AI","Derived"].includes(s?.quality?.source??"")||["AI","Derived"].includes(s?.condition?.source??"")?[["AI","Derived"].includes(s?.quality?.source??"")?
2s.quality?.value:"",["AI","Derived"].includes(s?.condition?.source??"")?s.condition?.value:""].filter(Boolean).join(" / "):void 0,ins:Rc(s?.quality)||Rc(s?.condition)?[Rc(s?.quality)??"",Rc(s?.condition)??""].filter(Boolean).join(" / "):void 0,insBoxli:Op(s?.quality)||Op(s?.condition)}),alwaysShow:!0},{id:"interiorQualityCondition",label:"Interior Quality / Condition",icon:e.jsx(ul,{className:"w-3.5 h-3.5"}),getValues:()=>({}),alwaysShow:!0},{id:"exteriorQualityCondition",label:"Exterior Quality / Condition",icon:e.jsx(ul,{className:"w-3.5 h-3.5"}),getValues:()=>({}),alwaysShow:!0},{id:"location",label:"Site Influence (Location)",icon:e.jsx(zR,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.siteInfluence||t?.locationInfluence,pr:a?.siteInfluence||a?.locationInfluence}),alwaysShow:!0},{id:"attachedDetached",label:"Attached / Detached",icon:e.jsx(Fo,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.attachmentType||t?.attachedDetached,pr:a?.attachmentType||a?.attachedDetached}),alwaysShow:!0},{id:"constructionMethod",label:"Construction Method",icon:e.jsx(lp,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.constructionMethod||t?.constructionType,pr:a?.constructionMethod||a?.constructionType}),alwaysShow:!0},{id:"design",label:"Design/Style",icon:e.jsx(Fo,{className:"w-3.5 h-3.5"}),getValues:(t,a,s)=>({mls:t?.style||null,pr:a?.style||null,ins:Rc(s?.designStyle),insBoxli:Op(s?.designStyle)})},{id:"view",label:"View",icon:e.jsx(zR,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.view||t?.viewType,pr:a?.view||a?.viewType}),alwaysShow:!0},{id:"heatingCooling",label:"Heating/Cooling",icon:e.jsx(b5,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.heatingCooling||AT(t?.heatingType||t?.heating,t?.cooling||t?.coolingType||t?.airConditioning),pr:a?.heatingCooling||AT(a?.heatingType||a?.heating,a?.cooling||a?.coolingType||a?.airConditioning)}),alwaysShow:!0},{id:"functionalUtility",label:"Functional Issues",icon:e.jsx(lp,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.functionalUtility,pr:a?.functionalUtility}),alwaysShow:!0},{id:"porchPatioDeck",label:"Outdoor Living",icon:e.jsx(Fo,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.porchPatioDeck||t?.patioAndPorchFeatures,pr:a?.porchPatioDeck||a?.patioAndPorchFeatures}),alwaysShow:!0},{id:"energyEfficient",label:"Energy Efficient & Green",icon:e.jsx(ul,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.energyEfficient||t?.greenEnergyEfficient||t?.greenFeatures||(t?.solarPanelYN===!0||/^y/i.test(String(t?.solarPanelYN??""))?"Solar panels":null)||(t?.hersIndex!=null&&t?.hersIndex!==""?`HERS ${t.hersIndex}`:null),pr:a?.energyEfficient||a?.greenEnergyEfficient||a?.greenFeatures}),alwaysShow:!0},{id:"pool",label:"Water Features",icon:e.jsx(y5,{className:"w-3.5 h-3.5"}),getValues:(t,a)=>({mls:t?.pool!=null?String(t.pool):t?.poolYN||t?.poolFeatures||null,pr:a?.pool!=null?String(a.pool):a?.poolYN||null}),alwaysShow:!0}];ON.map(t=>t.id);const zA={location:{section:"site",field:"SiteInfluenceType"},view:{section:"site",field:"ViewType"},lotSize:{section:"site",field:"LotSizeAreaMeasure"}},iw=(()=>{const t=new Map;for(const s of T2){if(!s.home)continue;const r=`${s.home.section}.${s.home.field}`;let n=t.get(s.name);n||t.set(s.name,n=new Map),n.set(r,{section:s.home.section,field:s.home.field})}const a=new Map;return t.forEach((s,r)=>{s.size===1&&a.set(r,s.values().next().value)}),a})(),e4={design:"designOtherDescription"};function t4(t){if(t.source!=="catalog"||!t.rowId)return null;const a=Pr(t.rowId);if(a&&a.length>0)return a;const s=mb.find(r=>r.rowId===t.rowId);if(s?.uad36Element){const r=Pr(s.uad36Element);if(r&&r.length>0)return r}return null}function a4(t){if(t.source!=="catalog"||!t.rowId)return null;const a=iw.get(t.rowId);if(a)return a;const s=mb.find(r=>r.rowId===t.rowId);if(s?.uad36Element){const r=iw.get(s.uad36Element);if(r)return r}return null}const s4={location:"location",view:"view",functionalUtility:"functionalUtility",heatingCooling:"heatingType",energyEfficient:"efficiencyRatingExists",qualityCondition:"quality",interiorQualityCondition:"interiorQuality",exteriorQualityCondition:"exteriorQuality"};function r4(t){return s4[t]??t}const n4={location:"location",lotSize:"site",view:"view",yearBuilt:"yearBuilt",attachedDetached:"attachedDetached",constructionMethod:"constructionMethod",design:"design",functionalUtility:"functionalUtility",heatingCooling:"heatingCooling",beds:"aboveGrade",bathsFull:"aboveGrade",bathsHalf:"aboveGrade",gla:"gla",basement:"basement",basementAccess:"basement",qualityCondition:"qualityCondition",interiorQualityCondition:"interiorQuality",exteriorQualityCondition:"exteriorQuality",energyEfficient:"energyEfficient",garageCarport:"garageCarport"};function ow(t){if(t==="ViewType")return"view";if(t==="ViewTypeOtherDescription")return"viewOtherDescription";if(t===uT)return Av;let a=t.match(/^ViewRangeTypeOtherDescription(\d*)$/);return a?`viewRangeOtherDescription${a[1]}`:(a=t.match(/^ViewRangeType(\d*)$/),a?`viewRange${a[1]}`:(a=t.match(/^ViewValueMarketabilityImpactType(\d*)$/),a?`viewImpact${a[1]}`:t))}const i4={pool:"amenities",attachedDetached:"dwelling",porchPatioDeck:"amenities"},o4={attachedDetached:-1},XD=(()=>{const t=new Map;
2return ON.forEach((a,s)=>{const r=n4[a.id],n=i4[a.id]??(r?D3(r):void 0);if(!n)return;const i=hd.find(p=>p.id===n),l=r&&i?i.fields.indexOf(r):-1,c=o4[a.id]??(l<0?Number.MAX_SAFE_INTEGER:l),d=t.get(n)??[];d.push({id:a.id,order:c,decl:s}),t.set(n,d)}),hd.filter(a=>a.id!=="general").map(a=>({id:a.id,title:a.title,optional:!!a.optional,ids:(t.get(a.id)??[]).sort((s,r)=>s.order-r.order||s.decl-r.decl).map(s=>s.id)}))})(),lw="Other",l4=XD,c4=Object.fromEntries(ON.map(t=>[t.id,t.label])),d4={water:"No water frontage details yet — add the body of water, frontage length, or access details.",energy:"No energy or green-feature details yet — record certifications, ratings, or renewable components.",amenities:"No amenity details yet — add pools, outdoor living, or other amenity categories.",outbuilding:"No outbuildings declared yet — add one if the property has a barn, shed, or workshop."};function u4(t){if(!(t.source!=="catalog"||!t.rowId))return Dh(t.rowId,og(t.rowId))}const ek=[{key:"mls",label:"MLS Listing",shortLabel:"MLS",sub:"Listing",color:"text-blue-700",bg:"bg-blue-50",activeBg:"bg-blue-100 ring-2 ring-blue-400",border:"border-blue-200"},{key:"pr",label:"Public Record",shortLabel:"PR",sub:"Public Rec.",color:"text-emerald-700",bg:"bg-emerald-50",activeBg:"bg-emerald-100 ring-2 ring-emerald-400",border:"border-emerald-200"},{key:"ai",label:"AI Analysis",shortLabel:"AI",sub:"Analysis",color:"text-purple-700",bg:"bg-purple-50",activeBg:"bg-purple-100 ring-2 ring-purple-400",border:"border-purple-200"},{key:"ins",label:"Inspection",shortLabel:"Manual",sub:"Inspection",color:"text-orange-700",bg:"bg-orange-50",activeBg:"bg-orange-100 ring-2 ring-orange-400",border:"border-orange-200"},{key:"csv",label:"CSV Import",shortLabel:"CSV",sub:"Imported",color:"text-cyan-700",bg:"bg-cyan-50",activeBg:"bg-cyan-100 ring-2 ring-cyan-400",border:"border-cyan-200"}];function p4({sourceKey:t}){const a=ek.find(s=>s.key===t);return e.jsx("span",{className:"text-[8px] px-1 py-0.5 bg-slate-100 text-slate-500 font-bold tracking-wider uppercase rounded border border-slate-200",children:a?.shortLabel??(t==="manual"?"User":String(t).toUpperCase())})}function m4({value:t,formatter:a,isActive:s,isConflict:r,sourceKey:n,onClick:i,hasValue:l,mappedFrom:c,aiSuggested:d}){if(!l)return e.jsx("div",{className:"px-1 py-[5px] flex items-center justify-center border-l border-slate-200/40",children:e.jsx("span",{className:"text-[12px] text-slate-300",children:"–"})});const p=a?a(t):String(t),u=p.length>16?p.slice(0,14)+"…":p,m=c==="mls"?"MLS":c==="pr"?"PR":null;return e.jsx("div",{className:Q("px-1 py-[5px] flex items-center justify-center border-l border-slate-200/40",s&&"bg-[#293757]/10"),children:e.jsx(gr,{delayDuration:200,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("button",{onClick:i,className:Q("max-w-full inline-flex items-center justify-center gap-0.5 px-1 py-0.5 rounded text-[11px] text-center transition-colors cursor-pointer truncate tabular-nums",s?"font-semibold text-[#293757]":r?"font-semibold text-amber-700 hover:bg-white/70":"text-slate-900 hover:bg-white/70"),"data-testid":`cell-${n}-active`,children:[s&&e.jsx(Bs,{className:"w-3 h-3 shrink-0 text-[#293757]"}),e.jsx("span",{className:"truncate",children:u}),d?e.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 text-[7px] font-bold uppercase tracking-tight text-fuchsia-600 leading-none","data-testid":`cell-${n}-aimapped`,children:[e.jsx(ul,{className:"w-2 h-2"}),"AI"]}):m&&e.jsxs("span",{className:"shrink-0 text-[7px] font-bold uppercase tracking-tight text-purple-500 leading-none","data-testid":`cell-${n}-mapped`,children:["↦",m]})]})}),(p.length>16||m)&&e.jsx(Wa,{side:"top",className:"text-xs max-w-[250px]",children:d?`AI-standardized from ${c==="mls"?"the MLS listing":"Public Records"}: ${p}`:m?`Standardized from ${c==="mls"?"the MLS listing":"Public Records"}: ${p}`:p})]})})})}function h4({confidence:t}){if(t==null)return e.jsx("span",{className:"inline-block ml-1 px-1 py-0.5 rounded text-[8px] font-bold bg-red-100 text-red-600",children:"N/A"});const a=t>=80?"bg-green-100 text-green-700":t>=60?"bg-slate-100 text-slate-600":"bg-red-100 text-red-600";return e.jsxs("span",{className:Q("inline-block ml-1 px-1 py-0.5 rounded text-[8px] font-bold",a),children:[t,"%"]})}function f4({value:t,confidence:a,normNote:s,formatter:r,isActive:n,onClick:i}){if(t==null||t===0||t==="")return e.jsx("div",{className:"px-1 py-[5px] flex items-center justify-center border-l border-slate-200/40",children:e.jsx(gr,{delayDuration:200,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("button",{onClick:i,className:Q("inline-flex items-center gap-0.5 px-1 py-0.5 rounded text-[11px] text-center transition-colors cursor-pointer",n?"bg-red-100 text-red-700 font-semibold":"text-red-500 hover:bg-red-50"),"data-testid":"cell-ai-gla-na",children:["N/A",e.jsx("span",{className:"px-1 py-0.5 rounded text-[8px] font-bold bg-red-100 text-red-600",children:"!"})]})}),e.jsx(Wa,{side:"top",className:"text-xs max-w-[280px]",children:s||"GLA unavailable from both MLS and Public Records — manual entry required"})]})})});const c=r?r(t):String(t);return e.jsx("div",{className:Q("px-1 py-[5px] flex items-center justify-center border-l border-slate-200/40",n&&"bg-[#293757]/10"),children:e.jsx(gr,{delayDuration:200,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("button",{onClick:i,className:Q("inline-flex items-center gap-0.5 px-1 py-0.5 rounded text-[11px] text-center transition-colors cursor-pointer tabular-nums",n?"font-semibold text-[#293757]":"text-slate-700 hover:bg-white/70"),"data-testid":"cell-ai-gla",children:[n&&e.jsx(Bs,{className:"w-3 h-3 shrink-0 text-[#293757]"}),e.jsx("span",{className:"truncate",children:c}),e.jsx(h4,{confidence:a})]})}),e.jsx(Wa,{side:"top",className:"text-xs max-w-[280px]",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"font-semibold",children:["AI Normalized GLA: ",c]}),s&&e.jsx("p",{className:"text-slate-400",children:s}),a!=null&&e.jsxs("p",{className:"text-slate-400",children:["Confidence: ",a,"%"]})]})})]})})})}const g4=(()=>{const t=Pr("FunctionalIssueType");return t&&t.length>0?t:["CeilingHeight","FloorPlan","NonConformity","None","Other","Overimprovement","Underimprovement"]})(),tk="|";function cw(t){return t==null||t===""?[]:String(t).split(tk).map(a=>
2a.trim()).filter(Boolean)}function x4(t){return t.join(tk)}function b4({options:t,tokens:a,otherDescription:s,onTokensChange:r,onOtherChange:n}){const i=c=>{if(c==="None"){r(a.includes("None")?[]:["None"]);return}const d=a.filter(p=>p!=="None");r(d.includes(c)?d.filter(p=>p!==c):[...d,c])},l=a.length?a.join(", "):null;return e.jsxs("div",{className:"w-full space-y-1",children:[e.jsxs(Qh,{children:[e.jsx(Zh,{asChild:!0,children:e.jsxs("button",{className:Q("w-full inline-flex items-center justify-between gap-1 px-2 py-1 rounded border text-[11px] transition-colors",l?"border-slate-300 bg-white text-slate-900 hover:bg-slate-50":"border-amber-300 bg-amber-50 text-amber-700 hover:bg-amber-100"),"data-testid":"functional-issues-trigger",children:[e.jsx("span",{className:"truncate text-left",children:l??"Select issues…"}),e.jsx(Rr,{className:"w-3 h-3 shrink-0 opacity-60"})]})}),e.jsx(Jh,{align:"start",className:"min-w-[180px]",children:t.map(c=>{const d=a.includes(c);return e.jsxs(Yl,{onSelect:p=>{p.preventDefault(),i(c)},className:"text-[12px] gap-2","data-testid":`functional-issue-${c}`,children:[e.jsx(Bs,{className:Q("w-3.5 h-3.5",d?"opacity-100 text-[#293757]":"opacity-0")}),c]},c)})})]}),a.includes("Other")&&e.jsx(ze,{value:s,onChange:c=>n(c.target.value),placeholder:"Describe other issue",className:"h-7 text-[11px]","data-testid":"functional-issue-other-desc"})]})}function tv({enumField:t,options:a,tokens:s,onChange:r,testidBase:n,placeholder:i,optional:l}){const c=p=>{if(p==="None"){r(s.includes("None")?[]:["None"]);return}const u=s.filter(m=>m!=="None");r(u.includes(p)?u.filter(m=>m!==p):[...u,p])},d=s.length?s.map(p=>Dc(t,p)).join(", "):null;return e.jsxs(Qh,{children:[e.jsx(Zh,{asChild:!0,children:e.jsxs("button",{className:Q("w-full inline-flex items-center justify-between gap-1 px-2 py-1 rounded border text-[11px] transition-colors",d||l?"border-slate-300 bg-white text-slate-900 hover:bg-slate-50":"border-amber-300 bg-amber-50 text-amber-700 hover:bg-amber-100"),"data-testid":`${n}-trigger`,children:[e.jsx("span",{className:"truncate text-left",children:d??i}),e.jsx(Rr,{className:"w-3 h-3 shrink-0 opacity-60"})]})}),e.jsx(Jh,{align:"start",className:"min-w-[180px]",children:a.map(p=>{const u=s.includes(p);return e.jsxs(Yl,{onSelect:m=>{m.preventDefault(),c(p)},className:"text-[12px] gap-2","data-testid":`${n}-opt-${p}`,children:[e.jsx(Bs,{className:Q("w-3.5 h-3.5",u?"opacity-100 text-[#293757]":"opacity-0")}),Dc(t,p)]},p)})})]})}function k0({label:t,enumField:a,value:s,onChange:r,testid:n,options:i}){const l=i??Pr(a)??[],c="__clear__";return e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"block text-[10px] font-medium text-slate-500",children:t}),e.jsxs(sr,{value:s===""?void 0:s,onValueChange:d=>r(d===c?"":d),children:[e.jsx(rr,{className:"h-7 w-full text-xs","data-testid":n,children:e.jsx(or,{placeholder:"Select…"})}),e.jsxs(nr,{children:[e.jsx(vs,{value:c,children:e.jsx("span",{className:"text-muted-foreground",children:"— Clear —"})}),l.map(d=>e.jsx(vs,{value:d,className:"text-xs",children:Dc(a,d)},d))]})]})]})}function y4({get:t,set:a}){const s=t("BodyOfWaterType"),r=t("PrivateAccessIndicator"),n=t("WaterfrontFeatureType").split("|").map(l=>l.trim()).filter(Boolean),i=(l,c,d)=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-slate-500",children:c}),e.jsx("div",{className:"inline-flex rounded border border-slate-300 overflow-hidden",children:["true","false"].map(p=>e.jsx("button",{onClick:()=>a(l,t(l)===p?"":p),className:Q("px-2 py-0.5 text-[10px] font-semibold",p==="false"&&"border-l border-slate-300",t(l)===p?"bg-[#293757] text-white":"bg-white text-slate-500 hover:bg-slate-50"),"data-testid":`${d}-${p==="true"?"yes":"no"}`,children:p==="true"?"Yes":"No"},p))})]});return e.jsxs("div",{className:"mt-1 space-y-1.5 rounded border border-slate-200 p-1.5","data-testid":"water-frontage-fields",children:[e.jsx("span",{className:"block text-[10px] font-semibold text-slate-600",children:"Water Frontage"}),e.jsx(k0,{label:"Body of Water Type",enumField:"BodyOfWaterType",value:s,onChange:l=>{a("BodyOfWaterType",l),l!=="Other"&&a("BodyOfWaterTypeOtherDescription","")},testid:"water-body-type"}),s==="Other"&&e.jsx(ze,{value:t("BodyOfWaterTypeOtherDescription"),onChange:l=>a("BodyOfWaterTypeOtherDescription",l.target.value),placeholder:"Describe body of water",className:"h-7 text-[11px]","data-testid":"water-body-type-other"}),i("PrivateAccessIndicator","Private Access","water-private-access"),r==="true"&&e.jsxs(e.Fragment,{children:[e.jsx(ze,{value:t("BodyOfWaterName"),onChange:l=>a("BodyOfWaterName",l.target.value),placeholder:"Body of water name",className:"h-7 text-[11px]","data-testid":"water-body-name"}),e.jsx(k0,{label:"Water Access Depth",enumField:"WaterAccessDepthType",value:t("WaterAccessDepthType"),onChange:l=>{a("WaterAccessDepthType",l),l!=="Other"&&a("WaterAccessDepthTypeOtherDescription","")},testid:"water-depth-type"}),t("WaterAccessDepthType")==="Other"&&e.jsx(ze,{value:t("WaterAccessDepthTypeOtherDescription"),onChange:l=>a("WaterAccessDepthTypeOtherDescription",l.target.value),placeholder:"Describe access depth",className:"h-7 text-[11px]","data-testid":"water-depth-type-other"}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"block text-[10px] font-medium text-slate-500",children:"Water Frontage (linear ft)"}),e.jsx(ze,{type:"number",value:t("WaterFrontageTotalLengthLinearMeasure"),onChange:l=>a("WaterFrontageTotalLengthLinearMeasure",l.target.value),placeholder:"e.g. 120",className:"h-7 text-[11px]","data-testid":"water-frontage-length"})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"block text-[10px] font-medium text-slate-500",children:"Waterfront Features"}),e.jsx(tv,{enumField:"WaterfrontFeatureType",options:Pr("WaterfrontFeatureType")??[],tokens:n,onChange:l=>{a("WaterfrontFeatureType",l.join("|")),l.includes("Other")||a("WaterfrontFeatureTypeOtherDescription",""),l.length===1&&l[0]==="None"||a("WaterfrontDevelopmentRightsIndicator","")},testidBase:"waterfront-features",placeholder:"Select features…",optional:!0})]}),n.includes("Other")&&e.jsx(ze,{value:t("WaterfrontFeatureTypeOtherDescription"),onChange:l=>a("WaterfrontFeatureTypeOtherDescription",l.target.value),placeholder:"Describe waterfront feature",className:"h-7 text-[11px]","data-testid":"waterfront-feature-other"}),n.length===1&&n[0]==="None"&&i("WaterfrontDevelopmentRightsIndicator","Development Rights","water-dev-rights")]})]})}function S4({get:t,set:a}){const s=(r,n)=>{a("heatingCooling",r||n?`${r};${n}`:"")};return e.jsxs("div",{className:"w-full space-y-1.5","data-testid":"heating-cooling-cell",children:[e.jsx(k0,{label:"Heating System",enumField:"HeatingSystemType",value:t("heatingType"),onChange:r=>{a("heatingType",r),r!=="Other"&&a("heatingOtherDescription",""),s(r,t("cooling"))},testid:"heatcool-heating-type"}),t("heatingType")==="Other"&&e.jsx(ze,{value:t("heatingOtherDescription"),onChange:r=>a("heatingOtherDescription",r.target.value),placeholder:"Describe heating system",className:"h-7 text-[11px]","data-testid":"heatcool-heating-type-other"}),e.jsx(k0,{label:"Heating Fuel",enumField:"HeatingFuelType",value:t("heatingFuel"),onChange:r=>{a("heatingFuel",r),r!=="Other"&&a("heatingFuelOtherDescription","")},testid:"heatcool-heating-fuel"}),t("heatingFuel")==="Other"&&e.jsx(ze,{value:t("heatingFuelOtherDescription"),onChange:r=>a("heatingFuelOtherDescription",r.target.value),placeholder:"Describe heating fuel",className:"h-7 text-[11px]","data-testid":"heatcool-heating-fuel-other"}),e.jsx(k0,{label:"Cooling System",enumField:"CoolingSystemType",value:t("cooling"),onChange:r=>{a("cooling",r),r!=="Other"&&a("coolingOtherDescription",""),s(t("heatingType"),r)},testid:"heatcool-cooling-type"}),t("cooling")==="Other"&&e.jsx(ze,{value:t("coolingOtherDescription"),onChange:r=>a("coolingOtherDescription",r.target.value),placeholder:"Describe cooling system",className:"h-7 text-[11px]","data-testid":"heatcool-cooling-type-other"})]})}const v4=(()=>{const t=Pr("RenewableEnergyComponentType");return t&&t.length>0?t:["Geothermal","Other","Solar","WindTurbine"]})();function qA({label:t,isYes:a,onYes:s,onNo:r,testidBase:n,children:i}){return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium text-slate-700",children:t}),e.jsxs("div",{className:"inline-flex rounded border border-slate-300 overflow-hidden",children:[e.jsx("button",{onClick:s,className:Q("px-2 py-0.5 text-[10px] font-semibold",a?"bg-[#293757] text-white":"bg-white text-slate-500 hover:bg-slate-50"),"data-testid":`${n}-yes`,children:"Yes"}),e.jsx("button",{onClick:r,className:Q("px-2 py-0.5 text-[10px] font-semibold border-l border-slate-300",a?"bg-white text-slate-500 hover:bg-slate-50":"bg-slate-600 text-white"),"data-testid":`${n}-no`,children:"No"})]})]}),a?e.jsx("div",{className:"space-y-1 pl-1",children:i}):e.jsx("span",{className:"block text-[10px] text-slate-400 pl-1",children:"None"})]})}function N4({get:t,set:a}){return e.jsxs("div",{className:"w-full space-y-2","data-testid":"energy-features-cell",children:[e.jsxs(qA,{label:"Efficiency Rating",isYes:t("efficiencyRatingExists")==="Yes",onYes:()=>a("efficiencyRatingExists","Yes"),onNo:()=>a("efficiencyRatingExists","No"),testidBase:"energy-efficiency",children:[e.jsx(ze,{value:t("eff
2iciencyRatingName"),onChange:s=>a("efficiencyRatingName",s.target.value),placeholder:"Rating name",className:"h-7 text-[11px]","data-testid":"energy-efficiency-name"}),e.jsx(ze,{value:t("efficiencyRatingScore"),onChange:s=>a("efficiencyRatingScore",s.target.value),placeholder:"Score",className:"h-7 text-[11px]","data-testid":"energy-efficiency-score"})]}),e.jsxs(qA,{label:"Green Certification",isYes:t("greenCertificationExists")==="Yes",onYes:()=>a("greenCertificationExists","Yes"),onNo:()=>a("greenCertificationExists","No"),testidBase:"energy-green",children:[e.jsx(ze,{value:t("greenCertificationName"),onChange:s=>a("greenCertificationName",s.target.value),placeholder:"Certification name",className:"h-7 text-[11px]","data-testid":"energy-green-name"}),e.jsx(ze,{value:t("greenCertificationLevel"),onChange:s=>a("greenCertificationLevel",s.target.value),placeholder:"Level",className:"h-7 text-[11px]","data-testid":"energy-green-level"})]}),e.jsx(qA,{label:"Renewable Energy",isYes:t("renewableEnergyExists")==="Yes",onYes:()=>a("renewableEnergyExists","Yes"),onNo:()=>a("renewableEnergyExists","No"),testidBase:"energy-renewable",children:e.jsxs(sr,{value:t("renewableEnergyType")||void 0,onValueChange:s=>a("renewableEnergyType",s),children:[e.jsx(rr,{className:"h-7 text-[11px]","data-testid":"energy-renewable-type",children:e.jsx(or,{placeholder:"Component type"})}),e.jsx(nr,{children:v4.map(s=>e.jsx(vs,{value:s,className:"text-[12px]",children:s},s))})]})})]})}function dw({qualityKey:t,conditionKey:a,get:s,set:r,testidBase:n}){return e.jsxs("div",{className:"w-full grid grid-cols-2 gap-1","data-testid":`${n}-cell`,children:[e.jsxs(sr,{value:s(t)||void 0,onValueChange:i=>r(t,i),children:[e.jsx(rr,{className:"h-7 text-[11px]","data-testid":`${n}-quality`,children:e.jsx(or,{placeholder:"Q…"})}),e.jsx(nr,{children:ZB.map(i=>e.jsx(vs,{value:i.value,className:"text-xs",children:i.label},i.value))})]}),e.jsxs(sr,{value:s(a)||void 0,onValueChange:i=>r(a,i),children:[e.jsx(rr,{className:"h-7 text-[11px]","data-testid":`${n}-condition`,children:e.jsx(or,{placeholder:"C…"})}),e.jsx(nr,{children:JB.map(i=>e.jsx(vs,{value:i.value,className:"text-xs",children:i.label},i.value))})]})]})}function A4({get:t,set:a}){const s=t("basementFinishedSqft"),r=t("basementUnfinishedSqft"),n=parseInt(s,10)||0,i=parseInt(r,10)||0,l=n+i;return e.jsxs("div",{className:"w-full space-y-1","data-testid":"basement-area-cell",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-1",children:[e.jsx(ze,{value:s,onChange:c=>a("basementFinishedSqft",c.target.value.replace(/[^0-9]/g,"")),placeholder:"Finished sf",className:"h-7 text-[11px]","data-testid":"basement-finished-input"}),e.jsx(ze,{value:r,onChange:c=>a("basementUnfinishedSqft",c.target.value.replace(/[^0-9]/g,"")),placeholder:"Unfinished sf",className:"h-7 text-[11px]","data-testid":"basement-unfinished-input"})]}),e.jsx("span",{className:"block text-[10px] text-slate-500","data-testid":"basement-area-summary",children:l>0?`${l.toLocaleString()}/${n.toLocaleString()} sf`:"No below-grade area"})]})}function uw({activeFields:t,listingDetails:a,propDetails:s,propertyData:r,subjectEls:n,subjectElsLoading:i,subjectQCLoading:l,fieldSelections:c,onFieldSourceChange:d,baselineSource:p,showConflictsOnly:u=!1,filterMode:m,collapsibleSubRows:h=!1,prefilledManualValues:f,manualColumnLabel:v,subjectNormalizedGla:S,subjectGlaConfidence:N,subjectGlaNormNote:x,onConflictCountChange:y,csvSubjectValues:b,addedRows:j=[],onAddedRowsChange:T,addedRowsHydrated:O=!1,inspectionImport:E,orderId:R,enableUad36:G=!1,homeownerResponsibleExterior:U}){const{inspecting:C}
2=fc(),[F,A]=o.useState(null),[M,B]=o.useState(""),oe=o.useRef(null),ae=m??(u?"needsReview":"all"),D=ae!=="all",[_,$]=o.useState(!1),[z,V]=o.useState({}),[le,W]=o.useState(null),me=o.useRef(null),[Z,pe]=o.useState({}),se=o.useRef(new Set),[fe,ue]=o.useState(!1),[be,H]=o.useState("catalog"),[ye,de]=o.useState(""),[ge,Be]=o.useState(null),[He,Ie]=o.useState(""),[ce,Pe]=o.useState(null),[We,Re]=o.useState({}),ne=o.useMemo(()=>_D(a,s,E),[a,s,E]),Me=o.useRef(!1),[lt,Tt]=o.useState(!1),je=o.useRef(0),Le=o.useRef([]),ut=o.useRef({});o.useEffect(()=>{if(!R){Me.current=!0,Tt(!0);return}Me.current=!1,Tt(!1);const $e=++je.current;let Ot=!1;return(async()=>{try{const _e=await fetch(`/api/orders/${R}/sales-grid-ui-state`);if(!_e.ok)throw new Error(`HTTP ${_e.status}`);const ma=await _e.json();if(Ot||je.current!==$e)return;const pt=ma?.optionalBandsOpen,re={};if(pt&&typeof pt=="object")for(const Ze of hd)Ze.optional&&typeof pt[Ze.id]=="boolean"&&(re[Ze.id]=pt[Ze.id]);ut.current={...re};const qe=Array.isArray(ma?.optionalBandOrder)?ma.optionalBandOrder:[];Le.current=qe.filter(Ze=>typeof Ze=="string"),Re(Ze=>Object.keys(re).length===0&&Object.keys(Ze).length===0?Ze:{...re,...Ze})}catch(_e){console.warn("[SubjectDataGrid] Failed to load optional-section state:",_e)}finally{!Ot&&je.current===$e&&(Me.current=!0,Tt(!0))}})(),()=>{Ot=!0}},[R]),o.useEffect(()=>{if(!R||!lt)return;let $e=!0;const Ot=qD(R,"SubjectDataGrid",async()=>{if($e)try{const _e=await fetch(`/api/orders/${R}/sales-grid-ui-state`);if(!_e.ok||!$e)return;const ma=await _e.json(),pt=ma?.optionalBandsOpen,re={};if(pt&&typeof pt=="object")for(const Ze of hd)Ze.optional&&typeof pt[Ze.id]=="boolean"&&(re[Ze.id]=pt[Ze.id]);const qe=Array.isArray(ma?.optionalBandOrder)?ma.optionalBandOrder:[];if(Le.current=qe.filter(Ze=>typeof Ze=="string"),!$e)return;Re(Ze=>{const It=ut.current,Ne={},Ue=new Set([...Object.keys(It),...Object.keys(re)]);for(const xt of Ue)It[xt]!==re[xt]&&re[xt]!==void 0&&(Ne[xt]=re[xt]);if(ut.current={...re},Object.keys(Ne).length===0)return Ze;const ct={...Ze,...Ne};return YD(Ze,ct)?Ze:ct})}catch{}});return()=>{$e=!1,Ot()}},[R,lt]),Fx({enabled:!!R,scopeId:R,isHydrated:()=>Me.current,label:"[SubjectDataGrid] optional-section state",persist:()=>fetch(`/api/orders/${R}/sales-grid-ui-state`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({optionalBandsOpen:We,optionalBandOrder:Le.current}),keepalive:!0}).then($e=>($e.ok&&R&&zD(R,"SubjectDataGrid"),$e)),deps:[R,We]});const st=o.useMemo(()=>ON.filter($e=>t.has($e.id)),[t]),Xt=o.useMemo(()=>({subjectNormalizedGla:S,subjectGlaConfidence:N,subjectGlaNormNote:x}),[S,N,x]),ua=o.useMemo(()=>{const $e=[a?.foundation,s?.foundation,a?.foundationType,s?.foundationType,a?.basementType,s?.basementType,a?.basement,s?.basement];for(const ma of $e){if(ma==null||ma==="")continue;if(Em("basementType",String(ma))?.value==="Basement")return!0}const Ot=Number(a?.basementSqFt??a?.basementArea??s?.basementSqFt??s?.basementArea??r?.basementArea?.value??0);if(Number.isFinite(Ot)&&Ot>0)return!0;const _e=$e.filter(Boolean).join(" ").toLowerCase();return!!/\b(basement|cellar|below[\s-]?grade|walk[\s-]?out|walk[\s-]?up|daylight)\b/.test(_e)},[a,s,r]),Oa=o.useMemo(()=>{if([a?.basementAccess,a?.belowGradeAccess,s?.basementAccess,s?.belowGradeAccess].some(_e=>_e!=null&&_e!==""))return!0;const Ot=[a?.foundation,s?.foundation,a?.foundationType,s?.foundationType,a?.basementType,s?.basementType,a?.basement,s?.basement].filter(
2Boolean).join(" ").toLowerCase();return/\b(walk[\s-]?out|walk[\s-]?up|cellar|daylight|exterior\s+(?:entry|entrance|access)|outside\s+entrance)\b/.test(Ot)},[a,s]),Xa=o.useMemo(()=>st.map($e=>{const Ot=$e.getValues(a,s,r,n,Xt);b?.[$e.id]!=null&&b[$e.id]!==""&&(Ot.csv=b[$e.id]);const _e=Ot.mls!=null&&Ot.mls!=="",ma=Ot.pr!=null&&Ot.pr!=="";let pt=Ot.ai!=null&&Ot.ai!=="";const re=Ot.ins!=null&&Ot.ins!=="",qe=f?.[$e.id]!=null&&f[$e.id]!=="",Ze=CE($e.id)?ML($e.id):null;let It=null,Ne=!1;if(Ze&&!pt){const Ka=_e?Em($e.id,Ot.mls):null,Ee=!Ka&&ma?Em($e.id,Ot.pr):null,dt=Ka??Ee;if(dt)Ot.ai=dt.value,It=Ka?"mls":"pr",pt=!0;else{const ot=Z[$e.id];ot&&Ze.includes(ot.value)&&(Ot.ai=ot.value,It=ot.from,Ne=!0,pt=!0)}}const Ue=_e||ma||pt||re||qe||$e.alwaysShow,ct=_e?$e.formatter?$e.formatter(Ot.mls):String(Ot.mls):null,xt=ma?$e.formatter?$e.formatter(Ot.pr):String(Ot.pr):null,Na=ct!=null&&xt!=null&&ct!==xt,qt=c[$e.id]?.manualValue;let la;if(qt==null||qt===""){if($e.id==="heatingCooling"){const Ka=c.heatingType?.manualValue??c.heatingFuel?.manualValue,Ee=c.cooling?.manualValue;la=AT(Ka,Ee)??void 0}else if($e.id==="bathsFull")la=zp(c.baths?.manualValue).full??void 0;else if($e.id==="bathsHalf")la=zp(c.baths?.manualValue).half??void 0;else if($e.id==="garageCarport"){const Ka=c.garage?.manualValue,Ee=c.garageType?.manualValue;Ka!=null&&Ka!==""?la=`${Ka} ${Ee!=null&&Ee!==""?Ee:"Garage"}`:Ee!=null&&Ee!==""&&(la=`1 ${Ee}`)}}const fs=la!=null&&la!=="",ps=p==="public-record"?"pr":"mls";let Te=ps;c[$e.id]?.selectedSource?Te=c[$e.id].selectedSource:qe||fs?Te="manual":re?Te="ins":$e.id==="qualityCondition"?Te=re?"ins":"ai":Ze&&pt?Te="ai":ps==="mls"&&!_e&&ma?Te="pr":ps==="pr"&&!ma&&_e&&(Te="mls");const at=qt!=null&&qt!==""?qt:fs?la:f?.[$e.id]??void 0,yt=at!=null&&at!=="",nt=Ot.csv!=null&&Ot.csv!=="",Wt=!_e&&!ma&&!pt&&!re&&!yt&&!nt,ts=Ze?Ze.map(Ka=>({value:Ka,label:Ka})):$e.selectOptions??null,gs=Te==="manual"?at:Ot[Te];let Va="",Mr;if(ts){const Ka=gs==null?"":String(gs);if(Ka&&ts.some(Ee=>Ee.value===Ka))Va=Ka;else if(Ze){const Ee=Em($e.id,gs);Va=Ee&&Ze.includes(Ee.value)?Ee.value:""}Mr=Va===""}else Mr=gs==null||gs==="";$e.id==="qualityCondition"&&l&&Wt&&(Mr=!1);const Sn=!!Ze&&Mr&&RE(gs),ds=(()=>{if(!Mr||Wt||Sn)return null;const Ka=gs??Ot.mls??Ot.pr??Ot.ai??Ot.ins;return Ka!=null&&Ka!==""?String(Ka):null})();let Zt=Ue||yt,Rs=Na,Os=Mr,qs=Sn,Ks=ds,Tn=!1;if($e.id==="basementAccess"){const Ka=at!=null&&at!=="";!ua||!Oa&&!Ka?Tn=!0:Zt=!0}else if($e.id==="functionalUtility"){const Ka=cw(at),Ee=c?.functionalIssueOtherDescription?.manualValue,dt=Ka.includes("Other")&&!(Ee!=null&&String(Ee).trim()!=="");Rs=!1,qs=!1,Ks=null,Os=Ka.length===0||dt}else if($e.id==="energyEfficient")Rs=!1,Os=!1,qs=!0,Ks=null;else if($e.id==="qualityCondition"||$e.id==="interiorQualityCondition"||$e.id==="exteriorQualityCondition"){const[Ka,Ee]=$e.id==="qualityCondition"?["quality","condition"]:$e.id==="interiorQualityCondition"?["interiorQuality","interiorCondition"]:["exteriorQuality","exteriorCondition"],dt=c[Ka]?.manualValue,ot=c[Ee]?.manualValue;Rs=!1,qs=!1,Ks=null,Os=!(dt!=null&&dt!==""&&ot!=null&&ot!==""),$e.id==="exteriorQualityCondition"&&U!==!0&&(Tn=!0),$e.id==="qualityCondition"&&l&&Os&&(Os=!1)}else if($e.id==="basement")Rs=!1,Os=!1,qs=!0,Ks=null;else if($e.id==="garageCarport"){Rs=!1,qs=!1,Ks=null;const Ka=at==null?"":String(at).trim();if(!Ka||Ka==="None")Os=!Ka;else{const Ee=Ka.split(";").map(ot=>ot.trim()).filter(ot=>ot!=="");let dt=!1;Ee.forEach((ot,xa)=>{const rs=ot.match(/^(\d+)\s*(.*)$/),Gs=rs?parseInt(rs[1],10):0,bs=rs?rs[2].trim():"";if(Gs!==0){if(!bs){dt=!0;return}if(bs==="Garage"||bs==="Carport"){const ba=Bp("garageAttachment",xa),ln=c[ba]?.manualValue;(!ln||String(ln).trim()==="")&&(dt=!0)}}}),Os=dt}}else if($e.id==="location"||$e.id==="view"){const Ka=Rm(c[$e.id]?.manualValue),Ee=$e.id==="location"?"SiteInfluenceTypeOtherDescription":"viewOtherDescription",dt=c[Ee]?.manualValue,ot=Ka.includes("Other")&&!(dt!=null&&String(dt).trim()!=="");Rs=!1,qs=!1,Ks=null,Os=Ka.length===0||ot}else if($e.id==="heatingCooling"){Rs=!1,qs=!1,Ks=null;const Ka=c.heatingType?.manualValue,Ee=c.heatingFuel?.manualValue,dt=c.cooling?.manualValue,ot=Ka!=null&&String(Ka).trim()!=="",xa=Ee!=null&&String(Ee).trim()!=="",rs=dt!=null&&String(dt).trim()!=="";Os=!ot||!xa||!rs}else($e.id==="pool"||$e.id==="porchPatioDeck")&&(Rs=!1,Os=!1,qs=!0,Ks=null);return{config:$e,values:Ot,hasMls:_e,hasPr:ma,hasAi:pt,hasIns:re,hasAnyValue:Zt,conditionalHidden:Tn,hasConflict:Rs,lockedEmpty:Os,intentionallyEmpty:qs,lockedSelectValue:Va,unresolvedSourceText:Ks,needsReview:Rs||Os&&!qs,currentSource:Te,manualValue:at,aiMappedFrom:It,aiSuggested:Ne,enumOptions:Ze}}),[st,a,s,r,n,Xt,c,p,f,Z,l,ua,Oa,U,b]);o.useEffect(()=>{st.forEach($e=>{if(!CE($e.id))return;const Ot=$e.getValues(a,s,r,n,Xt);if(b?.[$e.id]!=null&&b[$e.id]!==""&&(Ot.csv=b[$e.id]),Ot.ai!=null&&Ot.ai!=="")return;const ma=Ot.mls!=null&&Ot.mls!=="",pt=Ot.pr!=null&&Ot.pr!=="";if(!ma&&!pt)return;const re=ma?Em($e.id,Ot.mls):null,qe=!re&&pt?Em($e.id,Ot.pr):null;if(re||qe)return;const Ze=ma?"mls":"pr",It=String(ma?Ot.mls:Ot.pr);if(RE(It))return;const Ne=`${$e.id}::${It}`;se.current.has(Ne)||(se.current.add(Ne),fetch("/api/uad36/normalize-enum",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({fieldId:$e.id,raw:It})}).then(Ue=>Ue.ok?Ue.json():null).then(Ue=>{Ue?.success&&typeof Ue.value=="string"&&Ue.value&&pe(ct=>({...ct,[$e.id]:{value:Ue.value,from:Ze}}))}).catch(()=>{}))})},[st,a,s,r,n,Xt,b]);const qa=!!b&&Object.keys(b).length>0,os=o.useMemo(()=>ek.filter($e=>$e.key!=="csv"||qa),[qa]),ya=o.useMemo(()=>{const $e=new Map,Ot=[];for(const _e of j){const ma=u4(_e);if(ma){const pt=$e.get(ma)??[];pt.push(_e),$e.set(ma,pt)}else Ot.push(_e)}return{byBand:$e,flat:Ot}},[j]),At=o.useMemo(()=>{const $e=new Map(Xa.map(Ze=>[Ze.config.id,Ze])),Ot=new Set,_e=new Set,ma=(Ze,It)=>
2Ze==="energy"&&["efficiencyRatingExists","greenCertificationExists","renewableEnergyExists"].some(Ue=>{const ct=c[Ue]?.manualValue;return ct!=null&&ct!==""})?!0:It.some(Ne=>{const Ue=$e.get(Ne);if(!Ue||Ue.conditionalHidden)return!1;const ct=Ue.manualValue!=null&&Ue.manualValue!=="";return Ue.hasMls||Ue.hasPr||Ue.hasAi||Ue.hasIns||ct}),pt=Ze=>ae==="all"?!0:ae==="needsReview"?Ze.needsReview:Ze.lockedEmpty&&!Ze.intentionallyEmpty,re=XD.map(Ze=>{Ze.ids.forEach(xt=>Ot.add(xt));const It=ya.byBand.get(Ze.id)??[];let Ne=!0;if(Ze.optional){const xt=We[Ze.id];Ne=xt!==void 0?xt:lt&&(It.length>0||ma(Ze.id,Ze.ids)||!!ne[Ze.id])}const Ue=Ze.ids.map(xt=>$e.get(xt)).filter(xt=>!!xt),ct=Ne?Ue.filter(xt=>!xt.conditionalHidden&&xt.hasAnyValue&&pt(xt)):[];if(Ne)for(const xt of Ue)!xt.conditionalHidden&&xt.hasAnyValue&&_e.add(xt.config.id);return{...Ze,open:Ne,rows:ct,addedRows:Ne&&!D?It:[]}}),qe=Xa.filter(Ze=>!Ot.has(Ze.config.id)&&!Ze.conditionalHidden&&Ze.hasAnyValue&&pt(Ze));for(const Ze of Xa)!Ot.has(Ze.config.id)&&!Ze.conditionalHidden&&Ze.hasAnyValue&&_e.add(Ze.config.id);return{sections:re,leftover:qe,visibleIds:_e}},[Xa,ae,D,We,lt,ya,c,ne]),{sections:Fe,leftover:Oe,visibleIds:rt}=At,$t=o.useMemo(()=>Xa.filter($e=>rt.has($e.config.id)&&$e.needsReview).length,[Xa,rt]),na=rt.size;o.useEffect(()=>{y?.($t,na)},[$t,na,y]);const zt=o.useCallback(($e,Ot)=>{d($e,Ot)},[d]),Ua=o.useCallback(($e,Ot)=>{A($e),B(Ot?.toString()||""),setTimeout(()=>oe.current?.focus(),50)},[]),Ce=o.useCallback($e=>{const Ot=parseFloat(M.replace(/[^0-9.-]/g,""));d($e,"manual",isNaN(Ot)?M:Ot),A(null)},[M,d]),St=o.useCallback($e=>{d($e,"manual",M),A(null)},[M,d]),vt=o.useCallback(($e,Ot)=>{T?.([...j,{id:`catalog_${$e}_${Date.now()}`,label:Ot,source:"catalog",rowId:$e}]),ue(!1),de("")},[j,T]),Ve=o.useCallback(()=>{const $e=He.trim();if(!$e)return;const Ot=BD($e);if(Ot){Pe(Ot);return}Pe(null),T?.([...j,{id:`custom_${Date.now()}`,label:$e,source:"custom"}]),Ie(""),ue(!1)},[j,He,T]),sa=o.useCallback($e=>{T?.(j.filter(Ot=>Ot.id!==$e))},[j,T]),tt=o.useCallback(()=>{A(null),B("")},[]),it=o.useCallback(($e,Ot)=>{A(null),W($e),B(Ot!=null?String(Ot):""),setTimeout(()=>me.current?.focus(),50)},[]),Je=o.useCallback($e=>{if(M.trim()===""){d($e,"manual",""),W(null);return}const _e=parseFloat(M.replace(/[^0-9.-]/g,""));d($e,"manual",isNaN(_e)?M:_e),W(null)},[M,d]),ht=o.useCallback(($e,Ot)=>{d($e,"manual",Ot),W(null)},[d]),Kt=o.useCallback(()=>{W(null),B("")},[]),Sa=o.useMemo(()=>{const $e={};for(let Ot=0;Ot<x0;Ot++){for(const _e of["garageAttachment","garageArea","garageSurface","garageTenOrMore"]){const ma=Bp(_e,Ot),pt=c[ma]?.manualValue;pt!=null&&pt!==""&&($e[ma]=String(pt))}for(const _e of["garageCarport","garageSurface"]){const ma=Wf(_e,Ot),pt=c[ma]?.manualValue;pt!=null&&pt!==""&&($e[ma]=String(pt))}}return $e},[c]),Qt=o.useMemo(()=>`minmax(160px,1.5fr) repeat(${os.length}, minmax(56px,0.5fr)) minmax(160px,1.4fr)`,[os.length]),ea=Fe.some($e=>$e.rows.length>0||$e.addedRows.length>0)||Oe.length>0,tr=!u&&!!T,ir=($e,Ot)=>{const _e=F===$e.id,ma=c[$e.id]?.manualValue??f?.[$e.id]??null,pt=ma!=null&&ma!==""?String(ma):null,re=t4($e),qe=a4($e);return e.jsxs("div",{className:Q("grid border-b border-slate-200/40 transition-colors group",Ot%2===0?"bg-white hover:bg-blue-100/60":"bg-slate-50/80 hover:bg-blue-100/60"),style:{gridTemplateColumns:Qt},"data-testid":`row-added-${$e.id}`,children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-[11px] font-semibold truncate text-slate-500",children:$e.label}),C&&(qe?e.jsx(Fs,{section:qe.section,fieldName:qe.field}):e.jsx(Fs,{section:"fieldSelections",fieldName:$e.id})),e.jsx("button",{onClick:()=>sa($e.id),className:"text-slate-400 hover:text-red-500 hover:bg-red-50 rounded shrink-0 transition-colors p-0.5","data-testid":`button-remove-added-${$e.id}`,title:"Remove feature",children:e.jsx(ur,{className:"w-3 h-3"})})]}),os.map(Ze=>e.jsx("div",{className:"px-1 py-[5px] flex items-center justify-center border-l border-slate-200/40",children:e.jsx("span",{className:"text-slate-300 text-[11px]",children:"—"})}
2,Ze.key)),e.jsxs("div",{className:"px-2 py-[4px] flex flex-col justify-center gap-0.5 border-l-2 border-[#C5A572] bg-[#C5A572]/10 min-w-0",children:[re?e.jsxs(sr,{value:pt??"",onValueChange:Ze=>d($e.id,"manual",Ze),children:[e.jsx(rr,{className:"h-7 w-full text-xs","data-testid":`edit-select-${$e.id}`,children:e.jsx(or,{placeholder:"Select..."})}),e.jsx(nr,{children:re.map(Ze=>e.jsx(vs,{value:Ze,className:"text-xs",children:Ze},Ze))})]}):_e?e.jsxs("div",{className:"flex items-center gap-1 w-full",children:[e.jsx(ze,{ref:oe,value:M,onChange:Ze=>B(Ze.target.value),onKeyDown:Ze=>{Ze.key==="Enter"&&St($e.id),Ze.key==="Escape"&&tt()},className:"h-7 flex-1 min-w-0 text-xs text-center","data-testid":`edit-input-${$e.id}`}),e.jsx("button",{onClick:()=>St($e.id),className:"p-0.5 text-green-600 hover:text-green-700 shrink-0","data-testid":`edit-confirm-${$e.id}`,children:e.jsx(Bs,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:tt,className:"p-0.5 text-slate-400 hover:text-slate-600 shrink-0","data-testid":`edit-cancel-${$e.id}`,children:e.jsx(ur,{className:"w-3.5 h-3.5"})})]}):e.jsxs(Qh,{children:[e.jsx(Zh,{asChild:!0,children:e.jsxs("button",{className:"w-full flex items-center justify-between gap-1.5 bg-white border border-slate-200 rounded-md px-2 py-1 shadow-sm group-hover:border-blue-300 transition-colors text-left","data-testid":`edit-btn-${$e.id}`,children:[e.jsx("span",{className:"text-[11px] font-semibold tabular-nums text-[#293757] truncate",children:pt??e.jsx("span",{className:"text-slate-300 font-normal",children:"—"})}),e.jsxs("span",{className:"flex items-center gap-1 shrink-0",children:[pt?e.jsx(kr,{className:"w-3.5 h-3.5 text-emerald-500"}):e.jsx(Ru,{className:"w-3 h-3 text-slate-400"}),e.jsx(Rr,{className:"w-3 h-3 text-slate-400"})]})]})}),e.jsx(Jh,{align:"end",className:"w-52",children:e.jsxs(Yl,{onClick:()=>Ua($e.id,ma),className:"text-xs flex items-center gap-1.5","data-testid":`edit-manual-${$e.id}`,children:[e.jsx(Ru,{className:"w-3 h-3 text-slate-500"}),pt!=null?"Edit value":"Enter value"]})})]}),C&&e.jsx(Fs,{section:"fieldSelections",fieldName:`${$e.id}.manualValue`})]})]},$e.id)};if(!ea&&j.length===0&&!tr)return e.jsxs("div",{className:"text-center text-sm text-slate-500 py-6","data-testid":"subject-data-grid",children:[e.jsx(Bs,{className:"w-5 h-5 inline-block mr-1.5 text-green-500"}),ae==="unfilled"?"No unfilled fields — every locked value is set":D?"No conflicts detected — all sources agree":"No subject data available"]});const zs=v||"Locked Value",pr=Fe.some($e=>$e.rows.length>0||$e.addedRows.length>0)||Oe.length>0;return e.jsxs("div",{className:"overflow-x-auto rounded-lg border border-slate-200","data-testid":"subject-data-grid",children:[e.jsxs("div",{className:"min-w-[520px]",children:[e.jsxs("div",{className:"grid sticky top-0 z-10 bg-[#1E2940] backdrop-blur-sm border-b-2 border-[#C5A572] shadow-[0_1px_3px_rgba(0,0,0,0.12)]",style:{gridTemplateColumns:Qt},children:[e.jsx("div",{className:"px-3 py-2.5 flex items-end justify-center text-center",children:e.jsx("span",{className:"text-[12px] font-semibold text-white uppercase tracking-[0.04em] leading-tight",children:"Subject Feature"})}),os.map($e=>e.jsxs("div",{className:"px-1 py-2.5 flex flex-col items-center justify-end text-center border-l border-white/15",children:[e.jsx("span",{className:"text-[12px] font-semibold text-slate-100 uppercase tracking-[0.04em] leading-tight",children:$e.shortLabel}),e.jsx("span",{className:"text-[9px] text-slate-400 mt-0.5",children:$e.sub})]},$e.key)),e.jsxs("div",{className:"px-2.5 py-2.5 flex flex-col items-start justify-end bg-[#293757] border-l-2 border-[#C5A572]",children:[e.jsx("span",{className:"text-[9px] font-bold uppercase px-1.5 py-0.5 rounded bg-[#C5A572] text-white tracking-wide mb-0.5",children:"Verified"}),e.jsx("span",{className:"text-[12px] font-semibold text-white uppercase tracking-[0.04em] leading-tight truncate max-w-full",children:zs})]})]}),h&&e.jsx("div",{className:"flex items-center justify-end px-3 py-1 border-b border-slate-200/60 bg-slate-50/60",children:e.jsx("button",{type:"button",onClick:()=>{$($e=>!$e),V({})},className:"flex items-center gap-1 text-[10px] font-semibold text-blue-600 hover:text-blue-700 transition-colors","data-testid":"button-toggle-expand-all-subrows",children:_?e.jsxs(e.Fragment,{children:[e.jsx(Du,{className:"w-3 h-3"})," Collapse all"]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{className:"w-3 h-3"})," Expand all"]})})}),D&&!pr&&e.jsxs("div",{className:"px-3 py-6 text-center text-sm text-slate-500 bg-white","data-testid":"filter-empty-state",children:[e.jsx(Bs,{className:"w-4 h-4 inline-block mr-1.5 text-green-500"}),ae==="unfilled"?"No unfilled fields — every locked value is set.":"Nothing needs review."]}),[...Fe.map($e=>({key:$e.id,bandId:$e.id,title:$e.title,rows:$e.rows,added:$e.addedRows,optional:$e.optional,open:$e.open})),...Oe.length>0?[{key:lw,bandId:void 0,title:lw,rows:Oe,added:[],optional:!1,open:!0}]:[]].filter($e=>$e.rows.length>0||$e.added.length>0||$e.optional&&$e.open&&!D).map($e=>e.jsxs("div",{children:[e.jsx("div",{className:"grid border-y border-[#293757] bg-[#293757]",style:{gridTemplateColumns:Qt},"data-testid":$e.bandId?`band-header-${$e.bandId}`:void 0,children:e.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2",style:{gridColumn:"1 / -1"},children:[e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-[0.12em] text-white",children:$e.title}),tr&&$e.bandId&&e.jsx("button",{type:"button",onClick:()=>{H("catalog"),de(""),Be($e.bandId),ue(!0)},className:"shrink-0 rounded px-1.5 py-0.5 text-[9px] font-semibold normal-case tracking-normal text-slate-200 hover:bg-[#3A4A70] hover:text-white transition-colors","data-testid":`button-band-add-row-${$e.bandId}`,children:"+ Additional row"})]})}),$e.optional&&$e.open&&$e.bandId&&ne[$e.bandId]&&e.jsx("div",{className:"grid border-b border-slate-200/40 bg-emerald-50/60",style:{gridTemplateColumns:Qt},children:e.jsx("div",{className:"px-3 py-1 text-[10px] text-emerald-700",style:{gridColumn:"1 / -1"},"data-testid":`band-detection-note-${$e.bandId}`,children:$D(ne[$e.bandId])})}),(()=>{const Ot=(_e,ma)=>{const pt=F===_e.config.id,re=_e.config.id==="functionalUtility",qe=_e.config.id==="energyEfficient",Ze=_e.config.id==="qualityCondition"||_e.config.id==="interiorQualityCondition"||_e.config.id==="exteriorQualityCondition",It=_e.config.id==="basement",Ne=_e.config.id==="garageCarport",Ue=_e.config.id==="location",ct=_e.config.id==="view",xt=_e.config.id==="heatingCooling",Na=_e.config.id==="pool",qt=_e.config.id==="porchPatioDeck",la=Zt=>{const Rs=c[Zt]?.manualValue;return Rs==null?"":String(Rs)},fs=h&&(xt||qe||Ue||ct),ps=!fs||(z[_e.config.id]??_),Te=(()=>
2{if(!fs)return"";if(xt){const Rs=["heatingType","heatingFuel","cooling"].filter(Os=>la(Os)!=="").length;return Rs===0&&_e.manualValue!=null&&_e.manualValue!==""?String(_e.manualValue):`${Rs} of 3 set`}if(qe){const Rs=["efficiencyRatingExists","greenCertificationExists","renewableEnergyExists"].filter(Os=>la(Os)!=="").length;return Rs===0?"Not set":`${Rs} of 3 set`}const Zt=Rm(_e.manualValue);return Zt.length>0?Zt.join(", "):"Not set"})(),at=(Zt,Rs)=>{d(Zt,"manual",Rs)},yt=(()=>{const Zt=_e.currentSource==="manual"?_e.manualValue:_e.values[_e.currentSource];return Zt==null||Zt===""?null:_e.config.formatter?_e.config.formatter(Zt):String(Zt)})(),nt=os.filter(Zt=>{const Rs=_e.values[Zt.key];return Rs!=null&&Rs!==""}),Wt=_e.enumOptions?_e.enumOptions.map(Zt=>({value:Zt,label:Zt})):_e.config.selectOptions??null,ts=_e.lockedSelectValue,gs=le===_e.config.id,Va=_e.manualValue!=null&&_e.manualValue!==""?_e.manualValue:_e.values.ins!=null&&_e.values.ins!==""?_e.values.ins:null,Mr=Va!=null&&Va!=="",xs=Mr?_e.config.formatter?_e.config.formatter(Va):String(Va):null,Sn=_e.currentSource==="manual"||_e.currentSource==="ins",ds=Wt&&Mr&&Wt.some(Zt=>Zt.value===String(Va))?String(Va):"";return e.jsxs("div",{className:Q("grid border-b border-slate-200/40 transition-colors group",ma%2===0?"bg-white hover:bg-blue-100/60":"bg-slate-50/80 hover:bg-blue-100/60",_e.needsReview&&"shadow-[inset_2px_0_0_0_#fbbf24]"),style:{gridTemplateColumns:Qt},"data-testid":`row-${_e.config.id}`,children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-[11px] font-semibold truncate text-slate-500",children:_e.config.label}),C&&(zA[_e.config.id]?e.jsx(Fs,{section:zA[_e.config.id].section,fieldName:zA[_e.config.id].field}):e.jsx(Fs,{section:"fieldSelections",fieldName:_e.config.id})),_e.needsReview&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0","data-testid":`review-dot-${_e.config.id}`})]}),os.map(Zt=>{const Rs=_e.config.id==="qualityCondition",Os=Zt.key==="ai";if(Rs&&Os&&l&&!_e.values.ai)return e.jsx("div",{className:"px-1 py-[5px] flex items-center justify-center border-l border-slate-200/40",children:e.jsx(za,{className:"w-3 h-3 animate-spin text-purple-400"})},Zt.key);if(_e.config.id==="gla"&&Os&&S!==void 0)return e.jsx(f4,{value:_e.values.ai,confidence:N,normNote:x,formatter:_e.config.formatter,isActive:_e.currentSource==="ai",onClick:()=>zt(_e.config.id,"ai")},Zt.key);if(Zt.key==="ins"){if(Ze){const ot=_e.config.id==="qualityCondition"?"quality":_e.config.id==="interiorQualityCondition"?"interiorQuality":"exteriorQuality",xa=_e.config.id==="qualityCondition"?"condition":_e.config.id==="interiorQualityCondition"?"interiorCondition":"exteriorCondition",rs=_e.values.ins!=null?String(_e.values.ins):"",Gs=rs.match(/\bQ[1-6]\b/)?.[0]??"",bs=rs.match(/\bC[1-6]\b/)?.[0]??"",ba=zn=>{const fd=la(zn);return fd||(zn===ot?Gs:zn===xa?bs:"")},ln=!!(la(ot)||la(xa));return e.jsx("div",{className:"px-1 py-[4px] flex items-center border-l border-slate-200/40","data-testid":`manual-cell-${_e.config.id}`,children:e.jsx("div",{className:Q("w-full rounded p-0.5",ln&&"bg-emerald-50 ring-1 ring-emerald-300"),children:e.jsx(dw,{qualityKey:ot,conditionKey:xa,get:ba,set:at,testidBase:`manual-qcpair-${_e.config.id}`})})},Zt.key)}if(gs)return e.jsx("div",{className:"px-1 py-[4px] flex items-center border-l border-slate-200/40",children:Wt?e.jsxs(sr,{defaultOpen:!0,value:ds,onValueChange:ot=>ht(_e.config.id,ot),onOpenChange:ot=>{ot||Kt()},children:[e.jsx(rr,{className:"h-7 w-full text-xs","data-testid":`manual-select-${_e.config.id}`,children:e.jsx(or,{placeholder:"Select..."})}),e.jsx(nr,{children:Wt.map(ot=>e.jsx(vs,{value:ot.value,className:"text-xs",children:ot.label},ot.value))})]}):e.jsx(ze,{ref:me,value:M,onChange:ot=>B(ot.target.value),onBlur:()=>Je(_e.config.id),onKeyDown:ot=>{ot.key==="Enter"&&Je(_e.config.id),ot.key==="Escape"&&Kt()},className:"h-7 w-full min-w-0 text-xs text-center","data-testid":`manual-input-${_e.config.id}`})},Zt.key);const dt=!!_e.values.insBoxli&&!(_e.manualValue!=null&&_e.manualValue!=="")&&Mr;return e.jsx("div",{className:"px-1 py-[5px] flex items-center justify-center border-l border-slate-200/40",children:e.jsx("button",{type:"button",onClick:()=>it(_e.config.id,Va),className:Q("w-full flex items-center justify-center gap-1 rounded px-1 py-0.5 text-[11px] transition-colors group/manual",Sn?"bg-emerald-50 text-emerald-700 font-semibold ring-1 ring-emerald-300":"text-slate-600 hover:bg-blue-50"),"data-testid":`manual-cell-${_e.config.id}`,title:dt?"From the Boxli inspection scan — click to edit":"Click to edit",children:xs!=null?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tabular-nums truncate",children:xs}),dt&&e.jsx("span",{className:"shrink-0 text-[7px] font-bold uppercase tracking-tight text-sky-600 leading-none","data-testid":`cell-ins-boxli-${_e.config.id}`,children:"Boxli"})]}):e.jsx(Ru,{className:"w-3 h-3 text-slate-300 group-hover/manual:text-blue-400"})})},Zt.key)}const Ks=_e.values[Zt.key],Tn=Ks!=null&&Ks!=="",Bn=Tn?_e.config.formatter?_e.config.formatter(Ks):String(Ks):null,Ka=_e.currentSource===Zt.key,Ee=Tn&&!Ka&&yt!=null&&Bn!==yt;return e.jsx(m4,{value:Ks,formatter:_e.config.formatter,isActive:Ka,isConflict:Ee,sourceKey:Zt.key,onClick:()=>zt(_e.config.id,Zt.key),hasValue:Tn,mappedFrom:Zt.key==="ai"?_e.aiMappedFrom:null,aiSuggested:Zt.key==="ai"?_e.aiSuggested:!1},Zt.key)}),e.jsxs("div",{className:"px-2 py-[4px] flex flex-col justify-center gap-0.5 border-l-2 border-[#C5A572] bg-white min-w-0",children:[fs&&!ps?e.jsxs("button",{type:"button",onClick:()=>V(Zt=>({...Zt,[_e.config.id]:!0})),className:"w-full flex items-center justify-between gap-1.5 bg-white border border-slate-200 rounded-md px-2 py-1 shadow-sm group-hover:border-blue-300 transition-colors text-left","data-testid":`subrow-summary-${_e.config.id}`,children:[e.jsx("span",{className:"text-[11px] font-semibold tabular-nums text-[#293757] truncate",children:Te}),e.jsx(Rr,{className:"w-3 h-3 text-slate-400 shrink-0"})]}):re?e.jsx(b4,{options:g4,tokens:cw(_e.manualValue),otherDescription:la("functionalIssueOtherDescription"),onTokensChange:Zt=>{at("functionalUtility",x4(Zt)),Zt.includes("Other")||at("functionalIssueOtherDescription","")},onOtherChange:Zt=>at("functionalIssueOtherDescription",Zt)}):qe?e.jsx(N4,{get:la,set:at}):Ze?e.jsx(dw,{qualityKey:_e.config.id==="qualityCondition"?"quality":_e.config.id==="interiorQualityCondition"?"interiorQuality":"exteriorQuality",conditionKey:_e.config.id==="qualityCondition"?"condition":_e.config.id==="interiorQualityCondition"?"interior
2Condition":"exteriorCondition",get:la,set:at,testidBase:`qcpair-${_e.config.id}`}):It?e.jsx(A4,{get:la,set:at}):Ne?e.jsx("div",{className:"w-full","data-testid":"garage-storage-cell",children:e.jsx(JD,{currentValue:_e.manualValue??null,onSelect:Zt=>d("garageCarport","manual",Zt),otherDescriptions:Sa,onOtherDescriptionChange:(Zt,Rs)=>at(Zt,Rs),uad36:!0},String(_e.manualValue??""))}):Ue?e.jsxs("div",{className:"w-full space-y-1","data-testid":"site-influence-cell",children:[e.jsx(tv,{enumField:"SiteInfluenceType",options:Pr("SiteInfluenceType")??[],tokens:Rm(_e.manualValue),onChange:Zt=>{at("location",Zt.join("|")),Zt.includes("Other")||at("SiteInfluenceTypeOtherDescription","")},testidBase:"site-influence",placeholder:"Select site influences…"}),Rm(_e.manualValue).includes("Other")&&e.jsx(ze,{value:la("SiteInfluenceTypeOtherDescription"),onChange:Zt=>at("SiteInfluenceTypeOtherDescription",Zt.target.value),placeholder:"Describe other influence",className:"h-7 text-[11px]","data-testid":"site-influence-other-desc"}),Rm(_e.manualValue).includes("BodyOfWater")&&e.jsx(y4,{get:la,set:at})]}):ct?e.jsx("div",{className:"w-full","data-testid":"site-views-cell",children:e.jsx(J3,{getValue:Zt=>la(ow(Zt)),setValue:(Zt,Rs)=>at(ow(Zt),Rs),subjectMode:!0,testIdPrefix:"verify-view"})}):xt?e.jsx(S4,{get:la,set:at}):Na?e.jsx(tv,{enumField:"AmenityType",options:g0.WaterFeatures,tokens:Rm(_e.manualValue).filter(Zt=>g0.WaterFeatures.includes(Zt)),onChange:Zt=>at("pool",Zt.join("|")),testidBase:"water-features",placeholder:"None",optional:!0}):qt?e.jsx(tv,{enumField:"AmenityType",options:g0.OutdoorLiving,tokens:Rm(_e.manualValue).filter(Zt=>g0.OutdoorLiving.includes(Zt)),onChange:Zt=>at("porchPatioDeck",Zt.join("|")),testidBase:"outdoor-living",placeholder:"None",optional:!0}):Wt?(()=>{const Zt=e4[_e.config.id];return e.jsxs("div",{className:"w-full space-y-1",children:[e.jsxs(sr,{value:ts,onValueChange:Rs=>{d(_e.config.id,"manual",Rs),Zt&&Rs!=="Other"&&at(Zt,"")},children:[e.jsx(rr,{className:"h-7 w-full text-xs","data-testid":`edit-select-${_e.config.id}`,children:e.jsx(or,{placeholder:"Select..."})}),e.jsx(nr,{children:Wt.map(Rs=>e.jsx(vs,{value:Rs.value,className:"text-xs",children:Rs.label},Rs.value))})]}),Zt&&ts==="Other"&&e.jsx(ze,{value:la(Zt),onChange:Rs=>at(Zt,Rs.target.value),placeholder:"Describe other",className:"h-7 text-[11px]","data-testid":`edit-other-desc-${_e.config.id}`})]})})():pt?e.jsxs("div",{className:"flex items-center gap-1 w-full",children:[e.jsx(ze,{ref:oe,value:M,onChange:Zt=>B(Zt.target.value),onKeyDown:Zt=>{Zt.key==="Enter"&&Ce(_e.config.id),Zt.key==="Escape"&&tt()},className:"h-7 flex-1 min-w-0 text-xs text-center","data-testid":`edit-input-${_e.config.id}`}),e.jsx("button",{onClick:()=>Ce(_e.config.id),className:"p-0.5 text-green-600 hover:text-green-700 shrink-0","data-testid":`edit-confirm-${_e.config.id}`,children:e.jsx(Bs,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:tt,className:"p-0.5 text-slate-400 hover:text-slate-600 shrink-0","data-testid":`edit-cancel-${_e.config.id}`,children:e.jsx(ur,{className:"w-3.5 h-3.5"})})]}):e.jsxs(Qh,{children:[e.jsx(Zh,{asChild:!0,children:e.jsxs("button",{className:"w-full flex items-center justify-between gap-1.5 bg-white border border-slate-200 rounded-md px-2 py-1 shadow-sm group-hover:border-blue-300 transition-colors text-left","data-testid":`edit-btn-${_e.config.id}`,children:[e.jsx("span",{className:"text-[11px] font-semibold tabular-nums text-[#293757] truncate",children:yt??e.jsx("span",{className:"text-slate-300 font-normal",children:"—"})}),e.jsxs("span",{className:"flex items-center gap-1 shrink-0",children:[_e.hasConflict?e.jsx(p4,{sourceKey:_e.currentSource}):_e.lockedEmpty&&!_e.intentionallyEmpty?e.jsx(Ns,{className:"w-3.5 h-3.5 text-amber-500"}):e.jsx(kr,{className:"w-3.5 h-3.5 text-emerald-500"}),e.jsx(Rr,{className:"w-3 h-3 text-slate-400"})]})]})}),e.jsxs(Jh,{align:"end",className:"w-52",children:[nt.map(Zt=>{const Rs=_e.values[Zt.key],Os=_e.config.formatter?_e.config.formatter(Rs):String(Rs),qs=_e.currentSource===Zt.key;return e.jsxs(Yl,{onClick:()=>zt(_e.config.id,Zt.key),className:"text-xs flex items-center justify-between gap-2","data-testid":`verified-pick-${_e.config.id}-${Zt.key}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:Q("text-[8px] px-1 py-0.5 rounded font-bold uppercase tracking-wide",Zt.bg,Zt.color),children:Zt.shortLabel}),e.jsx("span",{className:"tabular-nums text-slate-700",children:Os})]}),qs&&e.jsx(Bs,{className:"w-3.5 h-3.5 text-[#293757]"})]},Zt.key)}),nt.length>0&&e.jsx(f0,{}),e.jsxs(Yl,{onClick:()=>Ua(_e.config.id,_e.manualValue),className:"text-xs flex items-center gap-1.5","data-testid":`edit-manual-${_e.config.id}`,children:[e.jsx(Ru,{className:"w-3 h-3 text-slate-500"}),_e.currentSource==="manual"&&_e.manualValue!=null?"Edit manual value":"Enter manually"]})]})]}),fs&&ps&&e.jsxs("button",{type:"button",onClick:()=>V(Zt=>({...Zt,[_e.config.id]:!1})),className:"self-start flex items-center gap-0.5 text-[9px] font-medium text-slate-400 hover:text-slate-600 transition-colors","data-testid":`subrow-collapse-${_e.config.id}`,children:[e.jsx(Du,{className:"w-2.5 h-2.5"})," Collapse"]}),_e.lockedEmpty&&!_e.intentionallyEmpty&&(_e.unresolvedSourceText?e.jsxs("span",{className:"flex items-start gap-0.5 text-[9px] font-medium text-amber-700 leading-tight","data-testid":`unresolved-cue-${_e.config.id}`,children:[e.jsx(Ns,{className:"w-2.5 h-2.5 shrink-0 mt-px"}),e.jsxs("span",{className:"truncate",children:[`Couldn't standardize "`,_e.unresolvedSourceText,'" — pick a value']})]}):e.jsx("span",{className:"text-[9px] font-medium text-amber-600 leading-tight","data-testid":`needs-value-cue-${_e.config.id}`,children:"Needs a value"})),C&&e.jsx(Fs,{section:"fieldSelections",fieldName:`${r4(_e.config.id)}.manualValue`})]})]},_e.config.id)};return $e.rows.map((_e,ma)=>Ot(_e,ma))})(),$e.added.map((Ot,_e)=>ir(Ot,$e.rows.length+_e)),$e.rows.length===0&&$e.added.length===0&&e.jsx("div",{className:"grid border-b border-slate-200/40 bg-white",style:{gridTemplateColumns:Qt},children:e.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2",style:{gridColumn:"1 / -1"},children:[e.jsx("span",{className:"text-[10px] text-slate-400","data-testid":`band-empty-${$e.bandId}`,children:d4[$e.bandId]??'No rows yet — use "+ Additional row" to add data points to this section.'}),e.jsxs("button",{type:"button",onClick:()=>{H("catalog"),de(""),Be($e.bandId??null),ue(!0)},className:"inline-flex items-center gap-0.5 text-[10px] font-semibold text-blue-600 hover:text-blue-700","data-testid":`band-empty-add-${$e.bandId}`,children:[e.jsx(un,{className:"w-3 h-3"})," Add a row"]})]})})]},$e.key)),tr&&ya.flat.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"grid border-b border-slate-300/60 bg-slate-50/80",style:{gridTemplateColumns:Qt},children:e.jsxs("div",{className:"px-3 py-1 flex items-center justify-between gap-2",style:{gridColumn:"1 / -1"},children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-[0.1em] text-slate-900",children:"Additional Features"}),e.jsxs("button",{type:"button",onClick:()=>{H("catalog"),ue(!0)},className:"flex items-center gap-1 text-[10px] font-semibold text-blue-600 hover:text-blue-700","data-testid":"button-add-feature-header",children:[e.jsx(un,{className:"w-3 h-3"})," + Additional row"]})]})}),ya.flat.map(($e,Ot)=>ir($e,Ot))]}),(tr||!D)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5 px-3 py-2 border-t border-slate-200/60 bg-white",children:[tr&&e.jsxs("button",{type:"button",onClick:()=>{H("catalog"),ue(!0)},className:"flex items-center gap-2 rounded-md bg-blue-600 px-3 py-2 text-xs font-semibold text-white shadow-sm hover:bg-blue-700 transition-colors shrink-0","data-testid":"button-add-feature",children:[e.jsx(un,{className:"w-4 h-4"})," + Additional row"]}),!D&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5","data-testid":"b1-optional-section-strip",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400 mr-1",children:"Add section:"}),Fe.filter($e=>$e.optional).map($e=>e.jsxs("button",{type:"button",onClick:Ot=>{const _e=!$e.open;if(Re(ma=>
2({...ma,[$e.id]:_e})),_e){const ma=Ot.currentTarget.closest('[data-testid="subject-data-grid"]');window.setTimeout(()=>{ma?.querySelector(`[data-testid="band-header-${$e.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},50)}},className:Q("inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[10px] font-semibold transition-colors",$e.open?"bg-[#293757] border-[#293757] text-white hover:bg-[#1E2940]":"bg-white border-slate-300 text-slate-600 hover:border-[#293757] hover:text-[#293757]"),"data-testid":`toggle-band-${$e.id}`,children:[$e.open?e.jsx(Bs,{className:"w-3 h-3"}):e.jsx(un,{className:"w-3 h-3"}),$e.title,ne[$e.id]&&e.jsxs("span",{className:Q("text-[9px] font-medium normal-case",$e.open?"text-slate-300":"text-emerald-600"),title:ne[$e.id].reason,"data-testid":`detected-cue-${$e.id}`,children:["· ",VD(ne[$e.id])]})]},$e.id))]}),tr&&!ea&&j.length===0&&e.jsx("span",{className:"text-[11px] text-slate-400",children:"No subject data yet — add a feature to get started."})]})]}),e.jsx(xi,{open:fe,onOpenChange:$e=>{ue($e),$e||(de(""),Ie(""),Be(null))},children:e.jsxs(bi,{className:"max-w-xl bg-white border-slate-200","data-testid":"dialog-add-feature",children:[e.jsxs($i,{children:[e.jsx(si,{className:"font-sans text-slate-900",children:"+ Additional row"}),e.jsx(pl,{className:"font-sans text-slate-500",children:"Pick a schema row or add a free-form custom row. It also appears on the Sales Comparison grid."})]}),e.jsxs(up,{value:be,onValueChange:$e=>H($e),children:[e.jsxs(pp,{className:"grid grid-cols-2 w-full bg-slate-100",children:[e.jsx($n,{value:"catalog","data-testid":"tab-catalog",className:"data-[state=active]:bg-white data-[state=active]:text-slate-900",children:"Schema rows"}),e.jsx($n,{value:"custom","data-testid":"tab-custom",className:"data-[state=active]:bg-white data-[state=active]:text-slate-900",children:"Custom row"})]}),e.jsxs(Bd,{value:"catalog",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Eu,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-slate-400"}),e.jsx(ze,{value:ye,onChange:$e=>de($e.target.value),placeholder:"Search rows…",className:"pl-8 h-9","data-testid":"input-search-catalog-feature"})]}),ge&&e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md bg-blue-50 border border-blue-200 px-2.5 py-1.5 text-xs text-blue-800","data-testid":"picker-band-filter",children:[e.jsxs("span",{children:["Showing rows for ",e.jsx("span",{className:"font-semibold",children:hd.find($e=>$e.id===ge)?.title??ge})]}),e.jsx("button",{type:"button",onClick:()=>Be(null),className:"shrink-0 font-semibold text-blue-600 hover:text-blue-800","data-testid":"button-clear-band-filter",children:"Show all"})]}),e.jsx(Qd,{className:"h-72 border rounded-md",children:(()=>{const $e=ye.trim().toLowerCase(),Ot=new Set(j.filter(re=>re.source==="catalog"&&re.rowId).map(re=>re.rowId)),ma=MD(G,!1,G).filter(re=>Ot.has(re.rowId)||ge&&Dh(re.rowId,re.group)!==ge?!1:$e?re.label.toLowerCase().includes($e)||re.group.toLowerCase().includes($e):!0);if(ma.length===0)return e.jsx("div",{className:"p-4 text-sm text-slate-500","data-testid":"text-catalog-empty",children:"No rows match. Try a different search term, or add a custom row."});const pt=new Map;for(const re of ma){const qe=pt.get(re.group)??[];qe.push(re),pt.set(re.group,qe)}return Array.from(pt.entries()).map(([re,qe])=>e.jsxs("div",{className:"border-b last:border-b-0",children:[e.jsx("div",{className:"px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wide bg-slate-50 text-slate-500",children:re}),e.jsx("ul",{children:qe.map(Ze=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>vt(Ze.rowId,Ze.label),className:"w-full text-left px-3 py-2 hover:bg-blue-50 flex items-center justify-between gap-2 text-sm","data-testid":`option-feature-${Ze.rowId}`,children:[e.jsx("span",{className:"font-medium truncate",children:Ze.label}),e.jsx(kt,{variant:"outline",className:"text-[10px] shrink-0",children:Ze.inputType})]})},Ze.rowId))})]},re))})()})]}),e.jsxs(Bd,{value:"custom",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{htmlFor:"custom-feature-label",children:"Row name"}
2),e.jsx(ze,{id:"custom-feature-label",value:He,onChange:$e=>{Ie($e.target.value),Pe(null)},placeholder:"Row name…","data-testid":"input-custom-feature-label",onKeyDown:$e=>{$e.key==="Enter"&&He.trim()&&($e.preventDefault(),Ve())}}),e.jsx("p",{className:"text-xs text-slate-500",children:"Custom rows accept free-form text."}),ce&&e.jsx("p",{className:"text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded-md px-2 py-1.5","data-testid":"text-custom-feature-duplicate",children:ce})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(De,{type:"button",size:"sm",onClick:Ve,disabled:!He.trim(),"data-testid":"button-add-custom-feature",children:[e.jsx(un,{className:"w-4 h-4 mr-1"})," Add custom row"]})})]})]})]})})]})}const ak={gla:["gla"],bedrooms:["beds"],bathrooms:["bathsFull","bathsHalf"],fullBaths:["bathsFull"],halfBaths:["bathsHalf"],yearBuilt:["yearBuilt"],lotSize:["lotSize"],attachmentType:["attachedDetached"],quality:["qualityCondition"],condition:["qualityCondition"],basementArea:["basement"],basementFinish:["basement"]},j4=["Q1","Q2","Q3","Q4","Q5","Q6"],T4=["C1","C2","C3","C4","C5","C6"];function I4(t){switch(t){case"gla":case"beds":case"bathsFull":case"bathsHalf":case"yearBuilt":case"lotSize":return{kind:"number",keys:[t]};case"attachedDetached":{const a=ML("attachedDetached")??[];return{kind:"enum",keys:[t],options:a}}case"qualityCondition":return{kind:"qcPair",keys:["quality","condition"]};case"basement":return{kind:"basementArea",keys:["basementFinishedSqft","basementUnfinishedSqft"]};default:return null}}function C4(t){if(t==null||t==="")return{full:null,half:null};const a=parseFloat(String(t));if(!Number.isFinite(a))return{full:null,half:null};const s=Math.floor(a);return{full:s,half:a-s>.01?1:0}}const R4=t=>{const a=[];for(const[s,r]of Object.entries(Kp)){const n=ak[r];n&&n.includes(t)&&a.push(s)}return a},Kf=t=>!TI(t);function pw(t,a){const s=t[a];return s&&s.selectedSource==="manual"&&Kf(s.manualValue)?String(s.manualValue):null}function E4(t){const{scanFields:a,bag:s,fieldSelections:r}=t,n=new Map;for(const c of a)c&&typeof c.fieldKey=="string"&&Kf(c.value)&&n.set(c.fieldKey,{value:c.value,displayValue:c.displayValue});const i=c=>{const d=c4[c]??c,p=R4(c),u=I4(c);let m=null,h=null;const f=new Map,v=p.filter(j=>n.has(j));if(v.length>0)if(c==="bathsFull"||c==="bathsHalf"){const j=c==="bathsFull"?n.get("fullBaths"):n.get("halfBaths");if(j)m=String(j.value),f.set(c,j.value);else{const T=C4(n.get("bathrooms")?.value),O=c==="bathsFull"?T.full:T.half;O!=null&&(m=String(O),f.set(c,O))}}else if(c==="qualityCondition"){const j=n.get("quality")?.value,T=n.get("condition")?.value;m=[j,T].filter(Kf).join(" / ")||null,Kf(j)&&f.set("quality",j),Kf(T)&&f.set("condition",T)}else if(c==="basement"){const j=n.get("basementSqft"),T=n.get("belowGradeFinished"),O=[];j&&O.push(j.displayValue||`${j.value} sf`),T&&O.push(`${T.displayValue||`${T.value}% finished`}`),m=O.join(" · ")||null,j&&f.set("basementFinishedSqft",j.value)}else if(u?.kind==="enum"){const j=n.get(v[0]);
2h=Em(c,j.value)?.value??null,m=h??String(j.displayValue||j.value),f.set(c,h??j.value)}else{const j=n.get(v[0]);m=String(j.displayValue||j.value),f.set(c,j.value)}let S=null,N=!1;const y=(u?.keys??[c]).map(j=>pw(r,j)).filter(j=>j!=null);if(y.length>0)S=y.join((u?.kind==="qcPair"," / ")),N=!0;else for(const j of p){const T=Kp[j],O=T?s[T]:void 0;if(O&&Kf(O.value)){S=String(O.value);break}}let b="none";if(m!=null)if(v.some(T=>J2(T,n.get(T).value,s)))b="merged";else{let T=!1;for(const[O,E]of Array.from(f.entries())){const R=pw(r,O);if(R!=null&&!yv(R,E)){T=!0;break}const G=v.find(F=>Kp[F]&&ak[Kp[F]]?.includes(c)),U=G?Kp[G]:void 0,C=U?s[U]:void 0;if(R==null&&C&&Kf(C.value)&&C.source!=="boxli"&&!yv(C.value,E)){T=!0;break}}b=T?"conflict":"scan"}return{rowId:c,label:d,scanKeys:p,scanDisplay:m,normalizedEnumValue:h,status:b,currentValue:S,currentIsManual:N,edit:u}},l=[];for(const c of l4){if(c.ids.length===0)continue;const d=c.ids.map(i);c.optional&&!d.some(p=>p.scanDisplay!=null)||l.push({id:c.id,title:c.title,rows:d})}return l}const w4="#072034",YA="#E7DFD2",P4="#FAF6EF";function GA({rowId:t,fieldKey:a,current:s,disabled:r,onCommit:n}){const[i,l]=o.useState(null),c=i??s??"",d=()=>{if(i==null)return;const p=i.trim();l(null),!(p===""||p===(s??""))&&n(a,p)};return e.jsx(ze,{className:"h-7 w-28 text-xs",value:c,disabled:r,placeholder:"—",inputMode:"decimal",onChange:p=>l(p.target.value),onBlur:d,onKeyDown:p=>{p.key==="Enter"&&p.target.blur()},"data-testid":`grid-preview-input-${t}-${a}`})}function HA({rowId:t,fieldKey:a,options:s,current:r,disabled:n,placeholder:i,onCommit:l}){return e.jsxs(sr,{value:r&&s.includes(r)?r:void 0,disabled:n,onValueChange:c=>{c&&c!==r&&l(a,c)},children:[e.jsx(rr,{className:"h-7 w-36 text-xs","data-testid":`grid-preview-select-${t}-${a}`,children:e.jsx(or,{placeholder:i??"—"})}),e.jsx(nr,{children:s.map(c=>e.jsx(vs,{value:c,className:"text-xs","data-testid":`grid-preview-option-${t}-${a}-${c}`,children:c},c))})]})}function O4({row:t}){return t.status==="merged"?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] font-medium text-emerald-700 uppercase tracking-wide shrink-0",title:"This scan value is merged into the order.","data-testid":`grid-preview-merged-${t.rowId}`,children:[e.jsx(kr,{className:"w-3 h-3"})," In order"]}):t.status==="conflict"?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] font-medium text-amber-700 uppercase tracking-wide shrink-0",title:"Your value disagrees with the scan — merging will ask whether to replace or keep it.","data-testid":`grid-preview-conflict-${t.rowId}`,children:[e.jsx(Ns,{className:"w-3 h-3"})," Conflict"]}):t.status==="scan"?e.jsx("span",{className:"inline-flex items-center text-[10px] font-medium text-slate-400 uppercase tracking-wide shrink-0",title:"The scan captured this value but it hasn't been merged to the order yet.","data-testid":`grid-preview-scanonly-${t.rowId}`,children:"Scan only"}):null}function L4({scanFields:t,bag:a,bagState:s,fieldSelections:r,onFieldEdit:n}){const i=o.useMemo(()=>E4({scanFields:t,bag:a,fieldSelections:r}),[t,a,r]),l=!!n&&s==="ok",c=(p,u)=>{n?.({[p]:u})},d=p=>{const u=r[p];return u?.selectedSource==="manual"&&u.manualValue!=null&&String(u.manualValue).trim()!==""?String(u.manualValue):null};return t.length===0?e.jsx("div",{className:"bg-white border rounded-lg p-4 text-xs text-slate-500",style:{borderColor:YA},"data-testid":"grid-preview-empty",children:"No inspection scan data yet — pull a scan first, then this view shows where each value will land on the Subject Verify grid."}):e.jsxs("div",{className:"space-y-3","data-testid":"inspection-grid-preview",children:[e.jsxs("p",{className:"text-[11px] text-slate-500",children:["Where the scan data lands on the Subject Verify grid. Edits here become your manual (EDIT) value on the Verify step — same data, two views.",s==="loading"&&e.jsxs("span",{className:"inline-flex items-center gap-1 ml-2 text-slate-400",children:[e.jsx(za,{className:"w-3 h-3 animate-spin"})," Loading order values…"]})]}),i.map(p=>e.jsxs("div",{className:"bg-white border rounded-lg overflow-hidden",style:{borderColor:YA},"data-testid":`grid-preview-band-${p.id}`,children:[e.jsx("div",{className:"px-3 py-1.5 border-b text-[11px] font-semibold uppercase tracking-wider",style:{backgroundColor:P4,borderColor:YA,color:w4},children:p.title}),e.jsx("div",{className:"divide-y divide-slate-100",children:p.rows.map(u=>e.jsxs("div",{className:"px-3 py-1.5 grid grid-cols-[minmax(140px,1.2fr)_minmax(90px,1fr)_auto] items-center gap-2","data-testid":`grid-preview-row-${u.rowId}`,children:[e.jsx("div",{className:"text-xs font-medium text-slate-700 truncate",title:u.label,children:u.label}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:`text-xs truncate ${u.scanDisplay==null?"text-slate-300":"text-slate-600"}`,title:u.scanDisplay??"No scan data","data-testid":`grid-preview-scan-${u.rowId}`,children:u.scanDisplay??"—"}),e.jsx(O4,{row:u})]}),e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[u.edit?.kind==="number"&&e.jsx(GA,{rowId:u.rowId,fieldKey:u.edit.keys[0],current:u.currentIsManual?u.currentValue:d(u.edit.keys[0]),disabled:!l,onCommit:c}),u.edit?.kind==="enum"&&e.jsx(HA,{rowId:u.rowId,fieldKey:u.edit.keys[0],options:u.edit.options??[],current:d(u.edit.keys[0]),disabled:!l,onCommit:c}),u.edit?.kind==="qcPair"&&e.jsxs(e.Fragment,{children:[e.jsx(HA,{rowId:u.rowId,fieldKey:"quality",options:j4,current:d("quality"),disabled:!l,placeholder:"Q—",onCommit:c}),e.jsx(HA,{rowId:u.rowId,fieldKey:"condition",options:T4,current:d("condition"),disabled:!l,placeholder:"C—",onCommit:c})]}),u.edit?.kind==="basementArea"&&e.jsxs(e.Fragment,{children:[e.jsx(GA,{rowId:u.rowId,fieldKey:"basementFinishedSqft",current:d("basementFinishedSqft"),disabled:!l,onCommit:c}),e.jsx("span",{className:"text-[10px] text-slate-400",children:"fin sf /"}),e.jsx(GA,{rowId:u.rowId,fieldKey:"basementUnfinishedSqft",current:d("basementUnfinishedSqft"),disabled:!l,onCommit:c}),e.jsx("span",{className:"text-[10px] text-slate-400",children:"unfin sf"})]}),!u.edit&&e.jsx("span",{className:`text-xs ${u.currentValue==null?"text-slate-300":u.currentIsManual?"text-slate-800 font-medium":"text-slate-600"}`,"data-testid":`grid-preview-current-${u.rowId}`,children:u.currentValue??"—"})]})]},u.rowId))})]}
2,p.id)),e.jsx("p",{className:"text-[10px] text-slate-400",children:"Rows the scan can't fill show a dash — their values are still edited on the Verify step. Scan-only fields without a grid row (altitude, ceiling height, …) stay in the Provider view."})]})}x_.map(t=>t.value);b_.map(t=>t.value);y_.map(t=>t.value);const D4=["Kitchen","Bathroom","Bedroom","LivingArea","DiningRoom","Laundry","Basement","Garage","Exterior","Other"];bL.map(t=>t.value);xL.map(t=>t.value);gL.map(t=>t.value);function _b(t){if(t.length===0)return{value:null,photoIds:[]};const a=new Map;for(const n of t){const i=a.get(n.token)??[];i.push(n.photoId),a.set(n.token,i)}let s=null,r=[];for(const[n,i]of Array.from(a.entries()))(i.length>r.length||i.length===r.length&&(s===null||n>s))&&(s=n,r=i);return{value:s,photoIds:r}}const k4={Kitchen:"Kitchen",Bathroom:"FullBathroom",Bedroom:"Bedroom",LivingArea:"LivingRoom",DiningRoom:"DiningRoom",Laundry:"LaundryRoom",Basement:null,Garage:null,Exterior:null,Other:null},M4={Kitchen:"Kitchen",Bathroom:"Bathroom",Bedroom:"Bedroom",LivingArea:"Living Area",DiningRoom:"Dining Room",Laundry:"Laundry",Basement:"Basement",Garage:"Garage",Exterior:"Exterior",Other:"Other"};function sk(t){return t.sceneOverride??t.insight?.sceneCategory??null}function WA(t){return t.insight?.kind==="exterior"?!0:t.insight?.kind==="interior"?!1:sk(t)==="Exterior"}function KA(t){for(const a of t)if(a)return a;return null}function F4(t){const a=t.filter(b=>b.status==="ok"&&b.insight),s=t.filter(b=>b.status==="error").length,r=[],n=[],i=[],l=[];for(const b of a){const j=b.insight,T=WA(b);j.qualityRating&&(T?i:r).push({token:j.qualityRating,photoId:b.photoId}),j.conditionRating&&(T?l:n).push({token:j.conditionRating,photoId:b.photoId})}const c=_b(r),d=_b(n),p=_b(i),u=_b(l),m=(b,j)=>b.value?j.value?b.value>=j.value?b:j:b:j,h=m(c,p),f=m(d,u),v={AttachmentType:[],StructuralDesignType:[],ConstructionMethodType:[],CarStorageAttachmentType:[],WallMaterialType:[],FoundationMaterialType:[],RoofMaterialType:[],ViewType:[],SiteFeatureType:[]};for(const b of a){if(!WA(b))continue;const j=b.insight,T=(E,R)=>{R&&v[E].push({token:R,photoId:b.photoId})},O=(E,R)=>{for(const G of R??[])v[E].push({token:G,photoId:b.photoId})};T("AttachmentType",j.attachmentType),T("StructuralDesignType",j.structuralDesignType),T("ConstructionMethodType",j.constructionMethodType),T("CarStorageAttachmentType",j.carStorageAttachmentType),O("WallMaterialType",j.wallMaterialTypes),O("FoundationMaterialType",j.foundationMaterialTypes),O("RoofMaterialType",j.roofMaterialTypes),O("ViewType",j.viewTypes),O("SiteFeatureType",j.siteFeatureTypes)}const S=Object.fromEntries(Object.entries(v).map(([b,j])=>[b,_b(j)])),N=new Map;for(const b of a){if(WA(b))continue;let j,T,O=null,E=null;if(b.roomName)j=`room:${b.floorName??""}::${b.roomName}`,T=b.floorName?`${b.floorName} — ${b.roomName}`:b.roomName,O=b.floorName,E=ND(b.roomName);else{const G=sk(b);if(!G||G==="Exterior")continue;j=`scene:${G}`,T=M4[G]??G,E=k4[G]??null}const R=N.get(j)??{photos:[],label:T,floorName:O,roomType:E};R.photos.push(b),N.set(j,R)}const x=[];for(const[b,j]of Array.from(N.entries())){const T=j.photos.map(C=>C.insight),O=KA(T.map(C=>C.updateStatusType)),E=O&&O!=="NotUpdated"?KA(T.map(C=>C.updatedTimeframeType)):null,R=KA(T.map(C=>C.roomConditionStatusType)),G=[];for(const C of T)C.comments&&G.push(C.comments),C.materials.length>0&&G.push(`Materials: ${C.materials.join(", ")}.`);const U=G.length>0?_4(G):null;!O&&!R&&!U||x.push({roomKey:b,roomLabel:j.label,floorName:j.floorName,roomType:j.roomType,photoIds:j.photos.map(C=>C.photoId),photoUrls:j.photos.map(C=>C.photoUrl),updateStatusType:O,updatedTimeframeType:E,roomConditionStatusType:R,comments:U})}const y=new Map;for(const b of a)for(const j of b.insight.defects){const T=`${j.area}\0${j.feature.toLowerCase()}\0${j.description.toLowerCase()}`,O=y.get(T);O?(O.photoIds.push(b.photoId),O.photoUrls.push(b.photoUrl)):y.set(T,{...j,photoIds:[b.photoId],photoUrls:[b.photoUrl]})}return{rooms:x,interiorQuality:c,interiorCondition:d,exteriorQuality:p,exteriorCondition:u,overallQuality:h,overallCondition:f,structural
2:S,defects:Array.from(y.values()),analyzedCount:a.length,errorCount:s}}function _4(t){const a=new Set,s=[];for(const r of t){const n=r.toLowerCase();a.has(n)||(a.add(n),s.push(r))}return s.join(" ").slice(0,2e3)}function U4(t,a){const s=/(\d+)\s*$/.exec(a.roomLabel.trim());if(s){const i=parseInt(s[1],10);if(Number.isFinite(i)&&i>=1)return i-1}const n=t.filter(i=>i.roomType===a.roomType).findIndex(i=>i.roomKey===a.roomKey);return n>=0?n:0}function V4(t,a,s,r={}){if(!a.roomType)return{buildings:t,applied:!1,skippedReason:"no-room-type"};const n=!!r.overwrite;let i=0,l=!1;const c=t.map(d=>l||d.improvementType!=="Dwelling"?d:{...d,units:d.units.map(p=>l?p:{...p,levels:p.levels.map(u=>l?u:{...u,rooms:u.rooms.map(m=>l||m.roomType!==a.roomType||i++!==s?m:(l=!0,$4(m,a,n)))})})});return l?{buildings:c,applied:!0,skippedReason:null}:{buildings:t,applied:!1,skippedReason:"no-matching-room"}}function $4(t,a,s){const r=(n,i)=>i!=null&&(s||n==null||n==="")?i:n??null;return{...t,updateStatusType:r(t.updateStatusType,a.updateStatusType),updatedTimeframeType:r(t.updatedTimeframeType,a.updatedTimeframeType),conditionStatusType:r(t.conditionStatusType,a.roomConditionStatusType),conditionAdditionalDescription:r(t.conditionAdditionalDescription,a.comments)}}function B4(t,a){let s=0;for(const r of t)if(r.improvementType==="Dwelling")for(const n of r.units)for(const i of n.levels)for(const l of i.rooms)l.roomType===a&&s++;return s}function z4(t,a){const s=Cu(t.area);return{section:t.area,...s??{},feature:t.feature,location:t.location??"",description:t.description,affectsSoundness:t.affectsSoundness,recommendedAction:t.recommendedAction??"",estimatedCost:null,photos:t.photoUrls.slice(0,a).map((r,n)=>({id:t.photoIds[n]??`photo-${n}`,src:r,caption:"AI photo analysis evidence"}))}}function q4(t){const a={},s=(r,n)=>{n.value&&(a[r]={value:n.value,photoIds:n.photoIds})};s("InteriorQualityRatingCode",t.interiorQuality),s("InteriorConditionRatingCode",t.interiorCondition),s("ExteriorQualityRatingCode",t.exteriorQuality),s("ExteriorConditionRatingCode",t.exteriorCondition);for(const[r,n]of Object.entries(t.structural??{}))s(r,n);return a}function Y4(t){let a=0;for(const s of[t.interiorQuality,t.interiorCondition,t.exteriorQuality,t.exteriorCondition,t.overallQuality,t.overallCondition])s.value&&a++;for(const s of Object.values(t.structural??{}))s.value&&a++;for(const s of t.rooms)s.updateStatusType&&a++,s.updatedTimeframeType&&a++,s.roomConditionStatusType&&a++,s.comments&&a++;return a+=t.defects.length,a}const G4="bg-emerald-100 text-emerald-700 border-emerald-200";function oS(){return e.jsx(kt,{variant:"outline",className:`text-[9px] px-1 py-0 ${G4}`,children:"Image"})}function QA({urls:t,idPrefix:a}){const s=Array.from(new Set(t)).slice(0,6);return s.length===0?null:e.jsx("span",{className:"inline-flex items-center gap-1 ml-1",children:s.map((r,n)=>e.jsx("a",{href:r,target:"_blank",rel:"noreferrer",className:"text-slate-400 hover:text-slate-600",title:`Evidence photo ${n+1}`,"data-testid":`link-${a}-photo-${n}`,children:e.jsx(rf,{className:"w-3 h-3 inline"})},r))})}function H4({orderId:t,photos:a,onSuggestions:s,readOnly:r}){const{toast:n}=hc(),i=ku(),l=[`/api/uad36/prefill/${t}
2`,"inspection-manifest"],c=[`/api/uad36/photo-analysis/${t}`],{data:d}=Vr({queryKey:l,queryFn:()=>Zn(`/api/uad36/prefill/${t}`),enabled:!!t,staleTime:3e4}),p=d?.sections??{},{data:u}=Vr({queryKey:c,queryFn:()=>Zn(`/api/uad36/photo-analysis/${t}`),enabled:!!t,staleTime:3e4}),[m,h]=o.useState(!1),[f,v]=o.useState(null),[S,N]=o.useState(null),[x,y]=o.useState(!0),[b,j]=o.useState(null),[T,O]=o.useState(new Set),E=S??u??null,R=o.useMemo(()=>E?.aggregate?E.aggregate:E?.photos&&E.photos.length>0?F4(E.photos):null,[E]),G=E?.narrative??null,U=o.useMemo(()=>(E?.photos??[]).filter(W=>W.analysisStatus==="analysis_failed"||W.status==="error"),[E]),C=o.useCallback(async W=>{if(!r){if(a.length===0){n({title:"No photos",description:"This order has no photos to analyze."});return}h(!0),v({done:0,total:a.length,fields:0});try{W&&await Zn(`/api/uad36/photo-analysis/${t}`,{method:"DELETE"});const me=5;let Z=[];for(let fe=0;fe<a.length;fe+=me){Z=Z.concat(a.slice(fe,fe+me));const ue=await Zn(`/api/uad36/photo-analysis/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({photos:Z,skipNarrative:!0})});N(ue),v({done:Math.min(Z.length,a.length),total:a.length,fields:ue.aggregate?Y4(ue.aggregate):0})}const pe=await Zn(`/api/uad36/photo-analysis/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({photos:a})});N(pe),await i.invalidateQueries({queryKey:c});const se=pe.aggregate;n({title:"Photo analysis complete",description:`${se?.analyzedCount??0} photos analyzed${se?.errorCount?`, ${se.errorCount} failed (fields stay Missing)`:""}.`})}catch(me){n({title:"Analysis failed",description:me instanceof Error?me.message:"Could not analyze photos.",variant:"destructive"})}finally{h(!1),v(null)}}},[t,a,i,n,r]),F=o.useCallback(async(W,me)=>{if(!r)try{const Z=await Zn(`/api/uad36/photo-analysis/${t}/scene`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({photoId:W,sceneOverride:me})});N(pe=>{const se=pe??u;return se?{...se,photos:se.photos.map(fe=>fe.photoId===W?Z.photo:fe),aggregate:null}:pe}),await i.invalidateQueries({queryKey:c})}catch(Z){n({title:"Could not save classification",description:Z instanceof Error?Z.message:"Save failed.",variant:"destructive"})}},[t,u,i,n,r]),A=o.useCallback(async W=>{r||(await Zn(`/api/uad36/section-attachments/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({patches:W})}),await i.invalidateQueries({queryKey:l}))},[t,i,r]),M=o.useCallback(async(W,me,Z)=>{if(!r){j(W);try{await Z(),O(pe=>new Set(pe).add(W)),n({title:"Suggestion applied",description:me})}catch(pe){n({title:"Save failed",description:pe instanceof Error?pe.message:"Could not save.",variant:"destructive"})}finally{j(null)}}},[n,r]),B=o.useCallback((W,me,Z,pe)=>M(W,`${pe} set to ${Z.value}.`,async()=>{await A([{section:"improvements",field:me,value:Z.value,source:"image"}])}),[M,A]),oe=o.useCallback((W,me,Z,pe)=>M(W,`${pe} set to ${Z.value}.`,async()=>{const se=E0(p),fe=se.findIndex(be=>be.improvementType!=="Outbuilding");if(fe<0)throw new Error("No dwelling exists in the Improvements structure yet — apply the structure from the fields list above first.");const ue=se.map((be,H)=>{if(H!==fe)return be;if(me.startsWith("exterior"))return{...be,[me]:Z.value};const ye=Array.isArray(be.units)?be.units:[];if(ye.length===0)throw new Error("The dwelling has no unit to hold an interior rating yet.");return{...be,units:ye.map((de,ge)=>ge===0?{...de,[me]:Z.value}:de)}});await A([{section:"improvements",field:"buildings",value:ue,source:"image"}])}),[M,A,p]),ae=o.useCallback(()=>M("narrative","Reconciliation narrative saved.",async()=>{const W=E0(p),me=W.findIndex(pe=>pe.improvementType!=="Outbuilding"&&Array.isArray(pe.units)&&pe.units.length>0);if(me<0)throw new Error("No dwelling unit exists in the Improvements structure yet — apply the structure from the fields list above first.");const Z=W.map((pe,se)=>se!==me?pe:{...pe,units:pe.units.map((fe,ue)=>{if(ue!==0)return fe;const be=(fe.unitValuationCommentText??"").trim(),H=be?`${be}
3
4${G}`:G;return{...fe,unitValuationCommentText:H}})});await A([{section:"improvements",field:"buildings",value:Z,source:"image"}])}),[M,A,p,G]),D=o.useCallback(W=>M(`room-${W.roomKey}`,`${W.roomLabel} updated.`,async()=>{const me=E0(p);if(!W.roomType)throw new Error("This room could not be matched to a report room type.");const Z=B4(me,W.roomType);if(Z===0)throw new Error("No matching room exists in the Improvements structure yet — apply the structure from the 3.6 Fields tab first.");const pe=Math.min(U4(R?.rooms??[],W),Z-1),se=V4(me,W,pe);if(!se.applied)throw new Error("Could not bind the suggestion to a report room.");await A([{section:"improvements",field:"buildings",value:se.buildings,source:"image"}])}),[M,A,p,R]),_=o.useCallback((W,me)=>M(`defect-${me}`,`Defect "${W.feature}" added.`,async()=>
4{if(!Cu(W.area))return;const Z=p?.defects?.items,pe=Array.isArray(Z?.value)?Z.value:Array.isArray(Z)?Z:[],se=z4(W,$U);await A([{section:"defects",field:"items",value:[...pe,se],source:"image"}])}),[M,A,p]),$=o.useMemo(()=>{if(!R)return[];const W=Z=>(pe,se,fe)=>B(pe,Z,se,fe),me=Z=>(pe,se,fe)=>oe(pe,Z,se,fe);return[{key:"overall-q",label:"Overall Quality",s:R.overallQuality,accept:W("QualityRatingType")},{key:"overall-c",label:"Overall Condition",s:R.overallCondition,accept:W("ConditionRatingType")},{key:"int-q",label:"Interior Quality",s:R.interiorQuality,accept:me("interiorQualityRatingCode")},{key:"int-c",label:"Interior Condition",s:R.interiorCondition,accept:me("interiorConditionRatingCode")},{key:"ext-q",label:"Exterior Quality",s:R.exteriorQuality,accept:me("exteriorQualityRatingCode")},{key:"ext-c",label:"Exterior Condition",s:R.exteriorCondition,accept:me("exteriorConditionRatingCode")}].filter(Z=>!!Z.s.value)},[R,B,oe]),z=o.useMemo(()=>{const W=new Map;for(const me of E?.photos??[])W.set(me.photoId,me.photoUrl);return W},[E]),V=o.useCallback(W=>W.map(me=>z.get(me)).filter(Boolean),[z]);o.useEffect(()=>{if(!s)return;if(!R){s({});return}const W=q4(R),me={};for(const[Z,pe]of Object.entries(W))me[Z]={...pe,photoUrls:V(pe.photoIds)};s(me)},[R,s,V]);const le=o.useMemo(()=>(E?.photos??[]).filter(W=>W.status==="ok"&&W.insight&&!W.roomName&&W.insight.kind!=="exterior"),[E]);return e.jsxs("div",{className:"rounded-lg border border-slate-200 bg-white","data-testid":"inspection-photo-analysis",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 text-left",onClick:()=>y(W=>!W),"data-testid":"button-toggle-photo-analysis",children:[x?e.jsx(Rr,{className:"w-3.5 h-3.5 text-slate-400"}):e.jsx(fo,{className:"w-3.5 h-3.5 text-slate-400"}),e.jsx(ul,{className:"w-3.5 h-3.5 text-emerald-600"}),e.jsx("span",{className:"text-xs font-semibold text-slate-700",children:"AI Photo Analysis"}),e.jsxs("span",{className:"text-[10px] text-slate-400",children:[a.length," photo",a.length===1?"":"s"," available"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[R&&e.jsxs(De,{size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px] text-slate-500",disabled:m||r,title:r?"Edit lock held by another user":void 0,onClick:()=>C(!0),"data-testid":"button-rerun-photo-analysis",children:[e.jsx(Kl,{className:"w-3 h-3 mr-1"}),"Re-run"]}),e.jsxs(De,{size:"sm",className:"h-6 px-2.5 text-[10px]",disabled:m||a.length===0||r,title:r?"Edit lock held by another user":void 0,onClick:()=>C(!1),"data-testid":"button-run-photo-analysis",children:[m?e.jsx(za,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(xg,{className:"w-3 h-3 mr-1"}
4),m?"Analyzing…":R?"Analyze new photos":"Analyze photos"]})]})]}),x&&e.jsxs("div",{className:"border-t border-slate-100 px-3 py-2 space-y-3",children:[m&&f&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-slate-600","data-testid":"text-photo-analysis-progress",children:[e.jsx(za,{className:"w-3 h-3 animate-spin text-emerald-600"}),e.jsxs("span",{children:[f.done," of ",f.total," photo",f.total===1?"":"s"," analyzed"," ","· ",f.fields," field suggestion",f.fields===1?"":"s"," so far"]})]}),!R&&!m&&e.jsx("p",{className:"text-[11px] text-slate-500","data-testid":"text-photo-analysis-empty",children:"Analyze the order's photos to get suggested room updates, quality/condition ratings, and observed defects. Suggestions are never applied automatically — you accept each one."}),R&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-[10px] text-slate-400","data-testid":"text-photo-analysis-status",children:[R.analyzedCount," photos analyzed",R.errorCount>0&&e.jsxs("span",{className:"text-amber-600",children:[" ","· ",R.errorCount," failed — imported evidence remains available"]})]}),U.length>0&&e.jsxs("div",{className:"rounded border border-red-200 bg-red-50 p-2.5 space-y-1.5",role:"status","aria-live":"polite","data-testid":"block-photo-analysis-failures",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold text-red-800",children:[e.jsx(Ns,{className:"w-3.5 h-3.5 shrink-0"}),U.length," photo",U.length===1?"":"s"," could not be analyzed"]}),e.jsx("p",{className:"text-[10px] text-red-700",children:"These photos are still present as imported inspection evidence. Re-run retries the existing stored assets; it does not repull the inspection from Banks."}),e.jsx("div",{className:"space-y-1",children:U.map(W=>e.jsxs("div",{className:"flex items-start gap-2 text-[10px] text-red-800","data-testid":`row-photo-analysis-failure-${W.photoId}`,children:[e.jsx("span",{className:"font-medium shrink-0",children:W.evidenceIdentity?.evidenceId||W.photoId}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"font-medium",children:[W.failureStage?W.failureStage.replace(/_/g," "):"analysis",":"]})," ",W.errorMessage||"The photo analysis did not produce a result."]})]},`${W.photoId}-${W.failureStage??"unknown"}`))})]}),le.length>0&&e.jsxs("div",{className:"space-y-1","data-testid":"block-photo-classifications",children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:"Photo Classifications"}),e.jsx("p",{className:"text-[10px] text-slate-400",children:"These photos have no inspection room label — confirm or correct the AI's scene guess so they group into the right room suggestions."}),le.map(W=>{const me=W.sceneOverride??W.insight?.sceneCategory??null,Z=!!W.sceneOverride;return e.jsxs("div",{className:"flex items-center gap-2 text-xs","data-testid":`row-scene-${W.photoId}`,children:[e.jsx("a",{href:W.photoUrl,target:"_blank",rel:"noreferrer",className:"shrink-0","data-testid":`link-scene-photo-${W.photoId}`,children:e.jsx("img",{src:W.photoUrl,alt:"Order photo",className:"w-9 h-9 rounded object-cover border border-slate-200",loading:"lazy"})}),e.jsx("span",{className:"text-[10px] text-slate-400 truncate flex-1 min-w-0",children:me?Z?"Confirmed":"AI guess — confirm or change":"Unclassified — pick a scene"}),e.jsxs(sr,{value:me??void 0,onValueChange:pe=>{r||F(W.photoId,pe)},children:[e.jsx(rr,{className:"h-6 w-36 text-[11px]","data-testid":`select-scene-${W.photoId}`,children:e.jsx(or,{placeholder:"Pick a scene…"})}),e.jsx(nr,{children:D4.map(pe=>e.jsx(vs,{value:pe,className:"text-xs",children:pe},pe))})]}),!Z&&me&&e.jsx(De,{size:"sm",variant:"outline",className:"h-5 px-2 text-[10px]",onClick:()=>F(W.photoId,me),disabled:r,title:r?"Edit lock held by another user":void 0,"data-testid":`button-confirm-scene-${W.photoId}`,children:"Confirm"}),Z&&e.jsx(Bs,{className:"w-3 h-3 text-emerald-600 shrink-0"})]},W.photoId)})]}),$.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:"Quality & Condition"}),$.map(W=>{const me=T.has(W.key);return e.jsxs("div",{className:"flex items-center gap-2 text-xs","data-testid":`row-rating-${W.key}`,children:[e.jsx("span",{className:"text-slate-600 w-36 shrink-0",children:W.label}),e.jsx("span",{className:"font-semibold text-slate-800",children:W.s.value}),e.jsx(oS,{}),e.jsx(QA,{urls:V(W.s.photoIds),idPrefix:`rating-${W.key}`}),e.jsx("span",{className:"flex-1"}),e.jsx(De,{size:"sm",variant:me?"ghost":"outline",className:"h-5 px-2 text-[10px]",disabled:me||b===W.key||r,title:r?"Edit lock held by another user":void 0,onClick:()=>W.accept(W.key,W.s,W.label),"data-testid":`button-accept-rating-${W.key}`,children:me?e.jsx(Bs,{className:"w-3 h-3 text-emerald-600"}):"Accept"})]},W.key)}),G&&e.jsxs("div",{className:"rounded border border-slate-100 bg-slate-50 p-2 mt-1","data-testid":"block-photo-narrative",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx("span",{className:"text-[10px] font-semibold text-slate-500",children:"Reconciliation narrative"}),e.jsx(oS,{}),e.jsx("span",{className:"flex-1"}),e.jsx(De,{size:"sm",variant:T.has("narrative")?"ghost":"outline",className:"h-5 px-2 text-[10px]",disabled:T.has("narrative")||b==="narrative"||r,title:r?"Edit lock held by another user":void 0,onClick:ae,"data-testid":"button-accept-narrative",children:T.has("narrative")?e.jsx(Bs,{className:"w-3 h-3 text-emerald-600"}):"Accept"})]}),e.jsx("p",{className:"text-[11px] text-slate-600 whitespace-pre-wrap",children:G})]})]}),R.rooms.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:"Rooms"}),R.rooms.map(W=>{const me=`room-${W.roomKey}`,Z=T.has(me);return e.jsxs("div",{className:"rounded border border-slate-100 p-2","data-testid":`row-room-${W.roomKey}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-slate-700",children:W.roomLabel}),e.jsx(oS,{}),e.jsx(QA,{urls:W.photoUrls,idPrefix:`room-${W.roomKey}`}),e.jsx("span",{className:"flex-1"}),e.jsx(De,{size:"sm",variant:Z?"ghost":"outline",className:"h-5 px-2 text-[10px]",disabled:Z||b===me||!W.roomType||r,title:r?"Edit lock held by another user":W.roomType?void 0:"No matching report room type",onClick:()=>D(W),"data-testid":`button-accept-room-${W.roomKey}`,children:Z?e.jsx(Bs,{className:"w-3 h-3 text-emerald-600"}):"Accept"})]}),e.jsxs("div",{className:"text-[10px] text-slate-500 mt-0.5 space-x-2",children:[W.updateStatusType&&e.jsxs("span",{children:["Update: ",W.updateStatusType]}),W.updatedTimeframeType&&e.jsxs("span",{children:["Timeframe: ",W.updatedTimeframeType]}),W.roomConditionStatusType&&e.jsxs("span",{children:["Condition: ",W.roomConditionStatusType]})]}),W.comments&&e.jsx("p",{className:"text-[10px] text-slate-500 mt-0.5",children:W.comments})]},W.roomKey)})]}),R.defects.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400 flex items-center gap-1",children:[e.jsx(Ns,{className:"w-3 h-3 text-amber-500"}),"Observed Defects"]}),R.defects.map((W,me)=>{const Z=`defect-${me}`,pe=T.has(Z);return e.jsxs("div",{className:"flex items-start gap-2 text-xs rounded border border-slate-100 p-2","data-testid":`row-defect-${me}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-slate-700",children:W.feature}),e.jsx("span",{className:"text-[9px] uppercase text-slate-400",children:W.area}),e.jsx(oS,{}),e.jsx(QA,{urls:W.photoUrls,idPrefix:`defect-${me}`})]}),e.jsx("p",{className:"text-[10px] text-slate-500 mt-0.5",children:W.description})]}),e.jsx(De,{size:"sm",variant:pe?"ghost":"outline",className:"h-5 px-2 text-[10px] shrink-0",disabled:pe||b===Z||r||!Cu(W.area),title:r?"Edit lock held by another user":Cu(W.area)?void 0:"Review this defect in the relevant building or unit editor so its structure can be selected.","aria-label":Cu(W.area)?void 0:`Review ${W.feature} defect in its building or unit editor`,onClick:()=>_(W,me),"data-testid":`button-accept-defect-${me}`,children:pe?e.jsx(Bs,{className:"w-3 h-3 text-emerald-600"}):Cu(W.area)?"Add defect":"Review in editor"})]},Z)})]})]})]})]})}function W4(t){const a={};for(const s of t)if(!(s.status!=="ok"||!s.insight))for(const r of s.insight.fields)a[r.name]||(a[r.name]={value:r.value,snippet:r.snippet,noteId:s.noteId,fileName:s.fileName??null});return a}function K4(t){const a=Cu(t.area);return{section:t.area,...a??{},feature:t.feature,location:t.location??"",description:t.description,affectsSoundness:t.affectsSoundness,recommendedAction:t.recommendedAction??"",estimatedCost:null,photos:[]}}const Q4="bg-rose-100 text-rose-700 border-rose-200";function Z4({orderId:t,onSuggestions:a,readOnly:s}){const{toast:r}=hc(),n=ku(),i=o.useRef(null),l=[`/api/uad36/voice-notes/${t}`],c=[`/api/uad36/prefill/${t}`,"inspection-manifest"],{data:d,isLoading:p}=Vr({queryKey:l,queryFn:()=>Zn(`/api/uad36/voice-notes/${t}`),enabled:!!t,staleTime:3e4}),u=o.useMemo(()=>d?.notes??[],[d?.notes]),{data:m}=Vr({queryKey:c,queryFn:()=>Zn(`/api/uad36/prefill/${t}`),enabled:!!t,staleTime:3e4}),h=m?.sections??{};o.useEffect(()=>{a?.(W4(u))},[u,a]);const[f,v]=o.useState({}),[S,N]=o.useState(!1),[x,y]=o.useState(null),[b,j]=o.useState(new Set),[T,O]=o.useState(null),E=o.useCallback(()=>n.invalidateQueries({queryKey:l}),[n]),R=o.useCallback(async F=>{if(!s){N(!0);try{const A=new FormData;A.append("audio",F);const M=await Zn(`/api/uad36/voice-notes/${t}`,{method:"POST",body:A});await E(),M.cached?r({title:"Already processed",description:"This recording was analyzed before — showing the saved result (no re-billing)."}):M.note?.status==="error"?r({title:"Processing failed",description:M.note.errorMessage||"The note could not be processed.",variant:"destructive"}):r({title:"Voice note processed",description:`${M.note?.insight?.fields.length??0} field suggestion(s) found.`})}catch(A){r({title:"Upload failed",description:A instanceof Error?A.message:"Could not upload the recording.",variant:"destructive"})}finally{N(!1),i.current&&(i.current.value="")}}},[t,E,r,s]),G=o.useCallback(async F=>{if(!s){y(F.noteId);try{await Zn(`/api/uad36/voice-notes/${t}/${F.noteId}/reprocess`,{method:"POST"}),await E(),r({title:"Note re-analyzed",description:"Suggestions were regenerated from the saved transcript."})}catch(A){r({title:"Re-run failed",description:A instanceof Error?A.message:"Could not re-analyze.",variant:"destructive"})}finally{y(null)}}},[t,E,r,s]),U=o.useCallback(async F=>{if(!s){y(F.noteId);try{await Zn(`/api/uad36/voice-notes/${t}/${F.noteId}`,{method:"DELETE"}),await E()}catch(A){r({title:"Delete failed",description:A instanceof Error?A.message:"Could not delete the note.",variant:"destructive"})}finally{y(null)}}},[t,E,r,s]),C=o.useCallback(async(F,A,M)=>{if(s||!Cu(A.area))return;const B=`${F.noteId}-${M}`;O(B);try{const oe=h?.defects?.items,ae=Array.isArray(oe?.value)?oe.value:Array.isArray(oe)?oe:[],D=K4(A);await Zn(`/api/uad36/section-attachments/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({patches:[{section:"defects",field:"items",value:[...ae,D],source:"voice"}]})}),await n.invalidateQueries({queryKey:c}),j(_=>
4new Set(_).add(B)),r({title:"Defect added",description:`"${A.feature}" was added to the report's defects.`})}catch(oe){r({title:"Save failed",description:oe instanceof Error?oe.message:"Could not save the defect.",variant:"destructive"})}finally{O(null)}},[t,h,n,r,s]);return e.jsxs("div",{className:"rounded-md border","data-testid":"inspection-voice-notes",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[e.jsx(UO,{className:"h-4 w-4 text-rose-600 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:"Voice notes"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Upload dictated inspection notes — mapped answers appear as Voice suggestions in the checklist below. Each recording is analyzed once."})]}),e.jsx("input",{ref:i,type:"file",accept:"audio/*,video/webm,video/mp4,.m4a,.mp3,.wav,.webm,.ogg",className:"hidden",onChange:F=>{const A=F.target.files?.[0];A&&R(A)},"data-testid":"input-voice-note-file"}),e.jsx(De,{size:"sm",variant:"outline",className:"h-7 text-xs",disabled:S||s,title:s?"Edit lock held by another user":void 0,onClick:()=>i.current?.click(),"data-testid":"button-upload-voice-note",children:S?e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"h-3.5 w-3.5 animate-spin mr-1"})," Processing…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zx,{className:"h-3.5 w-3.5 mr-1"})," Upload recording"]})})]}),p?e.jsxs("div",{className:"flex items-center gap-2 border-t px-3 py-2 text-xs text-muted-foreground","data-testid":"voice-notes-loading",children:[e.jsx(za,{className:"h-3.5 w-3.5 animate-spin"})," Loading voice notes…"]}):u.length>0?e.jsx("div",{className:"border-t divide-y",children:u.map(F=>{const A=f[F.noteId]??!1,M=x===F.noteId,B=F.insight?.fields.length??0,oe=F.insight?.observations.length??0,ae=F.insight?.defects??[];return e.jsxs("div",{"data-testid":`voice-note-${F.noteId}`,children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-xs",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 flex-1 min-w-0 text-left",onClick:()=>v(D=>({...D,[F.noteId]:!A})),"data-testid":`button-toggle-voice-note-${F.noteId}`,children:[A?e.jsx(Rr,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(fo,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:F.fileName||(F.source==="import"?"Imported transcript":"Voice recording")}),F.status==="error"?e.jsxs(kt,{variant:"outline",className:"text-[10px] bg-red-50 text-red-700 border-red-200 shrink-0",children:[e.jsx(Ns,{className:"h-3 w-3 mr-0.5"})," Failed"]}):e.jsxs(e.Fragment,{children:[e.jsxs(kt,{variant:"outline",className:`text-[10px] shrink-0 ${Q4}`,children:[B," field",B===1?"":"s"]}),oe>0&&e.jsxs("span",{className:"text-muted-foreground shrink-0",children:[oe," note",oe===1?"":"s"]}),ae.length>0&&e.jsxs(kt,{variant:"outline",className:"text-[10px] bg-amber-50 text-amber-700 border-amber-200 shrink-0",children:[ae.length," defect",ae.length===1?"":"s"]})]})]}),F.transcript&&e.jsx(De,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0",title:s?"Edit lock held by another user":"Re-run the field extraction on this transcript",disabled:M||s,onClick:()=>G(F),"data-testid":`button-reprocess-voice-note-${F.noteId}`,children:M?e.jsx(za,{className:"h-3 w-3 animate-spin"}):e.jsx(Kl,{className:"h-3 w-3"})}),e.jsx(De,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",title:s?"Edit lock held by another user":"Delete this voice note",disabled:M||s,onClick:()=>U(F),"data-testid":`button-delete-voice-note-${F.noteId}`,children:e.jsx(Ci,{className:"h-3 w-3"})})]}),A&&e.jsxs("div",{className:"border-t bg-muted/20 px-3 py-2 space-y-2 text-xs",children:[F.status==="error"&&e.jsxs("div",{className:"text-red-700","data-testid":`text-voice-error-${F.noteId}`,children:[F.errorMessage||"Processing failed.",F.transcript?" Use the re-run button to try again.":" Upload the recording again to retry."]}),F.transcript&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-0.5",children:"Transcript"}
4),e.jsx("div",{className:"whitespace-pre-wrap text-foreground/80 max-h-40 overflow-y-auto","data-testid":`text-transcript-${F.noteId}`,children:F.transcript})]}),B>0&&e.jsxs("div",{className:"text-muted-foreground",children:[B," mapped answer",B===1?"":"s"," — review and accept them on the matching rows in the checklist below (look for the ",e.jsx("span",{className:"text-rose-700 font-medium",children:"Voice"})," badge)."]}),oe>0&&e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-muted-foreground mb-0.5",children:"Other observations"}),e.jsx("ul",{className:"list-disc pl-4 space-y-0.5","data-testid":`list-observations-${F.noteId}`,children:F.insight.observations.map((D,_)=>e.jsx("li",{className:"text-foreground/80",children:D},_))})]}),ae.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"font-medium text-muted-foreground",children:"Defect mentions"}),ae.map((D,_)=>{const $=`${F.noteId}-${_}`,z=b.has($);return e.jsxs("div",{className:"flex items-start gap-2 rounded border bg-background px-2 py-1.5","data-testid":`voice-defect-${$}`,children:[e.jsx(Ns,{className:"h-3.5 w-3.5 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium",children:D.feature}),D.location?e.jsxs("span",{className:"text-muted-foreground",children:[" — ",D.location]}):null,e.jsx("div",{className:"text-foreground/80",children:D.description}),D.snippet&&e.jsxs("div",{className:"italic text-muted-foreground",children:["“",D.snippet,"”"]})]}),z?e.jsxs(kt,{variant:"outline",className:"text-[10px] bg-emerald-50 text-emerald-700 border-emerald-200 shrink-0",children:[e.jsx(Bs,{className:"h-3 w-3 mr-0.5"})," Added"]}):e.jsx(De,{size:"sm",variant:"outline",className:"h-6 px-2 text-[11px] shrink-0",disabled:T===$||s||!Cu(D.area),title:s?"Edit lock held by another user":Cu(D.area)?void 0:"Review this defect in the relevant building or unit editor so its structure can be selected.","aria-label":Cu(D.area)?void 0:`Review ${D.feature} defect in its building or unit editor`,onClick:()=>C(F,D,_),"data-testid":`button-accept-voice-defect-${$}`,children:T===$?e.jsx(za,{className:"h-3 w-3 animate-spin"}):Cu(D.area)?"Add defect":"Review in editor"})]},$)})]})]})]},F.noteId)})}):null]})}const J4={"roomCounts.bedrooms":"bedrooms","roomCounts.fullBaths":"fullBaths","roomCounts.halfBaths":"halfBaths","roomCounts.glaSqft":"gla","roomCounts.totalRooms":"totalRooms","roomCounts.stories":"stories","roomCounts.belowGradeArea":"basementArea","roomCounts.belowGradeFinished":"basementFinish","general.yearBuilt":"yearBuilt","general.effectiveAge":"effectiveAge","general.designStyle":"designStyle","foundation.type":"foundationWalls","exterior.walls":"exteriorWalls","exterior.roofSurface":"roofSurface","exterior.gutters":"guttersDownspouts","exterior.windowType":"windowType","heating.type":"heatingType","heating.fuel":"heatingFuel","cooling.type":"coolingType","interior.flooring":"interiorFloors","interior.walls":"interiorWalls","interior.trimFinish":"trimFinish","interior.bathFloor":"bathFloor","interior.bathWainscot":"bathWainscot","carStorage.garageType":"garageType","carStorage.garageCars":"garageCars","carStorage.drivewaySurface":"drivewaySurface","amenities.fireplaceCount":"fireplace","amenities.pool":"pool",grossLivingArea:"gla",grossLivingAreaSqft:"gla",grossLivingAreaSqFt:"gla",aboveGradeLivingArea:"gla",bedrooms:"bedrooms",fullBaths:"fullBaths",halfBaths:"halfBaths",yearBuilt:"yearBuilt"};function rk(t){return J4[t]||t}function X4(t,a,s){const r=rk(a),n=t[r];return!n||typeof n!="object"||!("value"in n)?t:{...t,[r]:{...n,value:String(s),source:"Inspection",isEdited:!0,alternatives:{...n.alternatives,inspection:String(s)}}}}const Ii="#072034",wl="#C5A572",El="#FAF9F7",Gr="#EDE8E4",ZA={roomCounts:"Room Counts",general:"General",foundation:"Foundation",exterior:"Exterior",heating:"Heating",cooling:"Cooling",interior:"Interior",carStorage:"Car Storage",amenities:"Amenities",appliances:"Appliances"},ez={sketch:"bg-blue-100 text-blue-700",photo:"bg-purple-100 text-purple-700",voice:"bg-pink-100 text-pink-700",propmix:"bg-cyan-100 text-cyan-700",mls:"bg-green-100 text-green-700",manual:"bg-slate-100 text-slate-700",lidar:"bg-indigo-100 text-indigo-700",inspection:"bg-[#F3EBDD] text-[#8B6F47]"};function tz({source:t}){if(!t)return null;const a=ez[t]||"bg-slate-100 text-slate-600";return e.jsx(kt,{className:`${a} text-[10px] px-1.5 py-0 font-medium border-0`,"data-testid":`badge-source-${t}`,children:t})}function mw({rating:t,type:a}){if(!t)return null;const s=a==="condition"?"Cond":"Qual";return e.jsxs(kt,{className:"bg-[#F3EBDD] text-[#8B6F47] text-[10px] px-1.5 py-0 font-medium border-0","data-testid":`badge-${a}-${t}`,children:[s,": ",t]})}function JA({orderId:t,onSend:a,readOnly:s}){return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-6 text-center","data-testid":"inspection-empty-state",children:[e.jsx("div",{className:"w-20 h-20 rounded-full bg-white border flex items-center justify-center mb-4",style:{borderColor:Gr}
4,children:e.jsx($O,{className:"w-10 h-10",style:{color:wl}})}),e.jsx("h3",{className:"text-sm font-semibold text-slate-700 mb-2",children:"No Inspection Data Yet"}),e.jsx("p",{className:"text-xs text-slate-500 max-w-[300px] mb-6",children:"Send order details to the Inspection App to pre-fill a job. Once the inspection is complete, data will appear here automatically."}),e.jsxs(De,{onClick:a,className:"text-white hover:opacity-90",style:{backgroundColor:Ii},disabled:s,title:s?"Edit lock held by another user":void 0,"data-testid":"button-send-empty",children:[e.jsx(gI,{className:"w-4 h-4 mr-2"}),"Send to Inspection App"]})]})}const lS=t=>t?.displayValue??(t?.value!=null?String(t.value):""),cS=t=>t?.value!=null?t.value:void 0;function hw(t){const a=t.map(s=>s?.origin).filter(Boolean);return a.length===0?null:a.every(s=>s===a[0])?a[0]:null}const az={Location:[{label:"Address",keys:["address","city","state","zip"],build:t=>{const a=lS(t.get("address")),s=lS(t.get("city")),r=lS(t.get("state")),n=lS(t.get("zip")),i=[s,[r,n].filter(Boolean).join(" ").trim()].filter(Boolean).join(", "),l=[a,i].filter(Boolean).join(", ");return l?{fieldKey:"combined-address",label:"Address",displayValue:l,origin:hw(["address","city","state","zip"].map(c=>t.get(c)).filter(Boolean)),combined:!0,keys:["address","city","state","zip"].filter(c=>t.has(c))}:null}}],Rooms:[{label:"Beds / Baths",keys:["bedrooms","fullBaths","halfBaths","bathrooms"],build:t=>{const a=cS(t.get("bedrooms")),s=cS(t.get("fullBaths")),r=cS(t.get("halfBaths")),n=cS(t.get("bathrooms")),i=[];a!=null&&i.push(`${a} bd`);const l=[s?`${s} full`:null,r?`${r} half`:null].filter(Boolean).join(", "),c=n??(Number(s)||0)+(Number(r)||0)*.5;return(l||n!=null)&&i.push(`${c} ba${l?` (${l})`:""}`),i.length===0?null:{fieldKey:"combined-beds-baths",label:"Beds / Baths",displayValue:i.join(" · "),origin:hw(["bedrooms","fullBaths","halfBaths","bathrooms"].map(d=>t.get(d)).filter(Boolean)),combined:!0,keys:["bedrooms","fullBaths","halfBaths","bathrooms"].filter(d=>t.has(d))}}}]};function sz(t,a){const s=new Map(a.map(i=>[i.fieldKey,i])),r=new Set,n=[];for(const i of az[t]||[]){const l=i.keys.filter(d=>s.has(d));if(l.length<2)continue;const c=i.build(s);c&&(n.push(c),l.forEach(d=>r.add(d)))}for(const i of a)r.has(i.fieldKey)||n.push({fieldKey:i.fieldKey,label:i.label||i.fieldKey,displayValue:i.displayValue||(i.value!=null?String(i.value):"—"),origin:i.origin,note:i.note,keys:[i.fieldKey]});return n}function rz({boxli:t,pipelineStatus:a,subjectBag:s,subjectBagState:r,onAcceptFields:n,accepting:i,readOnly:l}){const c=Array.isArray(t?.normalized?.fields)?t.normalized.fields:[],d=o.useMemo(()=>r==="ok"?r_(c,s):null,[r,c,s]),p=d?.accepted??0,u=r==="ok"&&p>0,h=u?(A=>{if(!A)return null;const M=new Date(A);return Number.isNaN(M.getTime())?null:M.toLocaleString()})(t?.mergedAt):null,f=o.useMemo(()=>{const A=new Map;for(const M of c){const B=M.group||"Other";A.has(B)||A.set(B,[]),A.get(B).push(M)}return A},[c]),v=["Location","Structure","Size","Measurements","Rooms","Condition","Other"],S=[...v.filter(A=>f.has(A)),...Array.from(f.keys()).filter(A=>!v.includes(A))],N=A=>A?new Date(A).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null,x=r==="ok",y=o.useMemo(()=>{const A=new Map;for(const M of c)A.set(M.fieldKey,M);return A},[c]),b=o.useCallback(A=>{const M=Kp[A],B=y.get(A)?.value;if(!M||B==null||String(B).trim()==="")return"reference";const oe=s[M],ae=!!oe&&!TI(oe.value);return ae&&oe.source==="boxli"&&yv(oe.value,B)?"accepted":ae&&!yv(oe.value,B)&&(oe.isEdited||oe.source==="User")?"conflict":"acceptable"},[y,s]),j=o.useCallback(A=>{const B=(A.keys&&A.keys.length?A.keys:[A.fieldKey]).filter($=>b($)!=="reference");if(B.length===0)return{actionable:!1};const oe=B.map(b),ae=oe.every($=>$==="accepted"),D=oe.some($=>$==="conflict"),_=B.filter($=>b($)!=="accepted");return{actionable:!0,mergeableKeys:B,allAccepted:ae,anyConflict:D,pending:_}},[b]),T=o.useMemo(()=>{if(!x)return[];const A=[];for(const M of c)b(M.fieldKey)==="acceptable"&&A.push({fieldKey:M.fieldKey,value:M.value});return A},[x,c,b]),O=o.useMemo(()=>
4{if(!x)return[];const A=[];for(const M of c){if(b(M.fieldKey)!=="conflict")continue;const B=Kp[M.fieldKey];A.push({fieldKey:M.fieldKey,value:M.value,label:M.label||M.fieldKey,scanDisplay:M.displayValue||(M.value!=null?String(M.value):""),currentValue:String(s[B]?.value??"")})}return A},[x,c,b,s]),E=T.length+O.length,R=o.useMemo(()=>c.some(A=>b(A.fieldKey)!=="reference"),[c,b]),[G,U]=o.useState(!1),C=A=>{const M=A?[...T,...O.map(B=>({fieldKey:B.fieldKey,value:B.value}))]:T;M.length!==0&&n(M,A?0:O.length)},F=()=>{!x||E===0||(O.length>0?U(!0):C(!1))};return e.jsxs("div",{className:"space-y-4 p-4","data-testid":"tab-data-content-boxli",children:[e.jsxs("div",{className:"bg-white border rounded-lg p-3 space-y-2",style:{borderColor:Gr},"data-testid":"boxli-summary",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",style:{color:Ii},children:[e.jsx(mc,{className:"w-4 h-4",style:{color:wl}}),e.jsx("span",{"data-testid":"text-boxli-captured",children:N(t?.normalized?.capturedAt)||N(t?.pulledAt)||"Date not set"})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx(kt,{className:"bg-blue-100 text-blue-700 border-0 text-[10px]","data-testid":"badge-boxli-source",children:"Boxli scan"}),e.jsx(kt,{className:"bg-[#F3EBDD] text-[#8B6F47] border-0 text-[10px]","data-testid":"badge-pipeline-status",children:a||"unknown"}),e.jsxs("span",{className:"text-xs text-slate-600","data-testid":"text-fields-count",children:[c.length," / ",n_.length," fields"]}),t?.pulledAt&&e.jsxs("span",{className:"text-[10px] text-slate-400","data-testid":"text-boxli-pulled",children:["Pulled ",new Date(t.pulledAt).toLocaleString()]}),u&&e.jsxs(kt,{className:"bg-green-100 text-green-700 border-0 text-[10px]","data-testid":"badge-boxli-merged",children:[e.jsx(kr,{className:"w-3 h-3 mr-1"}),p," of ",d.provided," fields merged"]}),h&&e.jsxs("span",{className:"text-[10px] text-slate-400","data-testid":"text-boxli-merged-at",children:["Merged ",h]})]}),x&&R&&e.jsxs(De,{size:"sm",className:"text-white hover:opacity-90 text-xs h-7 mt-1",style:{backgroundColor:Ii},onClick:F,disabled:i||E===0||l,"data-testid":"button-merge-to-order",title:l?"Edit lock held by another user":E===0?"Every scan value is already saved on the order.":"Copies every scan value into the order in one save. If any conflict with fields you edited by hand, you'll be asked first.",children:[i?e.jsx(za,{className:"w-3.5 h-3.5 mr-1.5 animate-spin"}):e.jsx(zO,{className:"w-3.5 h-3.5 mr-1.5"}),E===0?"Merged to order":"Merge to order"]})]}),c.length===0?e.jsxs("p",{className:"text-xs text-slate-400 flex items-center gap-1.5","data-testid":"text-boxli-no-fields",children:[e.jsx(qR,{className:"w-3.5 h-3.5"})," No data fields in this scan."]}):e.jsx("div",{className:"columns-1 md:columns-2 xl:columns-3 gap-3","data-testid":"boxli-groups-grid",children:S.map(A=>{const M=sz(A,f.get(A));return e.jsxs("div",{className:"bg-white border rounded-lg overflow-hidden mb-3 break-inside-avoid",style:{borderColor:Gr},"data-testid":`boxli-group-${A}`,children:[e.jsxs("div",{className:"px-3 py-2 flex items-center justify-between",style:{backgroundColor:El},children:[e.jsx("span",{className:"text-xs font-semibold text-slate-700",children:A}),e.jsxs("span",{className:"text-[10px] text-slate-400",children:[f.get(A).length," fields"]})]}),e.jsx("div",{className:"divide-y divide-slate-100",children:M.map(B=>{const oe=x?j(B):{actionable:!1},ae=oe.actionable&&oe.anyConflict&&B.keys&&B.keys.length===1?s[Kp[B.keys[0]]]?.value:void 0;return e.jsxs("div",{className:"px-3 py-1.5","data-testid":`boxli-field-${B.fieldKey}`,children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("span",{className:"text-[11px] font-medium text-slate-500",children:B.label}),B.origin&&e.jsx("span",{className:"text-[9px] text-slate-400 uppercase tracking-wide",children:B.origin})]}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-900 text-right truncate",title:B.displayValue,children:B.displayValue}),oe.actionable&&oe.allAccepted&&e.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 text-[10px] font-medium text-green-700","data-testid":`boxli-accepted-${B.fieldKey}`,children:[e.jsx(kr,{className:"w-3 h-3"})," In order"]}),oe.actionable&&!oe.allAccepted&&oe.anyConflict&&e.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 text-[10px] font-medium text-amber-700 uppercase tracking-wide",title:"You edited this field by hand and the scan disagrees — merging will ask whether to replace or keep your value.","data-testid":`boxli-conflict-${B.fieldKey}`,children:[e.jsx(Ns,{className:"w-3 h-3"})," Conflict"]})]})]}),ae!=null&&String(ae).trim()!==""&&e.jsxs("div",{className:"text-[10px] text-amber-700 mt-0.5 leading-tight","data-testid":`boxli-conflict-current-${B.fieldKey}`,children:["In order now: ",String(ae)]}),B.note&&e.jsx("div",{className:"text-[10px] text-slate-400 mt-0.5 leading-tight",children:B.note})]},B.fieldKey)})})]},A)})}),e.jsxs("div",{className:"bg-white border rounded-lg p-3",style:{borderColor:Gr},"data-testid":"boxli-notes-empty",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-slate-700",children:[e.jsx(qR,{className:"w-3.5 h-3.5 text-slate-400"}),"Inspector notes & voice transcripts"]}),e.jsx("p",{className:"text-[11px] text-slate-500 mt-1",children:"Boxli’s API doesn’t provide inspector notes or voice transcripts, so there are none to show here. Photo captions from the scan appear with each photo in the Photos tab."})]}),e.jsxs("p",{className:"text-[11px] text-slate-400",children:["Press ",e.jsx("span",{className:"font-medium text-slate-500",children:"Merge to order"})," to copy every scan value into the order’s subject data in one save. Fields that would overwrite something you typed are marked ",e.jsx("span",{className:"font-medium text-slate-500",children:"Conflict"})," — merging asks whether to replace or keep your values. To fetch a newer scan or fill fields the scan didn’t capture, use ",e.jsx("span",{className:"font-medium text-slate-500",children:"Pull from Boxli"}),"."]}),e.jsx(xi,{open:G,onOpenChange:A=>!A&&U(!1),children:e.jsxs(bi,{className:"max-w-md","data-testid":"dialog-merge-conflicts",children:[e.jsxs($i,{children:[e.jsx(si,{children:"Some fields conflict with your edits"}),e.jsxs(pl,{children:["You edited ",O.length," field",O.length===1?"":"s"," by hand and the scan disagrees. Replace them with the scan values (your edits are kept as alternatives), or keep your edits — every other field merges either way."]})]}),e.jsx("ul",{className:"space-y-1.5 max-h-[40vh] overflow-y-auto text-[13px]","data-testid":"list-merge-conflicts",children:O.map(A=>e.jsxs("li",{className:"flex items-baseline justify-between gap-3","data-testid":`merge-conflict-${A.fieldKey}`,children:[e.jsx("span",{className:"font-medium text-slate-700 shrink-0",children:A.label}),e.jsxs("span",{className:"text-slate-500 text-right min-w-0",children:["Scan: ",A.scanDisplay," · Yours: ",A.currentValue]})]},A.fieldKey))}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>U(!1),"data-testid":"button-merge-cancel",children:"Cancel"}),e.jsx(De,{variant:"outline",size:"sm",onClick:()=>{U(!1),C(!1)},"data-testid":"button-merge-keep-edits",children:"Keep my edits"}),e.jsx(De,{size:"sm",className:"text-white hover:opacity-90",style:{backgroundColor:Ii},onClick:()=>{U(!1),C(!0)},"data-testid":"button-merge-replace",children:"Replace with scan values"})]})]})})]})}function nz({inspectionData:t,onUseField:a,onUseFields:s,subjectBag:r,subjectBagState:n,onAcceptFields:i,accepting:l,readOnly:c}
4){const[d,p]=o.useState(new Set(Object.keys(ZA))),[u,m]=o.useState(new Set),h=t?.payload||t,f=h?.metadata||{},v=h?.rawData||{},S=h?.mappedFields||{},N=S?.fields||v?.extractedFields||{},x=v?.conditionQuality||{},y=v?.voiceTranscripts||[],b=v?.notes||[],j=Array.isArray(v?.dataAnswers)?v.dataAnswers:Object.entries(v?.dataFields||{}).map(([D,_])=>({stepId:D,question:D,value:String(_)})),T=D=>{p(_=>{const $=new Set(_);return $.has(D)?$.delete(D):$.add(D),$})},O=D=>D!=null&&String(D).trim()!=="",E=o.useMemo(()=>{const D=new Map;for(const _ of Object.keys(ZA)){const $=N[_];if(!$||typeof $!="object")continue;const z=[];for(const[V,le]of Object.entries($))O(le?.value)&&z.push({key:`${_}.${V}`,value:le.value});z.length>0&&D.set(_,z)}return D},[N]),R=o.useMemo(()=>j.filter(D=>O(D.value)).map(D=>({key:`inspectAnswer.${D.stepId}`,value:D.value})),[j]),G=o.useMemo(()=>{const D=[...R];for(const _ of Array.from(E.values()))D.push(..._);return D},[R,E]),U=o.useMemo(()=>{const D=new Map;for(const _ of G)D.set(_.key,_.value);return D},[G]),C=D=>m(_=>{const $=new Set(_);return $.has(D)?$.delete(D):$.add(D),$}),F=D=>m(_=>{const $=new Set(_);return D.length>0&&D.every(V=>$.has(V))?D.forEach(V=>$.delete(V)):D.forEach(V=>$.add(V)),$}),A=o.useMemo(()=>Array.from(u).filter(D=>U.has(D)).length,[u,U]),M=()=>{const D=Array.from(u).filter(_=>U.has(_)).map(_=>({fieldKey:_,value:U.get(_)}));D.length!==0&&(s(D),m(new Set))},B=({on:D})=>D?e.jsx(qO,{className:"w-3.5 h-3.5",style:{color:Ii}}):e.jsx(fI,{className:"w-3.5 h-3.5 text-slate-300"}),oe=o.useMemo(()=>{const D=[...y.map(_=>({..._,type:"voice"})),...b.map(_=>({..._,type:"text"}))];return D.sort((_,$)=>{const z=_.createdAt?new Date(_.createdAt).getTime():0;return($.createdAt?new Date($.createdAt).getTime():0)-z}),D},[y,b]);if(h?.boxli)return e.jsx(rz,{boxli:h.boxli,pipelineStatus:t?.pipelineStatus??null,subjectBag:r,subjectBagState:n,onAcceptFields:i,accepting:l,readOnly:c});if(h?.banksEvidence?.manifest)return e.jsx(iz,{evidence:h.banksEvidence,onUseField:a,capturedInspectionData:t,readOnly:c});const ae=G.length>0&&G.every(D=>u.has(D.key));return e.jsxs("div",{className:"space-y-3 p-4","data-testid":"tab-data-content",children:[e.jsxs("div",{className:"bg-white border rounded-lg px-3 py-2 flex items-center gap-3 flex-wrap",style:{borderColor:Gr},"data-testid":"inspection-summary",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-sm font-semibold",style:{color:Ii},children:[e.jsx(mc,{className:"w-4 h-4",style:{color:wl}}),e.jsx("span",{children:f.inspectionDate?new Date(f.inspectionDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Date not set"})]}),e.jsx(kt,{className:"bg-[#F3EBDD] text-[#8B6F47] border-0 text-[10px]","data-testid":"badge-pipeline-status",children:f.pipelineStatus||"unknown"}),e.jsxs("span",{className:"text-xs text-slate-600","data-testid":"text-fields-count",children:[S.fieldsFilled??"—"," / ",S.totalFields??"—"," fields"]}),f.formType&&e.jsxs(kt,{variant:"outline",className:"text-[10px]","data-testid":"badge-form-type",children:["Form ",f.formType]}),G.length>0&&e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsxs("button",{className:"flex items-center gap-1.5 text-xs text-slate-600 hover:text-slate-900 px-1.5 py-1 rounded hover:bg-[#FAF9F7] disabled:opacity-40 disabled:cursor-not-allowed",onClick:()=>!c&&F(G.map(D=>D.key)),disabled:c,"data-testid":"checkbox-select-all",children:[e.jsx(B,{on:ae}),"Select all fields"]}),e.jsxs(De,{size:"sm",className:"h-7 px-2.5 text-xs text-white hover:opacity-90",style:{backgroundColor:Ii},disabled:A===0||c,onClick:M,title:c?"Edit lock held by another user":void 0,"data-testid":"button-import-selected",children:[e.jsx(zO,{className:"w-3.5 h-3.5 mr-1.5"}),"Import selected into report",A>0?` (${A})`:""]})]})]}),j.length>0&&e.jsxs("div",{className:"bg-white border rounded-lg overflow-hidden",style:{borderColor:Gr},"data-testid":"homeowner-answers-section",children:[e.jsxs("div",{className:"px-3 py-1.5 flex items-center justify-between",style:{backgroundColor:El},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[R.length>0&&e.jsx("button",{className:"flex items-center p-0.5 rounded hover:bg-white/60 disabled:opacity-40 disabled:cursor-not-allowed",onClick:()=>!c&&F(R.map(D=>D.key)),disabled:c,title:"Select all homeowner answers","data-testid":"checkbox-select-all-answers",children:e.jsx(B,{on:R.every(D=>u.has(D.key))})}),e.jsx("span",{className:"text-xs font-semibold text-slate-700",children:"Homeowner Answers"})]}),e.jsxs("span",{className:"text-[10px] text-slate-400",children:[j.length," answer(s)"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-px bg-slate-100",children:j.map(D=>{const _=`inspectAnswer.${D.stepId}`,$=U.has(_);return e.jsxs("div",{className:"group flex items-center gap-2 bg-white px-2.5 py-1.5 hover:bg-[#FAF9F7]","data-testid":`answer-${D.stepId}
4`,children:[$?e.jsx("button",{className:"p-0.5 shrink-0 disabled:opacity-40 disabled:cursor-not-allowed",disabled:c,onClick:()=>!c&&C(_),"data-testid":`checkbox-answer-${D.stepId}`,children:e.jsx(B,{on:u.has(_)})}):e.jsx("span",{className:"w-[18px] shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[11px] font-medium text-slate-500 truncate",children:D.question}),e.jsx("div",{className:"text-xs font-semibold text-slate-900 truncate",children:D.value||"—"})]}),e.jsxs(De,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 shrink-0 text-[#072034] opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:bg-[#F3EBDD] disabled:opacity-30 disabled:cursor-not-allowed",onClick:()=>a(_,D.value),disabled:c,title:c?"Edit lock held by another user":"Import into report","data-testid":`button-import-answer-${D.stepId}`,children:[e.jsx(Zp,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"sr-only",children:"Import into report"})]})]},D.stepId)})})]}),Object.entries(ZA).map(([D,_])=>{const $=N[D];if(!$||typeof $!="object")return null;const z=Object.entries($);if(z.length===0)return null;const V=d.has(D),le=E.get(D)||[],W=le.length>0&&le.every(me=>u.has(me.key));return e.jsxs("div",{className:"bg-white border rounded-lg overflow-hidden",style:{borderColor:Gr},"data-testid":`category-${D}`,children:[e.jsxs("div",{className:"w-full flex items-center justify-between px-3 py-1.5",style:{backgroundColor:El},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[le.length>0&&e.jsx("button",{className:"flex items-center p-0.5 rounded hover:bg-white/60 disabled:opacity-40 disabled:cursor-not-allowed",onClick:()=>!c&&F(le.map(me=>me.key)),disabled:c,title:`Select all ${_} fields`,"data-testid":`checkbox-select-all-${D}`,children:e.jsx(B,{on:W})}),e.jsx("button",{onClick:()=>T(D),className:"text-xs font-semibold text-slate-700 hover:text-slate-900","data-testid":`button-toggle-${D}`,children:_})]}),e.jsxs("button",{onClick:()=>T(D),className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400",children:[z.length," fields"]}),V?e.jsx(Rr,{className:"w-3.5 h-3.5 text-slate-400"}):e.jsx(fo,{className:"w-3.5 h-3.5 text-slate-400"})]})]}),V&&e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-px bg-slate-100",children:z.map(([me,Z])=>{const pe=Z?.value,se=Z?.source,fe=Z?.allSources||[],ue=`${D}.${me}`,be=U.has(ue);return e.jsxs("div",{className:"group flex items-center gap-2 bg-white px-2.5 py-1.5 hover:bg-[#FAF9F7]","data-testid":`field-${D}-${me}`,children:[be?e.jsx("button",{className:"p-0.5 shrink-0 disabled:opacity-40 disabled:cursor-not-allowed",disabled:c,onClick:()=>!c&&C(ue),"data-testid":`checkbox-field-${D}-${me}`,children:e.jsx(B,{on:u.has(ue)})}):e.jsx("span",{className:"w-[18px] shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] font-medium text-slate-500 capitalize truncate",children:me.replace(/([A-Z])/g," $1").trim()}),e.jsx(tz,{source:se})]}),e.jsx("div",{className:"text-xs font-semibold text-slate-900 truncate",title:fe.length>1?fe.map(H=>`${H.source}: ${String(H.value)}`).join(" · "):void 0,children:pe!=null?String(pe):"—"}),fe.length>1&&e.jsx("div",{className:"text-[10px] text-slate-400 truncate",children:fe.map(H=>`${H.source}: ${String(H.value)}`).join(" · ")})]}),e.jsxs(De,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 shrink-0 text-[#072034] opacity-0 group-hover:opacity-100 focus-visible:opacity-100 hover:bg-[#F3EBDD] disabled:opacity-30 disabled:cursor-not-allowed",onClick:()=>a(ue,pe),disabled:c,title:c?"Edit lock held by another user":"Import into report","data-testid":`button-use-${D}-${me}`,children:[e.jsx(Zp,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"sr-only",children:"Import into report"})]})]},me)})})]},D)}),(x.conditionRating||x.qualityRating)&&e.jsxs("div",{className:"bg-white border rounded-lg p-3 space-y-3",style:{borderColor:Gr},"data-testid":"condition-quality-section",children:[e.jsxs("h4",{className:"text-xs font-semibold flex items-center gap-1.5",style:{color:Ii},children:[e.jsx(Lo,{className:"w-3.5 h-3.5",style:{color:wl}}),"Condition & Quality Ratings"]}),e.jsxs("div",{className:"flex gap-3",children:[x.conditionRating&&e.jsxs("div",{className:"flex-1 rounded-md p-2 border",style:{backgroundColor:El,borderColor:Gr},"data-testid":"condition-rating-card",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase tracking-wider",children:"Condition"}),e.jsx("div",{className:"text-lg font-bold",style:{color:Ii},children:x.conditionRating}),x.isUserOverride&&e.jsx(kt,{className:"bg-[#F3EBDD] text-[#8B6F47] border-0 text-[9px] mt-1",children:"Override"})]}),x.qualityRating&&e.jsxs("div",{className:"flex-1 rounded-md p-2 border",style:{backgroundColor:El,borderColor:Gr},"data-testid":"quality-rating-card",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase tracking-wider",children:"Quality"}),e.jsx("div",{className:"text-lg font-bold",style:{color:Ii},children:x.qualityRating})]})]}),x.conditionEvidence?.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-medium text-slate-500 mb-1",children:"Condition Evidence"}),e.jsx("ul",{className:"space-y-1",children:x.conditionEvidence.map((D,_)=>e.jsxs("li",{className:"text-xs text-slate-600 flex items-start gap-1.5",children:[e.jsx(kr,{className:"w-3 h-3 mt-0.5 shrink-0",style:{color:wl}}),D]},_))})]}),x.qualityEvidence?.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] font-medium text-slate-500 mb-1",children:"Quality Evidence"}),e.jsx("ul",{className:"space-y-1",children:x.qualityEvidence.map((D,_)=>e.jsxs("li",{className:"text-xs text-slate-600 flex items-start gap-1.5",children:[e.jsx(kr,{className:"w-3 h-3 mt-0.5 shrink-0",style:{color:wl}}),D]},_))})]}),x.narrative&&e.jsxs("div",{className:"rounded-md p-2 border",style:{backgroundColor:El,borderColor:Gr},children:[e.jsx("div",{className:"text-[10px] font-medium text-slate-500 mb-1",children:"Narrative"}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:x.narrative})]})]}),oe.length>0&&e.jsxs("div",{className:"space-y-2","data-testid":"notes-section",children:[e.jsxs("h4",{className:"text-xs font-semibold text-slate-700 flex items-center gap-1.5",children:[oe.some(D=>D.type==="voice")?e.jsx(UO,{className:"w-3.5 h-3.5"}):e.jsx(S5,{className:"w-3.5 h-3.5"}),"Notes & Transcripts"]}),oe.map((D,_)=>e.jsxs("div",{className:"bg-white border rounded-lg p-2.5",style:{borderColor:Gr},"data-testid":`note-${D.id||_}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[D.type==="voice"?e.jsx(kt,{className:"bg-pink-100 text-pink-700 border-0 text-[9px]",children:"Voice"}):e.jsx(kt,{className:"bg-slate-100 text-slate-600 border-0 text-[9px]",children:"Note"}),D.createdAt&&e.jsx("span",{className:"text-[10px] text-slate-400",children:new Date(D.createdAt).toLocaleStr
4ing("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})})]}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:D.content})]},D.id||_))]})]})}function iz({evidence:t,onUseField:a,capturedInspectionData:s,readOnly:r}){const n=[...Array.isArray(t.categories?.data)?t.categories.data:[],...Array.isArray(t.categories?.uad36)?t.categories.uad36:[]],i=n.filter(l=>{const c=l.raw?.conflict??l.raw?.conflicts??l.conflict;return c===!0||Array.isArray(c)&&c.length>0});return e.jsxs("div",{className:"space-y-3 p-4","data-testid":"tab-data-content-banks-evidence",children:[e.jsxs("div",{className:"bg-white border rounded-lg p-3",style:{borderColor:Gr},children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold",style:{color:Ii},children:[e.jsx(Jx,{className:"w-3.5 h-3.5",style:{color:wl}}),"Banks Inspection mapped data",e.jsxs(kt,{className:"ml-auto bg-blue-100 text-blue-700 border-0 text-[10px]",children:[n.length," evidence field",n.length===1?"":"s"]})]}),e.jsx("p",{className:"text-[11px] text-slate-500 mt-1",children:"Values below retain their source, provenance, and package evidence ID. Existing Insight review and mapping rules remain authoritative."})]}),i.length>0&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800","data-testid":"banks-evidence-conflicts",children:[i.length," conflict",i.length===1?"":"s"," reported by the inspection package."]}),n.length===0?e.jsx("div",{className:"text-xs text-slate-500 py-8 text-center","data-testid":"banks-evidence-no-data",children:"No mapped data fields were included in this package."}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2",children:n.map((l,c)=>{const d=l.value,p=String(l.fieldKey||l.id||`field-${c}`),u=l.provenance,m=typeof u=="string"?u:u&&typeof u=="object"?String(u.source??u.provider??""):"";return e.jsxs("div",{className:"bg-white border rounded-md p-2.5",style:{borderColor:Gr},"data-testid":`banks-evidence-field-${c}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] font-medium text-slate-500 truncate",children:l.label||p}),l.source&&e.jsx(kt,{variant:"outline",className:"text-[9px]",children:String(l.source)})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-900 truncate flex-1",children:d==null?"—":String(d)}),d!=null&&e.jsxs(De,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-[#072034]",disabled:r,onClick:()=>a(rk(p),d,s),title:r?"Edit lock held by another user":"Import into report",children:[e.jsx(Zp,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"sr-only",children:"Import into report"})]})]}),(m||l.id)&&e.jsxs("div",{className:"text-[10px] text-slate-400 mt-1 truncate",children:[m||"Banks Inspection"," · evidence ",String(l.id)]}),i.includes(l)&&e.jsx("div",{className:"text-[10px] text-amber-700 mt-1",children:"Conflict reported by source"})]},`${l.id??p}-${c}`)})})]})}function oz({inspectionData:t}){const a=t?.payload?.banksEvidence?.manifest;if(!a)return null;const s=a.status==="complete"?"bg-green-100 text-green-700":a.status==="partial"?"bg-amber-100 text-amber-700":"bg-red-100 text-red-700";return e.jsxs("div",{className:"mx-4 mt-3 rounded-lg border bg-white px-3 py-2.5",style:{borderColor:Gr},"data-testid":"banks-evidence-summary",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Jx,{className:"w-4 h-4",style:{color:wl}}),e.jsx("span",{className:"text-xs font-semibold",style:{color:Ii},children:"Banks Inspection Evidence"}),e.jsx(kt,{className:`text-[10px] border-0 ${s}`,children:a.status}),e.jsxs("span",{className:"text-[10px] text-slate-500",children:[a.itemCount," evidence item",a.itemCount===1?"":"s"," · ",a.assetCount," asset",a.assetCount===1?"":"s"]}),a.retrievedAssetCount!=null&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:[a.retrievedAssetCount," retrieved",a.failedAssetCount?` · ${a.failedAssetCount} failed`:""]})]}),e.jsxs("div",{className:"flex gap-x-4 gap-y-1 flex-wrap mt-1 text-[10px] text-slate-500",children:[e.jsxs("span",{children:["Schema: ",e.jsx("strong",{children:a.schema||"—"})]}),e.jsxs("span",{children:["Revision: ",e.jsx("strong",{children:a.revisionId||"—"})]}),e.jsxs("span",{children:["Inspection: ",e.jsx("strong",{children:a.inspectionId||"—"})]}),e.jsxs("span",{children:["Version: ",e.jsx("strong",{children:a.packageVersion??"—"})]}),a.contentHash&&e.jsxs("span",{children:["Hash: ",e.jsx("strong",{children:typeof a.contentHash=="string"?a.contentHash:"provided"})]})]})]})}function Ub({inspectionData:t,destination:a,title:s,emptyText:r}){const n=t?.payload?.banksEvidence?.categories?.[a]??[];return e.jsx("div",{className:"space-y-3 p-4","data-testid":`tab-${a}-content`,children:n.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6 text-center",children:[a==="video"?e.jsx(BO,{className:"w-10 h-10 text-slate-300 mb-2"}):e.jsx(gn,{className:"w-10 h-10 text-slate-300 mb-2"}),e.jsx("p",{className:"text-sm font-medium text-slate-600",children:r}),e.jsxs("p",{className:"text-xs text-slate-400 mt-1",children:["This package did n
4ot include any ",s.toLowerCase(),"."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-xs font-semibold",style:{color:Ii},children:[s," ",e.jsxs("span",{className:"text-slate-400 font-normal",children:["(",n.length,")"]})]}),n.map((i,l)=>e.jsxs("div",{className:"bg-white border rounded-lg p-3",style:{borderColor:Gr},"data-testid":`${a}-evidence-${l}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(kt,{className:"bg-slate-100 text-slate-600 border-0 text-[9px]",children:i.type||a}),i.source&&e.jsx("span",{className:"text-[10px] text-slate-400",children:String(i.source)}),i.retrievalStatus==="failed"&&e.jsx(kt,{className:"bg-red-100 text-red-700 border-0 text-[9px]",children:"Retrieval failed"})]}),i.assetUrl&&a==="video"&&e.jsx("video",{controls:!0,className:"w-full max-h-80 rounded bg-black",src:i.assetUrl}),i.assetUrl&&a==="audio"&&e.jsx("audio",{controls:!0,className:"w-full",src:i.assetUrl}),i.value!=null&&e.jsx("p",{className:"text-xs text-slate-700 whitespace-pre-wrap",children:typeof i.value=="string"?i.value:JSON.stringify(i.value,null,2)}),i.provenance&&e.jsxs("p",{className:"text-[10px] text-slate-400 mt-2",children:["Provenance: ",typeof i.provenance=="string"?i.provenance:JSON.stringify(i.provenance)]})]},`${i.id??l}-${l}`))]})})}function lz({inspectionData:t}){const a=t?.payload?.banksEvidence?.manifest,s=a?.items??[];return e.jsxs("div",{className:"space-y-3 p-4","data-testid":"tab-evidence-details-content",children:[e.jsxs("div",{className:"bg-white border rounded-lg p-3 text-xs",style:{borderColor:Gr},children:[e.jsx("div",{className:"font-semibold",style:{color:Ii},children:"Import details"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-1 mt-2 text-slate-600",children:[e.jsxs("span",{children:["Schema: ",a?.schema||"—"]}),e.jsxs("span",{children:["Package version: ",a?.packageVersion??"—"]}),e.jsxs("span",{children:["Inspection ID: ",a?.inspectionId||"—"]}),e.jsxs("span",{children:["Revision ID: ",a?.revisionId||"—"]}),e.jsxs("span",{children:["Source: ",a?.source||"Banks Inspection"]}),e.jsxs("span",{children:["Content hash: ",a?.contentHash?typeof a.contentHash=="string"?a.contentHash:"provided":"—"]})]})]}),e.jsx("div",{className:"space-y-2",children:s.map((r,n)=>e.jsxs("div",{className:"bg-white border rounded-lg px-3 py-2 text-xs",style:{borderColor:Gr},"data-testid":`evidence-detail-item-${n}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-slate-700",children:r.id}),e.jsx(kt,{variant:"outline",className:"text-[9px]",children:r.type}),e.jsx("span",{className:"text-[10px] text-slate-400",children:r.destination}),e.jsx(kt,{className:`ml-auto border-0 text-[9px] ${r.retrievalStatus==="failed"?"bg-red-100 text-red-700":r.retrievalStatus==="unsupported"?"bg-amber-100 text-amber-700":"bg-green-100 text-green-700"}`,children:r.retrievalStatus})]}),r.source&&e.jsxs("div",{className:"text-[10px] text-slate-500 mt-1",children:["Source: ",String(r.source)]}),r.retrievals?.map((i,l)=>e.jsxs("div",{className:"text-[10px] text-slate-400 mt-1",children:["Asset ",l+1,": ",i.status,i.failureReason?` — ${i.failureReason}`:"",i.contentHash?" · hash checked":""]},l))]},`${r.id??n}-${n}`))})]})}function cz({inspectionData:t}){const a=t?.payload||t,s=a?.rawData||{},r=e_(a),n=s?.mlsPhotos||[],[i,l]=o.useState(()=>{const S=new Set;return[...r,...n].forEach(N=>{N.photos?.forEach(x=>{x.selected&&S.add(x.id)})}),S}),c=o.useMemo(()=>{const S=[];return[...r,...n].forEach(N=>{N.photos?.forEach(x=>S.push(x.id))}),S},[r,n]),d=c.length,p=i.size,u=S=>{l(N=>{const x=new Set(N);return x.has(S)?x.delete(S):x.add(S),x})},m=()=>l(new Set(c)),h=()=>l(new Set),f=({photo:S,alt:N})=>{const[x,y]=o.useState(()=>!S.url),[b,j]=o.useState(0);return x?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-1.5 bg-slate-100 px-2 text-center","data-testid":`photo-error-${S.id}`,children:[e.jsx(Di,{className:"w-5 h-5 text-amber-600"}),e.jsx("span",{className:"text-[10px] leading-tight text-slate-600",children:"Photo unavailable. Your session or this inspection asset may have expired."}),e.jsx("button",{type:"button",className:"text-[10px] font-medium text-[#072034] underline",onClick:()=>{y(!1),j(T=>T+1)},children:"Retry"})]}):e.jsx("img",{src:S.url,alt:N,className:"w-full h-full object-cover",loading:"lazy",onError:()=>y(!0)},b)},v=(S,N,x=!1)=>e.jsxs("div",{className:"space-y-2","data-testid":`photo-group-${S.title||N}`,children:[e.jsxs("h4",{className:"text-xs font-semibold text-slate-700 flex items-center gap-1.5",children:[x?e.jsx(Wh,{className:"w-3.5 h-3.5 text-green-500"}):e.jsx(xg,{className:"w-3.5 h-3.5",style:{color:wl}}),S.title||`Group ${N+1}`,x&&e.jsx(kt,{className:"bg-green-100 text-green-700 border-0 text-[9px] ml-1",children:"MLS"}),e.jsxs("span",{className:"text-[10px] text-slate-400 ml-auto",children:[S.photos?.length||0," photos"]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 ga
4p-2",children:S.photos?.map((y,b)=>{const j=i.has(y.id);return e.jsxs("div",{className:"relative rounded-lg overflow-hidden border-2 transition-colors",style:{borderColor:j?wl:Gr},"data-testid":`photo-card-${y.id||b}`,children:[e.jsxs("div",{className:"aspect-square bg-slate-100 relative",children:[e.jsx(f,{photo:y,alt:y.caption||""}),e.jsxs("div",{className:"absolute top-1.5 right-1.5 flex gap-1",children:[y.condition&&e.jsx(mw,{rating:y.condition,type:"condition"}),y.quality&&e.jsx(mw,{rating:y.quality,type:"quality"})]}),y.category&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsx(kt,{className:"bg-black/60 text-white border-0 text-[9px]",children:y.category})})]}),e.jsxs("div",{className:"p-2 bg-white",children:[y.caption&&e.jsx("p",{className:"text-[10px] text-slate-600 leading-tight line-clamp-2 mb-1.5",children:y.caption}),y.features?.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mb-1.5",children:[y.features.slice(0,3).map((T,O)=>e.jsx("span",{className:"text-[9px] bg-slate-100 text-slate-500 px-1 py-0.5 rounded",children:T},O)),y.features.length>3&&e.jsxs("span",{className:"text-[9px] text-slate-400",children:["+",y.features.length-3]})]}),e.jsxs("button",{onClick:()=>u(y.id),className:`w-full flex items-center justify-center gap-1.5 py-1 rounded text-[10px] font-medium transition-colors ${j?"bg-[#F3EBDD] text-[#8B6F47] hover:bg-[#EDE2CC]":"bg-slate-50 text-slate-500 hover:bg-slate-100"}`,"data-testid":`toggle-select-${y.id||b}`,children:[j?e.jsx(qO,{className:"w-3 h-3"}):e.jsx(fI,{className:"w-3 h-3"}),j?"Selected for Report":"Select for Report"]})]})]},y.id||b)})})]},`${x?"mls":"insp"}-${N}`);return d===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6 text-center","data-testid":"photos-empty",children:[e.jsx(xg,{className:"w-12 h-12 text-slate-300 mb-3"}),e.jsx("p",{className:"text-sm font-medium text-slate-600",children:"No Photos Available"}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:"Photos will appear here after the inspection is completed."})]}):e.jsxs("div",{className:"space-y-4 p-4","data-testid":"tab-photos-content",children:[e.jsxs("div",{className:"flex items-center justify-between bg-white border rounded-lg px-3 py-2",style:{borderColor:Gr},children:[e.jsxs("span",{className:"text-xs font-medium",style:{color:Ii},"data-testid":"text-photo-count",children:[p," selected of ",d," total"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(De,{variant:"outline",size:"sm",className:"text-[10px] h-6 px-2",onClick:m,"data-testid":"button-select-all",children:"Select All"}),e.jsx(De,{variant:"outline",size:"sm",className:"text-[10px] h-6 px-2",onClick:h,"data-testid":"button-deselect-all",children:"Deselect All"})]})]}),r.map((S,N)=>v(S,N,!1)),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t pt-3",style:{borderColor:Gr},children:e.jsxs("h3",{className:"text-xs font-bold text-slate-600 uppercase tracking-wider mb-2 flex items-center gap-1.5",children:[e.jsx(Wh,{className:"w-3.5 h-3.5 text-green-500"}),"MLS Photos"]})}),n.map((S,N)=>v(S,N,!0))]})]})}function dz({inspectionData:t}){const a=t_(t?.payload||t),s=a?.rawData||{},r=s?.sketch||{},n=a_(s),i=n?{...s.glaCalculations,gla:n.gla,levels:n.levels}:s?.glaCalculations||r,l=!!(r.url||i.gla!=null||n?.levels.length),c=a?.boxli?.normalized?.sketch??null,d=!!(c?.floorplan&&Array.isArray(c.floorplan.walls)&&c.floorplan.walls.length>0),p=Array.isArray(a?.banksEvidence?.categories?.sketch)?a.banksEvidence.categories.sketch:[];if(!l&&p.length>0)return e.jsx("div",{className:"space-y-3 p-4","data-testid":"tab-sketch-content-banks-evidence",children:p.map((m,h)=>e.jsxs("div",{className:"bg-white border rounded-lg p-3",style:{borderColor:Gr},children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold text-slate-700",children:[e.jsx(m0,{className:"w-3.5 h-3.5",style:{color:wl}}),m.label||m.type||"Sketch evidence",m.source&&e.jsx(kt,{variant:"outline",className:"text-[9px]",children:String(m.source)}),m.retrievalStatus==="failed"&&e.jsx(kt,{className:"bg-red-100 text-red-700 border-0 text-[9px]",children:"Retrieval failed"})]}),m.assetUrl&&sx(m)==="image"&&e.jsx("img",{src:m.assetUrl,alt:m.label||"Inspection sketch",className:"mt-2 w-full rounded"}),m.assetUrl&&sx(m)==="document"&&e.jsx("iframe",{src:m.assetUrl,title:m.label||"Inspection sketch",className:"mt-2 w-full h-[60vh] border rounded-md bg-white",style:{borderColor:Gr}}),m.assetUrl&&sx(m)==="unsupported"&&e.jsx("div",{className:"mt-2 rounded bg-amber-50 border border-amber-200 px-3 py-4 text-center text-xs text-amber-800","data-testid":`sketch-unsupported-${m.id??h}`,children:"This sketch asset uses an unsupported media type."}),m.value!=null&&e.jsx("pre",{className:"mt-2 whitespace-pre-wrap text-xs text-slate-600",children:typeof m.value=="string"?m.value:JSON.stringify(m.value,null,2)}),m.provenance&&e.jsxs("div",{className:"mt-2 text-[10px] text-slate-400",children:["Provenance: ",typeof m.provenance=="string"?m.provenance:JSON.stringify(m.provenance)]})]},`${m.id??h}-${h}`))});if(!l&&(d||c?.reportPdfUrl))return e.jsxs("div",{className:"space-y-3 p-4","data-testid":"tab-sketch-content-boxli",children:[d&&e.jsx(s_,{floorplan:c.floorplan}),c.reportPdfUrl&&e.jsxs("div",{className:"space-y-1.5",children:[d&&e.jsx("p",{className:"text-xs text-slate-500",children:"Boxli PDF report"}),e.jsx("iframe",{src:c.reportPdfUrl,title:"Boxli sketch",className:"w-full h-[60vh] border rounded-md bg-white",style:{borderColor:Gr},"data-testid":"iframe-boxli-sketch"})]})]});if(!l)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6 text-center","data-testid":"sketch-empty",children:[e.jsx(m0,{className:"w-12 h-12 text-slate-300 mb-3"}),e.jsx("p",{className:"text-sm font-medium text-slate-600",children:"No Sketch Data"}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:"Floor plan and GLA data will appear here after the inspection."})]});const u=[{label:"Gross Living Area (GLA)",value:i.gla,unit:"sq ft"},{label:"Total Building Sq Ft",value:i.totalSqft,unit:"sq ft"},{label:"Basement Total",value:i.basementSqft,unit:"sq ft"},{label:"Basement Finished",value:i.basementFinishedSqft,unit:"sq ft"},{label:"Basement Unfinished",value:i.basementUnfinishedSqft,unit:"sq ft"},{label:"Garage",value:i.garageSqft,unit:"sq ft"},{label:"Porch",value:i.porchSqft,unit:"sq ft"},{label:"Patio",value:i.patioSqft,unit:"sq ft"}].filter(m=>m.value!==null&&m.value!==void 0);return e.jsxs("div",{className:"space-y-4 p-4","data-testid":"tab-sketch-content",children:[r.url&&sx(r)==="image"&&e.jsxs("div",{className:"bg-white border rounded-lg overflow-hidden",style:{borderColor:Gr},"data-testid":"sketch-image-container",children:[e.jsx("div",{className:"px-3 py-2 border-b",style:{backgroundColor:El,borderColor:Gr},children:e.jsxs("h4",{className:"text-xs font-semibold flex items-center gap-1.5",style:{color:Ii},children:[e.jsx(m0,{className:"w-3.5 h-3.5",style:{color:wl}}),"Floor Plan"]})}),e.jsx("div",{className:"bg-white p-2",children:e.jsx("img",{src:r.url,alt:"Floor Plan",className:"w-full rounded","data-testid":"sketch-image"})})]}),r.url&&sx(r)==="document"&&e.jsxs("div",{className:"bg-white border rounded-lg overflow-hidden",style:{borderColor:Gr},"data-testid":"sketch-document-container",children:[e.jsx("div",{className:"px-3 py-2 border-b",style:{backgroundColor:El,borderColor:Gr},children:e.jsxs("h4",{className:"text-xs font-semibold flex items-center gap-1.5",style:{color:Ii},children:[e.jsx(m0,{className:"w-3.5 h-3.5",style:{color:wl}}),"Floor Plan Document"]})}
4),e.jsx("iframe",{src:r.url,title:"Floor Plan Document",className:"w-full h-[60vh] bg-white","data-testid":"sketch-document"})]}),r.url&&sx(r)==="unsupported"&&e.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-4 text-center text-xs text-amber-800","data-testid":"sketch-unsupported",children:"This sketch asset uses an unsupported media type and cannot be previewed."}),u.length>0&&e.jsxs("div",{className:"bg-white border rounded-lg overflow-hidden",style:{borderColor:Gr},"data-testid":"gla-breakdown-table",children:[e.jsx("div",{className:"px-3 py-2 border-b",style:{backgroundColor:El,borderColor:Gr},children:e.jsxs("h4",{className:"text-xs font-semibold text-slate-700 flex items-center gap-1.5",children:[e.jsx(Um,{className:"w-3.5 h-3.5"}),"GLA Breakdown"]})}),e.jsx("div",{className:"divide-y divide-slate-100",children:u.map((m,h)=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2",style:h===0?{backgroundColor:El}:void 0,"data-testid":`gla-row-${h}`,children:[e.jsx("span",{className:`text-xs ${h===0?"font-bold":"text-slate-600"}`,style:h===0?{color:Ii}:void 0,children:m.label}),e.jsxs("span",{className:"text-xs font-semibold",style:{color:h===0?Ii:void 0},children:[m.value?.toLocaleString()," ",m.unit]})]},h))})]}),n&&!n.reconciles&&e.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800","data-testid":"levels-reconciliation-warning",children:"Banks per-level areas do not reconcile to the reported total GLA. The total GLA remains authoritative and no conflicting geometry value was substituted."}),i.levels?.length>0&&e.jsxs("div",{className:"bg-white border rounded-lg overflow-hidden",style:{borderColor:Gr},"data-testid":"levels-breakdown",children:[e.jsx("div",{className:"px-3 py-2 border-b",style:{backgroundColor:El,borderColor:Gr},children:e.jsxs("h4",{className:"text-xs font-semibold text-slate-700 flex items-center gap-1.5",children:[e.jsx(VO,{className:"w-3.5 h-3.5"}),n&&!n.reconciles?"Per-Level Source Areas":"Per-Level Breakdown"]})}),e.jsx("div",{className:"divide-y divide-slate-100",children:i.levels.map((m,h)=>e.jsxs("div",{className:"px-3 py-2","data-testid":`level-row-${h}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-slate-700",children:m.name||m.label||`Level ${h+1}`}),e.jsxs("span",{className:"text-xs font-semibold text-slate-800",children:[m.areaSqft!=null?Number(m.areaSqft).toLocaleString():m.squareFootage!=null?String(m.squareFootage):m.sqft!=null?Number(m.sqft).toLocaleString():m.area!=null?Number(m.area).toLocaleString():"—"," ","sq ft"]})]}),m.geometryConflict&&e.jsx("p",{className:"mt-1 text-[10px] text-amber-700",children:"Geometry reports a different area; canonical Banks GLA remains authoritative."})]},h))})]}),e.jsxs("div",{className:"bg-white border rounded-lg p-3",style:{borderColor:Gr},"data-testid":"room-counts-summary",children:[e.jsxs("h4",{className:"text-xs font-semibold mb-2 flex items-center gap-1.5",style:{color:Ii},children:[e.jsx(Fo,{className:"w-3.5 h-3.5",style:{color:wl}}),"Room Counts"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[{icon:hv,label:"Bedrooms",value:r.bedrooms??i.bedrooms},{icon:H0,label:"Bathrooms",value:r.bathrooms??i.bathrooms},{icon:_O,label:"Total Rooms",value:r.totalRooms??i.totalRooms},{icon:Hh,label:"Stories",value:r.stories??i.stories}].filter(m=>m.value!==null&&m.value!==void 0).map((m,h)=>e.jsxs("div",{className:"rounded-md p-2 border flex items-center gap-2",style:{backgroundColor:El,borderColor:Gr},"data-testid":`room-count-${m.label.toLowerCase()}`,children:[e.jsx(m.icon,{className:"w-4 h-4",style:{color:wl}}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-500",children:m.label}),e.jsx("div",{className:"text-sm font-bold text-slate-800",children:m.value})]})]},h))})]}),i.glaCalculationSteps?.length>0&&e.jsxs("div",{className:"bg-white border rounded-lg overflow-hidden",style:{borderColor:Gr},"data-testid":"gla-calc-steps",children:[e.jsx("div",{className:"px-3 py-2 border-b",style:{backgroundColor:El,borderColor:Gr},children:e.jsx("h4",{className:"text-xs font-semibold text-slate-700",children:"Calculation Steps"})}),e.jsx("div",{className:"p-3 space-y-1",children:i.glaCalculationSteps.map((m,h)=>e.jsxs("div",{className:"text-xs text-slate-600 flex items-start gap-1.5",children:[e.jsxs("span",{className:"font-bold shrink-0",style:{color:wl},children:[h+1,"."]}
4),e.jsx("span",{children:typeof m=="string"?m:m.description||m.label||JSON.stringify(m)})]},h))})]})]})}function uz({open:t,onOpenChange:a,inspectionData:s,orderId:r,onUseField:n,onRefresh:i,lastPushedToInspection:l,onBoxliFieldsMerged:c,verifyFieldSelections:d,onVerifyFieldEdit:p,readOnly:u}){const[m,h]=o.useState(!1),[f,v]=o.useState(null),[S,N]=o.useState(!1),[x,y]=o.useState(null),[b,j]=o.useState(!1),[T,O]=o.useState("inspection"),[E,R]=o.useState(null),[G,U]=o.useState("provider"),C=o.useRef(!1);o.useEffect(()=>{t&&(O("inspection"),R(null),C.current=!1)},[t]);const[F,A]=o.useState({}),[M,B]=o.useState("loading"),[oe,ae]=o.useState({}),[D,_]=o.useState(!1),[$,z]=o.useState({}),[V,le]=o.useState({}),{toast:W}=hc(),me=ku(),[Z,pe]=o.useState(!1),{data:se}=Vr({queryKey:["/api/integrations/banks-inspection/config"],queryFn:()=>Zn("/api/integrations/banks-inspection/config"),enabled:t,staleTime:5*6e4}),fe=se?.enabled===!0,{data:ue}=Vr({queryKey:[`/api/integrations/banks-inspection/orders/${r}/evidence`],queryFn:()=>Zn(`/api/integrations/banks-inspection/orders/${encodeURIComponent(r)}/evidence`),enabled:t&&!!r,retry:!1,staleTime:3e4}),be=ue?.payload?.banksEvidence?ue:s,H=o.useRef(new Set);o.useEffect(()=>{if(u||!t||!r||!s)return;const At=s?.payload||s,Fe=Array.isArray(At?.rawData?.voiceTranscripts)?At.rawData.voiceTranscripts:[];Fe.length!==0&&(async()=>{let Oe=!1;for(let rt=0;rt<Fe.length;rt++){const $t=Fe[rt],na=String($t?.transcript??$t?.transcription??$t?.text??"").trim();if(!na)continue;const zt=`${r}:${na.slice(0,200)}`;if(!H.current.has(zt)){H.current.add(zt);try{await Zn(`/api/uad36/voice-notes/${r}/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({transcript:na,fileName:$t?.title||$t?.label||`Imported voice note ${rt+1}`})}),Oe=!0}catch{H.current.delete(zt)}}}Oe&&me.invalidateQueries({queryKey:[`/api/uad36/voice-notes/${r}`]})})()},[t,r,s,me,u]),o.useEffect(()=>{if(!t||T!=="inspection"||!r)return;let At=!1;return B(Fe=>Fe==="ok"?Fe:"loading"),(async()=>{try{const Fe=await Zn(`/api/v2/orders/${r}/progress`);if(At)return;const Oe=Array.isArray(Fe?.progress)?Fe.progress:[],$t=(Oe.find(na=>na.stepKey==="subject_site")||Oe.find(na=>na.stepKey==="subject_property"))?.stepData??{};ae($t),A(XS($t.propertyData??{})),B("ok")}catch{At||B(Fe=>Fe==="ok"?Fe:"unavailable")}})(),()=>{At=!0}},[t,T,r]);const ye=o.useCallback(At=>{u||(A(Fe=>XS({...Fe,...At})),c?.(At))},[u,c]),de=o.useCallback(()=>{O("inspection"),i(),C.current&&(R("report-fields"),C.current=!1)},[i]),ge=o.useCallback(()=>{C.current=!0,i()},[i]),Be=o.useCallback(async()=>{if(!r)return;const At=s?.payload?.boxli?.normalized?.floors??[];await R3(r,At,me)==="applied"&&W({title:"Structure applied to report",description:"Scanned levels, rooms, and bed/bath counts were copied into the report's Improvements model."})},[r,s,me,W]),He=o.useCallback(()=>{Be()},[Be]),Ie=o.useCallback(At=>{if(At.length!==0){for(const Fe of At)n(Fe.fieldKey,Fe.value);W({title:"Imported into report",description:`${At.length} field${At.length===1?"":"s"} copied from the inspection.`})}},[n,W]),ce=o.useCallback(async(At,Fe=0)=>{if(u||M!=="ok"||!r)return;const Oe=At.filter(rt=>Kp[rt.fieldKey]&&rt.value!=null&&String(rt.value).trim()!=="");if(Oe.length!==0){_(!0);try{let rt={...F};for(const zt of Oe){const Ua=Kp[zt.fieldKey],Ce=rt[Ua],St={...Ce?.alternatives??{}};Ce&&!TI(Ce.value)&&Ce.source&&Ce.source!=="boxli"&&(St[Ce.source]=Ce.value),St.boxli=zt.value,rt[Ua]={value:String(zt.value),source:"boxli",isEdited:!1,alternatives:St}}rt=XS(rt),await Lh(r,{saveProgress:{stepKey:"subject_site",stepData:{...oe,propertyData:rt},isCompleted:!1}});const $t={};for(const[zt,Ua]of Object.entries(rt))Ua!==F[zt]&&($t[zt]=Ua);A(rt),ae(zt=>({...zt,propertyData:rt})),Object.keys($t).length>0&&c?.($t);const na=s?.payload?.boxli?.importId;na&&Zn(`/api/integrations/boxli/orders/${r}/versions/${na}/merged`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:"{}"}).catch(()=>{}),W({title:"Merged to order",description:`${Oe.length} field(s) merged from the Boxli scan.`+(Fe>0?` ${Fe} field(s) you edited by hand kept your values.`:"")}),await Be()}catch(rt){W({title:"Save failed",description:rt instanceof Error?rt.message:"Could not save.",variant:"destructive"})}finally{_(!1)}}},[M,F,oe,r,s,c,W,Be]),Pe=o.useMemo(()=>be?.payload?.banksEvidence?.categories?.uad36??be?.payload?.boxli?.normalized?.fields??[],[be]),We=o.useMemo(()=>be?.payload?.boxli?.normalized?.floors??[],[be]),Re=o.useMemo(()=>{const At=[],Fe=new Set,Oe=be?.payload||be,rt=Oe?.banksEvidence?.manifest,$t=new Map((rt?.items??[]).map(St=>[String(St.id),St])),na=St=>{!St.photoUrl||Fe.has(St.photoUrl)||(Fe.add(St.photoUrl),At.push(St))},zt=be?.payload?.boxli?.normalized?.photos??[];
4for(const St of zt)St?.sourceUrl&&na({photoId:String(St.uuid??St.sourceUrl),photoUrl:String(St.sourceUrl),roomName:St.roomName??null,floorName:St.floorName??null,source:"boxli"});const Ua=Oe?.rawData||{},Ce=[{list:Ua?.photos??[],source:"manual"},{list:Ua?.mlsPhotos??[],source:"mls"}];for(const St of Ce)for(const vt of St.list)for(const Ve of vt?.photos??[])Ve?.url&&na({photoId:String(Ve.id??Ve.url),photoUrl:String(Ve.url),roomName:null,floorName:null,source:Ve.source?String(Ve.source):St.source,evidenceId:Ve.evidenceId?String(Ve.evidenceId):null,revisionId:rt?.revisionId!=null?String(rt.revisionId):null,contentHash:$t.get(String(Ve.evidenceId??Ve.id))?.contentHash??null,sourceClassification:$t.get(String(Ve.evidenceId??Ve.id))?.source?String($t.get(String(Ve.evidenceId??Ve.id)).source):rt?.source?String(rt.source):null});return At},[be]),ne=x||l||null,Me=!!be,lt=!!be?.payload?.banksEvidence?.manifest,{data:Tt}=Vr({queryKey:[`/api/uad36/photo-analysis/${r}`],queryFn:()=>Zn(`/api/uad36/photo-analysis/${r}`),enabled:t&&!!r,staleTime:3e4}),{data:je}=Vr({queryKey:[`/api/uad36/voice-notes/${r}`],queryFn:()=>Zn(`/api/uad36/voice-notes/${r}`),enabled:t&&!!r,staleTime:3e4}),Le=o.useMemo(()=>{const At=new Set((Tt?.photos??[]).map(Fe=>String(Fe.photoId)));return Re.filter(Fe=>!At.has(String(Fe.photoId))).length},[Tt,Re]),ut=o.useMemo(()=>{const At=s?.payload||s,Fe=Array.isArray(At?.rawData?.voiceTranscripts)?At.rawData.voiceTranscripts.filter(rt=>String(rt?.transcript??rt?.transcription??rt?.text??"").trim()!==""):[];if(Fe.length===0)return 0;const Oe=(je?.notes??[]).filter(rt=>rt.source==="import").length;return Math.max(0,Fe.length-Oe)},[s,je]),[st,Xt]=o.useState(!1);o.useEffect(()=>{Xt(!1)},[r]);const ua=o.useRef(null),Oa=!st&&(Le>0||ut>0),Xa=[Le>0?`${Le} photo${Le===1?"":"s"}`:null,ut>0?`${ut} voice note${ut===1?"":"s"}`:null].filter(Boolean).join(" and "),qa=At=>{const Fe=new Date(At);return Fe.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})+" at "+Fe.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})},os=o.useCallback(async()=>{if(!u){h(!0),v(null),N(!1),j(!1);try{const At=await Zn(`/api/v2/orders/${r}`,{method:"PATCH",body:JSON.stringify({pushToInspection:!0}),headers:{"Content-Type":"application/json"}});At.pushedAt&&y(At.pushedAt),N(!0),setTimeout(()=>N(!1),3e3)}catch(At){v(At.message||"Failed to send data")}finally{h(!1)}}},[r,u]),ya=o.useCallback(()=>{u||(ne?j(!0):os())},[u,ne,os]);return e.jsx(xi,{open:t,onOpenChange:a,children:e.jsxs(bi,{className:"w-[90vw] max-w-[1400px] h-[90vh] p-0 flex flex-col overflow-hidden","data-testid":"inspection-panel",hideClose:!0,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 shrink-0",style:{backgroundColor:El},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[T==="review"&&e.jsxs("button",{onClick:de,className:"rounded-full p-1.5 hover:bg-gray-100 transition-colors","data-testid":"button-back-to-inspection",title:"Back to inspection",children:[e.jsx(fo,{className:"h-4 w-4 rotate-180"}),e.jsx("span",{className:"sr-only",children:"Back to inspection"})]}),e.jsx(si,{className:"text-sm font-semibold text-gray-700",children:T==="review"?"Inspection Review":"Inspection"})]}),e.jsx(pl,{className:"sr-only",children:"Two-way sync with Banks Inspection App"}),e.jsx(lL,{asChild:!0,children:e.jsxs("button",{className:"rounded-full p-1.5 hover:bg-gray-100 transition-colors","data-testid":"btn-close-inspection-modal",children:[e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})})]}),T==="review"&&!u?e.jsx("div",{className:"flex-1 overflow-y-auto",style:{backgroundColor:El},"data-testid":"inspection-review-view",children:e.jsx(X2,{orderId:r,embedded:!0,onBack:de,onFieldsMerged:ye,onDataChanged:ge,onMergedToOrder:He,onReviewSuggestions:de})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-4 py-2.5 border-b shrink-0 bg-white",style:{borderColor:Gr},children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(De,{size:"sm",className:"text-xs h-7 text-white hover:opacity-90",style:{backgroundColor:Ii},onClick:ya,disabled:m||u,title:u?"Edit lock held by another user":void 0,"data-testid":"button-send-to-inspection",children:[m?e.jsx(za,{className:"w-3.5 h-3.5 mr-1.5 animate-spin"}):e.jsx(gI,{className:"w-3.5 h-3.5 mr-1.5"}),"Send to Inspection App"]}),e.jsxs("div",{className:"flex items-center gap-0.5 rounded-md border px-1 py-0.5",style:{borderColor:Gr,backgroundColor:El},"data-testid":"group-import-sync",children:[e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wider text-slate-400 px-1.5 select-none",children:"Import / Sync"}),e.jsxs(De,{variant:"ghost",size:"sm",className:"text-xs h-6 px-2 text-[#072034] hover:bg-[#F3EBDD]",onClick:i,"data-testid":"button-refresh-inspection",children:[e.jsx(Kl,{className:"w-3.5 h-3.5 mr-1"}),"Refresh"]}),e.jsxs(De,{variant:"ghost",size:"sm",className:"text-xs h-6 px-2 text-[#072034] hover:bg-[#F3EBDD] disabled:opacity-50",onClick:()=>O("review"),disabled:u,title:u?"Edit lock held by another user":void 0,"data-testid":"button-open-boxli-review",children:[e.jsx(VO,{className:"w-3.5 h-3.5 mr-1"}),"Pull from Boxli"]}),e.jsx("span",{title:u?"Edit lock held by another user":fe?void 0:"Connection not configured",children:e.jsxs(De,{variant:"ghost",size:"sm",className:"text-xs h-6 px-2 text-[#072034] hover:bg-[#F3EBDD] disabled:opacity-50",onClick:()=>pe(!0),disabled:!fe||u,"data-testid":"button-open-banks-pull",children:[e.jsx(uN,{className:"w-3.5 h-3.5 mr-1"}),"Pull from Banks Inspection"]})}),!fe&&e.jsx("span",{className:"text-[10px] text-slate-400 pr-1.5 select-none","data-testid":"text-banks-not-configured",children:"Connection not configured"})]}),S&&e.jsxs(kt,{className:"bg-green-100 text-green-700 border-0 text-[10px]","data-testid":"badge-push-success",children:[e.jsx(Bs,{className:"w-3 h-3 mr-1"})," Sent!"]}),ne&&!S&&e.jsxs("span",{className:"text-[10px] text-slate-400","data-testid":"text-last-pushed-inspection",children:["Last sent ",qa(ne)]})]}),b&&e.jsxs("div",{className:"flex items-center gap-2 rounded border px-2.5 py-1.5 mt-2 text-xs",style:{backgroundColor:El,borderColor:wl,color:Ii},"data-testid":"inspection-push-confirm",children:[e.jsxs("span",{children:["Already sent ",qa(ne),". Send again?"]}),e.jsx(De,{size:"sm",className:"h-5 px-2 text-[10px] text-white hover:opacity-90",style:{backgroundColor:Ii},onClick:os,"data-testid":"button-confirm-resend-inspection",children:"Send"}),e.jsx(De,{size:"sm",variant:"ghost",className:"h-5 px-2 text-[10px] text-slate-500 hover:text-slate-700",onClick:()=>j(!1),"data-testid":"button-cancel-resend-inspection",children:"Cancel"})]}),f&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-red-600 mt-2","data-testid":"text-push-error",children:[e.jsx(Di,{className:"w-3.5 h-3.5"}),f]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",style:{backgroundColor:El},children:[e.jsx(oz,{inspectionData:be}),e.jsxs(up,{value:E??(Me?"data":"report-fields"),onValueChange:R,className:"w-full",children:[e.jsx("div",{className:"px-4 pt-3",children:e.jsxs(pp,{"data-testid":"inspection-tabs",children:[e.jsxs($n,{value:"data",className:"text-xs gap-1.5","data-testid":"tab-trigger-data",children:[e.jsx(Jx,{className:"w-3.5 h-3.5"}),"Data"]}),e.jsxs($n,{value:"photos",className:"text-xs gap-1.5","data-testid":"tab-trigger-photos",children:[e.jsx(xg,{className:"w-3.5 h-3.5"}),"Photos"]}),e.jsxs($n,{value:"sketch",className:"text-xs gap-1.5","data-testid":"tab-trigger-sketch",children:[e.jsx(m0,{className:"w-3.5 h-3.5"}),"Sketch"]}),e.jsxs($n,{value:"report-fields",className:"text-xs gap-1.5","data-testid":"tab-trigger-report-fields",children:[e.jsx($O,{className:"w-3.5 h-3.5"}),"3.6 Fields"]}),lt&&e.jsxs(e.Fragment,{children:[e.jsxs($n,{value:"video",className:"text-xs gap-1.5","data-testid":"tab-trigger-video",children:[e.jsx(BO,{className:"w-3.5 h-3.5"}),"Videos"]}),e.jsxs($n,{value:"notes",className:"text-xs gap-1.5","data-testid":"tab-trigger-notes",children:[e.jsx(gn,{className:"w-3.5 h-3.5"}),"Notes"]}),e.jsxs($n,{value:"evidence-details",className:"text-xs gap-1.5","data-testid":"tab-trigger-evidence-details",children:[e.jsx(Jx,{className:"w-3.5 h-3.5"}),"Import details"]}
4)]})]})}),e.jsxs("div",{className:"w-full",children:[e.jsx(Bd,{value:"data",className:"m-0",children:Me?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"inline-flex rounded-md border overflow-hidden",style:{borderColor:Gr},"data-testid":"data-view-toggle",children:[e.jsx("button",{type:"button",className:`px-2.5 py-1 text-[11px] font-medium ${G==="provider"?"text-white":"text-slate-600 bg-white hover:bg-slate-50"}`,style:G==="provider"?{backgroundColor:Ii}:void 0,onClick:()=>U("provider"),"data-testid":"button-data-view-provider",children:"Provider view"}),e.jsx("button",{type:"button",className:`px-2.5 py-1 text-[11px] font-medium border-l ${G==="grid"?"text-white":"text-slate-600 bg-white hover:bg-slate-50"}`,style:{borderColor:Gr,...G==="grid"?{backgroundColor:Ii}:{}},onClick:()=>U("grid"),"data-testid":"button-data-view-grid",children:"Grid Preview"})]}),G==="grid"?e.jsx(L4,{scanFields:Pe,bag:F,bagState:M,fieldSelections:d??{},onFieldEdit:p}):e.jsx(nz,{inspectionData:be,onUseField:n,onUseFields:Ie,subjectBag:F,subjectBagState:M,onAcceptFields:ce,accepting:D,readOnly:u})]}):e.jsx(JA,{orderId:r,onSend:ya,readOnly:u})}),e.jsx(Bd,{value:"photos",className:"m-0",children:Me?e.jsx(cz,{inspectionData:be}):e.jsx(JA,{orderId:r,onSend:ya,readOnly:u})}),e.jsx(Bd,{value:"sketch",className:"m-0",children:Me?e.jsx(dz,{inspectionData:be}):e.jsx(JA,{orderId:r,onSend:ya,readOnly:u})}),e.jsxs(Bd,{value:"report-fields",className:"m-0 p-3 space-y-3",children:[Oa&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2",style:{backgroundColor:"#F3EBDD",borderColor:wl},"data-testid":"banner-analysis-nudge",children:[e.jsx(xg,{className:"w-4 h-4 shrink-0",style:{color:Ii}}),e.jsxs("div",{className:"flex-1 text-xs",style:{color:Ii},"data-testid":"text-analysis-nudge",children:[Xa," from this order ",Le+ut===1?"hasn't":"haven't"," been analyzed yet — run the analysis to get 3.6 field suggestions below."]}),e.jsx(De,{size:"sm",variant:"outline",className:"h-6 px-2 text-[11px] border-[#C5A572] text-[#072034] hover:bg-white shrink-0",onClick:()=>ua.current?.scrollIntoView({behavior:"smooth",block:"start"}),"data-testid":"button-nudge-analyze",children:"Go to Analyze photos"}),e.jsxs("button",{className:"rounded p-0.5 hover:bg-white/60 shrink-0",onClick:()=>Xt(!0),title:"Dismiss","data-testid":"button-dismiss-analysis-nudge",children:[e.jsx(ur,{className:"w-3.5 h-3.5 text-slate-500"}),e.jsx("span",{className:"sr-only",children:"Dismiss"})]})]}),e.jsx("div",{ref:ua,children:e.jsx(H4,{orderId:r,photos:Re,onSuggestions:z,readOnly:u})}),e.jsx(Z4,{orderId:r,onSuggestions:le,readOnly:u}),e.jsx(T3,{orderId:r,boxliFields:Pe,floors:We,subjectBag:F,bagReady:M==="ok",onAcceptBagFields:ce,imageSuggestions:$,voiceSuggestions:V,readOnly:u})]}),lt&&e.jsxs(e.Fragment,{children:[e.jsx(Bd,{value:"video",className:"m-0",children:e.jsx(Ub,{inspectionData:be,destination:"video",title:"Inspection videos",emptyText:"No Videos Available"})}),e.jsx(Bd,{value:"notes",className:"m-0",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ub,{inspectionData:be,destination:"notes",title:"Inspection notes",emptyText:"No Notes Available"}),e.jsx(Ub,{inspectionData:be,destination:"transcript",title:"Transcripts",emptyText:"No Transcripts Available"}),e.jsx(Ub,{inspectionData:be,destination:"coverage",title:"Coverage records",emptyText:"No Coverage Records Available"}),e.jsx(Ub,{inspectionData:be,destination:"audio",title:"Voice notes and audio",emptyText:"No Audio Available"})]})}),e.jsx(Bd,{value:"evidence-details",className:"m-0",children:e.jsx(lz,{inspectionData:be})})]})]})]})]})]}),e.jsx(H$,{open:Z,onOpenChange:pe,orderId:r,onPulled:i})]})})}function pz(t,a){let s=!1;const r={...t};for(const[n,i]of Object.entries(a)){if(!i||typeof i!="object"||!("value"in i))continue;const l=r[n];l&&typeof l=="object"&&"value"in l?r[n]={...l,...i}:r[n]={value:i.value,source:i.source??"User",isEdited:i.isEdited??!0,alternatives:i.alternatives??{}},s=!0}return s?r:t}function jT({property:t,open:a,onClose:s,onSelect:r,onDeselect:n,isSelected:i=!1,isSubject:l=!1,isLoading:c=!1,isPhotosLoading:d=!1,onRefreshPhotos:p,onFocusOnMap:u,onNext:m,onPrev:h,hasNext:f=!1,hasPrev:v=!1,currentIndex:S,totalCount:N,orderId:x=null}){return o.useEffect(()=>{if(!a)return;const y=b=>{if(document.querySelector('[data-testid="photo-lightbox"], [data-testid="all-photos-view"]'))return;const j=b.target?.tagName;j==="INPUT"||j==="TEXTAREA"||b.target?.isContentEditable||(b.key==="ArrowLeft"&&v&&h?(b.preventDefault(),h()):b.key==="ArrowRight"&&f&&m&&(b.preventDefault(),m()))};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[a,v,f,h,m]),t?e.jsx(xi,{open:a,onOpenChange:()=>s(),children:e.jsxs(bi,{hideClose:!0,className:"max-w-[1400px] w-[80vw] p-0 gap-0 overflow-hidden bg-white h-[88vh] flex flex-col rounded-xl","data-testid":"expanded-property-card",children:[e.jsx(v5,{children:e.jsxs(si,{children:["Property Details - ",t.address]})}),e.jsx(KV,{property:t,isSubject:l,isSelected:i,isLoading:c,isPhotosLoading:d,onRefreshPhotos:p,onSelect:r,onDeselect:n,onFocusOnMap:u,onNext:m,onPrev:h,hasNext:f,hasPrev:v,currentIndex:S,totalCount:N,onClose:s,onBack:l?void 0:s,orderId:x})]})}):null}const mz=["ACTV","NEW","PCHG","BOMK","RACT","CSOON","HOLD","PEND","CTG","AUC","CLSD"],hz={status:["CLSD","ACTV","PEND"],statusSelection:mz,monthsBack:12},nk={status:["CLSD"],monthsBack:12,sortBy:"match",minBeds:void 0,maxBeds:void 0,minBaths:void 0,maxBaths:void 0,bedsSelection:void 0,bathsSelection:void 0,statusSelection:void 0,propertyTypes:void 0,dateFilterField:"closed",dateRangeMode:void 0,dateRangePreset:void 0,dateRangeStart:void 0,dateRangeEnd:void 0,minLotSqft:void 0,maxLotSqft:void 0,stories:void 0,hasPool:void 0,hasBasement:void 0,basementType:void 0,maxHoa:void 0,minGarage:void 0,maxGarage:void 0,minYearBuilt:void 0,maxYearBuilt:void 0,strOnly:!1,remarksSearch:void 0,styleSelection:void 0,cityFilter:void 0,streetNameFilter:void 0,minStreet
4Number:void 0,maxStreetNumber:void 0,conditionRatings:void 0,qualityRatings:void 0,minLocationScore:void 0,maxLocationScore:void 0,minOccupancyPct:void 0,maxOccupancyPct:void 0},fw={phase:"market-scout",filters:nk,marketDefinition:null,properties:[],selectedComps:[],hoveredPropertyId:null,focusedPropertyId:null,isLoading:!1,error:null,aiSuggestions:[],searchPerformed:!1,dataSource:null,cacheMetadata:null};function Vb(t,a=!1){const s=t.photos||(t.photoUrl?[t.photoUrl]:[]),r=t.mlsData||{},n=t.publicRecordData||{};let i=t.beds&&t.beds>0?t.beds:null;i===null&&r.bedrooms&&(i=parseInt(String(r.bedrooms))||null),i===null&&r.BedroomsTotal&&(i=parseInt(String(r.BedroomsTotal))||null),i===null&&n.bedrooms&&(i=parseInt(String(n.bedrooms))||null);let l=t.baths&&t.baths>0?t.baths:null;l===null&&r.bathrooms&&(l=parseFloat(String(r.bathrooms))||null),l===null&&r.BathroomsTotalInteger&&(l=parseFloat(String(r.BathroomsTotalInteger))||null),l===null&&r.BathroomsFull&&(l=parseFloat(String(r.BathroomsFull))||null),l===null&&n.bathrooms&&(l=parseFloat(String(n.bathrooms))||null);const c=x=>{if(x==null)return null;const y=typeof x=="number"?x:Number(x);return!isNaN(y)&&y>=0?y:null};let d=c(t.fullBathrooms)??c(r.BathroomsFull)??c(r.bathroomsFull)??c(r.fullBathrooms)??c(n.fullBathrooms)??c(n.bathroomsFull)??null,p=c(t.halfBathrooms)??c(r.BathroomsHalf)??c(r.bathroomsHalf)??c(r.halfBathrooms)??c(n.halfBathrooms)??c(n.bathroomsHalf)??null;const u=c(t.basementFullBaths)??c(r.basementFullBaths)??null,m=c(t.basementHalfBaths)??c(r.basementHalfBaths)??null;if(d===null&&p===null&&l!==null){d=Math.floor(l);const x=l-d;p=x>=.1?Math.round(x*2):0}const h=x=>{if(x==null)return null;const y=typeof x=="number"?x:Number(x);return!isNaN(y)&&y>0?y:null},f=h(t.prLivingArea)??h(n.squareFeet)??h(n.livingArea),v=h(n.lotSize)??(n.lotAcres&&Math.round(Number(n.lotAcres)*43560)||null),S=h(n.yearBuilt),N=DI({propertyScope:t.propertyScope,unitCount:t.unitCount,unitCountSource:t.unitCountSource,unitCountAlternatives:t.unitCountAlternatives,unitNumber:t.unitNumber,unitNumberSource:t.unitNumberSource,sqft:t.gla,sqftPR:t.prLivingArea,buildingAreaSqft:t.buildingAreaSqft,buildingAreaSource:t.buildingAreaSource,unitAreaSqft:t.unitAreaSqft,unitAreaSource:t.unitAreaSource,unitMix:t.unitMix,unitMixSource:t.unitMixSource,unitBreakdown:t.unitBreakdown,unitBreakdownSource:t.unitBreakdownSource,scopeEvidence:t.scopeEvidence,propertyType:t.propertyType,mlsData:r,publicRecordData:n});return{id:t.id,snapshotId:t.snapshotId,mlsNumber:t.mlsNumber||null,mlsBoard:t.mlsBoard||null,address:t.address,city:t.city,state:t.state,zip:t.zip,price:t.price,listPrice:t.listPrice||null,beds:i,baths:l,fullBathrooms:d,halfBathrooms:p,basementFullBaths:u,basementHalfBaths:m,sqft:t.gla||null,sqftPR:f,lotSqft:t.lotSize||null,lotSqftPR:v,photoUrl:t.photoUrl||null,photos:s,photoCount:s.length,photosStatus:t.photosStatus||(s.length>0?"ready":"pending"),dom:t.dom||0,status:t.isStrProperty?"Rental":t.status,propertyType:t.propertyType||"House",strNightlyRate:t.strAverageDailyRate,stories:t.stories??h(r.stories)??h(n.stories)??null,garageSpaces:t.garageSpaces??h(r.garageSpaces)??h(n.garageSpaces)??null,style:t.style||r.style||r.ArchitecturalStyle||n.style||null,basement:t.basement||r.basement||r.Basement||n.basement||null,coordinates:t.coordinates,similarityScore:t.similarityScore,isSelected:a,yearBuilt:t.yearBuilt,yearBuiltPR:S,pricePerSqft:t.pricePerSqft,mlsData:t.mlsData,publicRecordData:t.publicRecordData,propertyScope:t.propertyScope&&t.propertyScope!=="unknown"?t.propertyScope:N.scope,unitCount:t.unitCount??N.unitCount,unitCountSource:t.unitCountSource??N.unitCountSource,unitCountAlternatives:t.unitCountAlternatives??N.unitCountAlternatives,unitCountConflict:t.unitCountConflict??N.unitCountConflict,unitNumber:t.unitNumber??N.unitNumber,unitNumberSource:t.unitNumberSource??N.unitNumberSource,buildingAreaSqft:t.buildingAreaSqft??N.buildingAreaSqft,buildingAreaSource:t.buildingAreaSource??N.buildingAreaSource,unitAreaSqft:t.unitAreaSqft??N.unitAreaSqft,unitAreaSource:t.unitAreaSource??N.unitAreaSource,unitMix:t.unitMix??N.unitMix,unitMixSource:t.unitMixSource??N.unitMixSource,unitBreakdown:t.unitBreakdown??N.unitBreakdown,unitBreakdownSource:t.unitBreakdownSource??N.unitBreakdownSource,scopeEvidence:t.scopeEvidence??N,propMixCachedAt:t.propMixCachedAt||null,saleDate:t.saleDate||null,contractDate:t.contractDate||null,listDate:t.listDate||r.ListingContractDate||null,distance:t.distance??null,distressedYN:(()=>{const x=r.DistressedYN??r.distressedYN;if(x===!0)return!0;
4if(x===!1)return!1;if(typeof x=="string"){const y=x.trim().toLowerCase();if(y==="y"||y==="yes"||y==="true"||y==="1")return!0;if(y==="n"||y==="no"||y==="false"||y==="0")return!1}return null})(),distressType:(r.DistressType??r.distressType??r.DistressedType)||null,specialListingConditions:(r.SpecialListingConditions??r.specialListingConditions??r.SaleType??r.saleType)||null,btDesignStyle:t.btDesignStyle??null,btStyleConfidence:t.btStyleConfidence!=null?Number(t.btStyleConfidence):null,btNormalizedGla:t.btNormalizedGla??null,btGlaSource:t.btGlaSource??null,btGlaConfidence:t.btGlaConfidence??null,btGlaNormNote:t.btGlaNormNote??null,mlsAboveGradeArea:t.mlsAboveGradeArea??null,mlsTotalLivingArea:t.mlsTotalLivingArea??null,prLivingArea:t.prLivingArea??null,roomMathGla:t.roomMathGla??null,roomMathFactor:t.roomMathFactor??null,roomCount:t.roomCount??null,roomMathAgreement:t.roomMathAgreement??null,glaSanityFlag:t.glaSanityFlag??null,btMarketPositionScore:t.btMarketPositionScore??null,btLocationRating:t.btLocationRating??null,btViewScore:t.btViewScore??null,btViewRating:t.btViewRating??null,btTimeAdjustmentRate:t.btTimeAdjustmentRate!=null?Number(t.btTimeAdjustmentRate):null,btTimeAdjustmentMethod:t.btTimeAdjustmentMethod??null,aiConditionRating:t.aiConditionRating??null,aiConditionSignals:t.aiConditionSignals??null,aiQualitySignals:t.aiQualitySignals??null,aiRecentUpdates:t.aiRecentUpdates??null,aiBasementDetails:t.aiBasementDetails??null,conditionRating:t.conditionRating??null,conditionSource:t.conditionSource??null,qualityRating:t.qualityRating??null,qualitySource:t.qualitySource??null,echoLocationScore:t.echoLocationScore,isStrProperty:t.isStrProperty,strListingName:t.strListingName,strAverageDailyRate:t.strAverageDailyRate,strOccupancyRate:t.strOccupancyRate,strGrossRevenue12mo:t.strGrossRevenue12mo,strRating:t.strRating,strReviewCount:t.strReviewCount,strMaxGuests:t.strMaxGuests,strProvider:t.strProvider,strListingUrl:t.strListingUrl,derivedAddressSource:t.derivedAddressSource??null,derivedAddressConfidence:t.derivedAddressConfidence??null,sourceAddressWasCityLevel:t.sourceAddressWasCityLevel}}const hi=(t,a="Derived",s={})=>({value:t,source:a,isEdited:!1,alternatives:{[a.toLowerCase().replace(/[\/ ]/g,"_")]:t,...s}}),fz={subjectAddress:{value:"",source:"Echo",isEdited:!1,alternatives:{}},lender:{value:"",source:"Echo",isEdited:!1,alternatives:{}},client:{value:"",source:"Echo",isEdited:!1,alternatives:{}},effectiveDate:{value:"",source:"Derived",isEdited:!1,alternatives:{}},appraiser:{value:"",source:"Echo",isEdited:!1,alternatives:{}},form:{value:"",source:"Echo",isEdited:!1,alternatives:{}},loanNumber:{value:"",source:"Echo",isEdited:!1,alternatives:{}},fhaVaNumber:{value:"",source:"Echo",isEdited:!1,alternatives:{}},borrower:{value:"",source:"Echo",isEdited:!1,alternatives:{}},coBorrower:{value:"",source:"Echo",isEdited:!1,alternatives:{}},purpose:{value:"",source:"Echo",isEdited:!1,alternatives:{}},owner:{value:"",source:"Echo",isEdited:!1,alternatives:{}},appraiserLicense:{value:"",source:"Echo",isEdited:!1,alternatives:{}},appraiserLicenseExpiration:{value:"",source:"Echo",isEdited:!1,alternatives:{}},appraiserLicenseType:{value:"",source:"Echo",isEdited:!1,alternatives:{}},appraiserLicenseState:{value:"",source:"Echo",isEdited:!1,alternatives:{}},lenderAddress:{value:"",source:"Echo",isEdited:!1,alternatives:{}},clientAddress:{value:"",source:"Echo",isEdited:!1,alternatives:{}},assignmentType:{value:"",source:"Derived",isEdited:!1,alternatives:{}},assignmentTypeOtherDescription:{value:"",source:"Derived",isEdited:!1,alternatives:{}},offeredForSale:{value:null,source:"Derived",isEdited:!1,alternatives:{}},offeredForSaleDataSource:{value:"",source:"Derived",isEdited:!1,alternatives:{}},offeredForSaleMlsNumber:{value:"",source:"Derived",isEdited:!1,alternatives:{}},offeredForSalePrice:{value:"",source:"Derived",isEdited:!1,alternatives:{}},offeredForSaleListDate:{value:"",source:"Derived",isEdited:!1,alternatives:{}},contractAnalyzed:{value:null,source:"Derived",isEdited:!1,alternatives:{}},contractAnalysisExplanation:{value:"",source:"Derived",isEdited:!1,alternatives:{}},contractPrice:{value:"",source:"Derived",isEdited:!1,alternatives:{}},contractDate:{value:"",source:"Derived",isEdited:!1,alternatives:{}},sellerOwnerOfRecord:{value:null,source:"Derived",isEdited:!1,alternatives:{}},sellerOwnerDataSource:{value:"",source:"Derived",isEdited:!1,alternatives:{}},financialAssistance:{value:null,source:"Derived",isEdited:!1,alternatives:{}},financialAssistanceAmount:{value:"",source:"Derived",isEdited:!1,alternatives:{}},financialAssistanceDescription:{value:"",source:"Derived",isEdited:!1,alternatives:{}}};hi("Newrez LLC","Echo"),hi("eStreet AMC","Echo"),hi("12/01/2024","Echo"),hi("Edward Fermanis","Echo"),hi("1004","Echo"),hi("9789318749","Echo"),hi("138-2657973","Echo"),hi("Kathryn Maday","Echo"),hi("N/A","Echo"),hi("Refinance","Echo"),hi("Kathryn Maday","PublicRecord"),hi("556.004321","Echo"),hi("12/31/2025","Echo"),hi("Certified","Echo"),hi("IL","Echo"),hi("1100 Virginia Dr, Fort Washington, PA 19034","
4Echo"),hi("1185 Avenue of the Americas, New York, NY 10036","Echo"),hi("Refinance","Derived"),hi("BV-2026-0052","Echo"),hi("Echo Valuation Services","Echo"),hi("Owner","PublicRecord");const ux={neighborhoodName:{value:"",source:"Derived",isEdited:!1,alternatives:{}},pinNumber:{value:"",source:"Derived",isEdited:!1,alternatives:{}},legalDescription:{value:"",source:"Derived",isEdited:!1,alternatives:{}},taxYear:{value:"",source:"Derived",isEdited:!1,alternatives:{}},taxes:{value:"",source:"Derived",isEdited:!1,alternatives:{}},assessedValue:{value:"",source:"Derived",isEdited:!1,alternatives:{}},yearBuilt:{value:"",source:"Derived",isEdited:!1,alternatives:{}},pud:{value:"",source:"Derived",isEdited:!1,alternatives:{}},hoaFees:{value:"",source:"Derived",isEdited:!1,alternatives:{}},hoaFeeFrequency:{value:"",source:"Derived",isEdited:!1,alternatives:{}},zoningClassification:{value:"",source:"Derived",isEdited:!1,alternatives:{}},zoningDescription:{value:"",source:"Derived",isEdited:!1,alternatives:{}},zoningCompliance:{value:"Legal",source:"Derived",isEdited:!1,alternatives:{}},highestBestUse:{value:!0,source:"Derived",isEdited:!1,alternatives:{}},county:{value:"",source:"Derived",isEdited:!1,alternatives:{}},censusTract:{value:"",source:"Derived",isEdited:!1,alternatives:{}},mapReference:{value:"",source:"Derived",isEdited:!1,alternatives:{}},specialAssessments:{value:"",source:"Derived",isEdited:!1,alternatives:{}},lotSize:{value:"",source:"Derived",isEdited:!1,alternatives:{}},lotDimensions:{value:"",source:"Derived",isEdited:!1,alternatives:{}},stories:{value:"",source:"Derived",isEdited:!1,alternatives:{}},designStyle:{value:"",source:"Derived",isEdited:!1,alternatives:{}},gla:{value:"",source:"Derived",isEdited:!1,alternatives:{}},garageSpaces:{value:"",source:"Derived",isEdited:!1,alternatives:{}},fireplace:{value:"",source:"Derived",isEdited:!1,alternatives:{}},basement:{value:"",source:"Derived",isEdited:!1,alternatives:{}},basementFinishedArea:{value:"",source:"Derived",isEdited:!1,alternatives:{}},femaFloodZone:{value:"",source:"Derived",isEdited:!1,alternatives:{}},femaMapNumber:{value:"",source:"Derived",isEdited:!1,alternatives:{}},attachmentType:{value:"",source:"Derived",isEdited:!1,alternatives:{}},numParcels:{value:"",source:"Derived",isEdited:!1,alternatives:{}},allRightsAppraised:{value:"",source:"Derived",isEdited:!1,alternatives:{}}};hi("R-4","PublicRecord",{echo:"Res",public_record:"R-4",mls:"Residential"}),hi("Single Family Residential","PublicRecord",{echo:"SF",public_record:"Single Family Residential"}),hi("Legal","Derived"),hi(!0,"Derived"),hi("Single Family","Echo",{echo:"Single Family",public_record:"Single Family"}),hi("1","PublicRecord",{echo:"1",public_record:"1"}),hi("Fee Simple","PublicRecord",{echo:"Fee Simple",public_record:"Fee Simple"});function hg(t,a){const s=t.filter(d=>d!=null&&d>0&&isFinite(d));if(s.length<5)return null;const r=s.length,n=s.reduce((d,p)=>d+p,0)/r,i=s.reduce((d,p)=>d+(p-n)**2,0)/(r-1),l=Math.sqrt(i);if(l===0)return null;const c=a==="year built"?-1/0:0;return{mean:Math.round(n),stdDev:Math.round(l),greenRange:[Math.max(c,Math.round(n-.5*l)),Math.round(n+.5*l)],yellowLowRange:[Math.max(c,Math.round(n-1*l)),Math.max(c,Math.round(n-.5*l))],yellowHighRange:[Math.round(n+.5*l),Math.round(n+1*l)],sampleSize:r,attribute:a}}function Yx(t,a){if(t>=a.greenRange[0]&&t<=a.greenRange[1])return"green";const s=a.yellowLowRange[0],r=a.yellowHighRange[1];return t>=s&&t<=r?"yellow":"red"}function gw(t){const a=t.map(c=>c.sqft).filter(c=>c!=null&&c>0),s=hg(a,"above-grade finished area");if(!s)return null;const r=t.map(c=>c.lotSqft).filter(c=>c!=null&&c>0),n=hg(r,"site size"),i=t.map(c=>c.yearBuilt).filter(c=>c!=null&&c>1800),l=hg(i,"year built");return{gla:s,lotSize:n??void 0,yearBuilt:l??void 0}}function XA(t,a,s,r){const n=Yx(a,t),i=r?.unit??"square feet",l=r?.adjustmentNoun??"gross living area",c=t.attribute==="year built",d=h=>c?String(h):h.toLocaleString(),p=n==="green"?`falls within the typical market range and within the sensitivity band where buyers generally perceive homes as providing similar ${c?"age-related utility":"living utility"}`:n==="yellow"?`falls within the primary tolerance range but outside the sensitivity band, indicating ${c?"age":"size"} may begin to influence buyer perception`:"falls outside the primary tolerance range, indicating a meaningful difference from the competitive market segment",u=n==="green"?`no ${l} adjustment is supported by ${c?"age":"size"} alone unless a comparable falls outside the typical market range or the difference materially changes buyer utility`:n==="yellow"?`${l} adjustments should be considered where ${c?"age":"size"} differences cross the sensitivity threshold and demonstrably affect buyer utility`:`${l} adjustments are warranted to account for the meaningful ${c?"age":"size"} differential relative to the competitive market segment`,m=n==="green"?`Accordingly, the subject's ${c?"age":"size"} is consistent with the competitive market segment, and`:n==="yellow"?"Given the subject's position near the edge of the typical range,":`Given the subject's ${c?"age":"size"} falls outside the typical competitive range,`;return`A buyer utility analysis was performed using closed sales within the competitive market segment. Based on ${t.sampleSize} closed sales, the market's mean ${s} is approximately ${d(t.mean)} ${i} with a standard deviation of approximately ${d(t.stdDev)} ${i}. This produces a sensitivity range (Mean ±0.5 SD) of approximately ${d(t.greenRange[0])} to ${d(t.greenRange[1])} ${i} and a primary tolerance range (Mean ±1.0 SD) of approximately ${d(t.yellowLowRange[0])} to ${d(t.yellowHighRange[1])} ${i}. The subject property, at ${d(a)} ${i}, ${p}. ${m} ${u}.`}function av(t){const a=String(t??"").toLowerCase().trim();return a?a.includes("sold")||a.includes("closed")||a==="clsd"?"sold":a.includes("pending")||a.includes("contract")||a.includes("contingen")||a==="pend"?"underContract":a.includes("active")||a==="actv"?"active":null:null}function gz(t,a,s=new Date){const r=new Date(s);r.setMonth(r.getMonth()-Math.max(a,1));const i=t.some(p=>p.listDate?!isNaN(new Date(p.listDate).getTime()):!1)?t.filter(p=>{if(av(p.status)!=="active"||!p.listDate)return!1;const u=new Date(p.listDate);return!isNaN(u.getTime())&&u>=r&&u<=s}).length:null,l=t.filter(p=>av(p.status)==="active").length,c=t.filter(p=>av(p.status)==="underContract").length,d=t.length>0?Math.round(t.filter(p=>p.isDistressed===!0).length/t.length*1e3)/10:null;return{newListings:i,active:l,underContract:c,distressedSharePct:d}}function $b(t,a){const s=a.scaleMax-a.scaleMin;return s>0?Math.min(1,Math.max(0,(t-a.scaleMin)/s)):.5}function xw(t){if(t.length===0)return 0;const a=[...t].sort((r,n)=>r-n),s=Math.floor(a.length/2);return a.length%2?a[s]:(a[s-1]+a[s])/2}function xz(t){const a=[],s=(m,h,f)=>m<h?"below":m>f?"above":"within",r=(m,h,f,v)=>{const S=hg(m,h);return S?{low:S.yellowLowRange[0],high:S.yellowHighRange[1]}:f<=0?null:{low:f-v,high:f+v}},n=(m,h,f,v)=>{if(!m)return;const S=Math.min(m.low,v,h,...f.length?[Math.min(...f)]:[]),N=Math.max(m.high,v,h,...f.length?[Math.max(...f)]:[]),x=N-S,y=x>0?x*.06:Math.max(Math.abs(N)*.05,1);return{low:m.low,high:m.high,median:h,scaleMin:S-y,scaleMax:N+y}},i=(m,h)=>({key:m,label:h,direction:"within",noData:!0});if(t.subjectGla!=null&&t.subjectGla>0&&t.medGla>0){const m=r(t.poolGlas,"above-grade finished area",t.medGla,t.medGla*.15);a.push({key:"gla",label:"GLA",subjectValue:t.subjectGla,typicalValue:t.medGla,direction:m?s(t.subjectGla,m.low,m.high):"within",band:n(m,t.medGla,t.poolGlas,t.subjectGla)})}else a.push(i("gla","GLA"));if(t.subjectBeds!=null&&t.subjectBeds>
40&&t.poolBeds.length>0){const m=t.medBeds>0?t.medBeds:xw(t.poolBeds);a.push({key:"beds",label:"Beds",subjectValue:t.subjectBeds,typicalValue:m,direction:s(t.subjectBeds,m-1,m+1),band:n({low:m-1,high:m+1},m,t.poolBeds,t.subjectBeds)})}else a.push(i("beds","Beds"));if(t.subjectBaths!=null&&t.subjectBaths>0&&t.poolBaths.length>0){const m=t.medBaths>0?t.medBaths:xw(t.poolBaths);a.push({key:"baths",label:"Baths",subjectValue:t.subjectBaths,typicalValue:m,direction:s(t.subjectBaths,m-1,m+1),band:n({low:m-1,high:m+1},m,t.poolBaths,t.subjectBaths)})}else a.push(i("baths","Baths"));if(t.subjectYearBuilt!=null&&t.subjectYearBuilt>1800&&t.medYearBuilt>1800){const m=r(t.poolYearBuilts,"year built",t.medYearBuilt,15);a.push({key:"yearBuilt",label:"Year Built",subjectValue:t.subjectYearBuilt,typicalValue:t.medYearBuilt,direction:m?s(t.subjectYearBuilt,m.low,m.high):"within",band:n(m,t.medYearBuilt,t.poolYearBuilts,t.subjectYearBuilt)})}else a.push(i("yearBuilt","Year Built"));const l=a.filter(m=>!m.noData);if(l.length===0)return{attributes:[],conclusion:"unknown",explanation:"Subject details not available for comparison."};const c=l.filter(m=>m.direction==="above").length,d=l.filter(m=>m.direction==="below").length;let p,u;return c>=2||c===1&&l.length===1?(p="over-improvement",u=`Subject exceeds the typical market range on: ${l.filter(h=>h.direction==="above").map(h=>h.label).join(", ")}. Consider whether the market fully recognizes the extra utility.`):d>=2||d===1&&l.length===1?(p="under-improvement",u=`Subject falls below the typical market range on: ${l.filter(h=>h.direction==="below").map(h=>h.label).join(", ")}. Consider whether this limits marketability relative to the pool.`):c===1&&d===0?(p="over-improvement",u=`Subject exceeds the typical market range on ${l.find(h=>h.direction==="above").label}; other attributes conform.`):d===1&&c===0?(p="under-improvement",u=`Subject falls below the typical market range on ${l.find(h=>h.direction==="below").label}; other attributes conform.`):c>0&&d>0?(p="conforms",u="Subject is above typical on some attributes and below on others — overall it competes within this market."):(p="conforms",u="Subject GLA, beds, baths, and year built all fall within the typical range for this market."),{attributes:a,conclusion:p,explanation:u}}function bz(t,a){if(t==null||t<0||a==null||a<=0)return null;const s=Math.max(30,Math.round(a*1.5));return{subjectDom:t,marketMedianDom:a,typicalUpperBound:s,inRange:t<=s}}const bw=/active|pending|coming\s*soon|under\s*contract|contingent|back\s*on\s*market/i,yw=/sold|closed|expired|withdrawn|cancell?ed|off\s*market|leased|rented/i,yz=365;function Sz(t){if(t==null||String(t).trim()==="")return null;const a=Number(String(t).replace(/[^0-9.]/g,""));return isFinite(a)&&a>=0?Math.round(a):null}function sv(t){return t==null||String(t).trim()===""||isNaN(new Date(t).getTime())?null:String(t)}function vz(t){return sv(t.soldDate??t.SoldDate??t.closeDate??t.CloseDate)??sv(t.offMarketDate??t.OffMarketDate)??sv(t.statusChangeDate??t.StatusChangeDate??t.statusChangeTimestamp??t.StatusChangeTimestamp)}function Sw(t,a=!1){if(!t||typeof t!="object")return null;const s=t.status??t.standardStatus??t.listingStatus??t.Status??t.StandardStatus??t.MlsStatus??null,r=s!=null&&String(s).trim()!==""?String(s):null,n=Sz(t.daysOnMarket??t.dom??t.DaysOnMarket),i=sv(t.listDate??t.date??t.ListDate??t.ListingContractDate??t.OnMarketDate);return n==null&&i==null?null:{dom:n,status:r,listDate:i,endDate:vz(t),fromHistory:a}}function vw(t){if(t.listDate==null||t.endDate==null)return null;const a=new Date(t.endDate).getTime()-new Date(t.listDate).getTime();return a>=0?Math.floor(a/864e5):null}function Nz(t,a=new Date){if(!t||typeof t!="object")return null;const s=[],r=Sw(t);r&&s.push(r);const i=(Array.isArray(t.listingHistory)?t.listingHistory:[]).map(f=>Sw(f,!0)).filter(f=>f!=null).sort((f,v)=>{const S=f.listDate?new Date(f.listDate).getTime():0;return(v.listDate?new Date(v.listDate).getTime():0)-S});s.push(...i);const l=f=>{if(!f.listDate)return!1;const v=(a.getTime()-new Date(f.listDate).getTime())/864e5;return v>=0&&v<=yz},c=f=>(f.dom!=null||vw(f)!=null)&&l(f),d=s.find(f=>f.status&&bw.test(f.status)?!0:f.status&&yw.test(f.status)?c(f):l(f));if(!d)return null;const p=!!(d.status&&yw.test(d.status)),u=!!(d.status&&bw.test(d.status)),m=p||d.fromHistory&&!u;let h=d.dom;if(h==null){if(p)h=vw(d);else if(d.listDate!=null){const f=a.getTime()-new Date(d.listDate).getTime();f>=0&&(h=Math.floor(f/864e5))}}return h==null?null:{dom:h,status:d.status,listDate:d.listDate,isPrior:m}}
4async function Nw(t){const a=t.querySelector("svg");if(!a)return null;const s=parseInt(a.getAttribute("width")||"0",10)||Math.round(a.getBoundingClientRect().width)||600,r=parseInt(a.getAttribute("height")||"0",10)||Math.round(a.getBoundingClientRect().height)||300,n=new XMLSerializer,i=a.cloneNode(!0);i.hasAttribute("xmlns")||i.setAttribute("xmlns","http://www.w3.org/2000/svg");const l=document.createElementNS("http://www.w3.org/2000/svg","rect");l.setAttribute("x","0"),l.setAttribute("y","0"),l.setAttribute("width",String(s)),l.setAttribute("height",String(r)),l.setAttribute("fill","#ffffff"),i.insertBefore(l,i.firstChild);const c=n.serializeToString(i),d=new Blob([c],{type:"image/svg+xml;charset=utf-8"}),p=URL.createObjectURL(d);return new Promise(u=>{const m=new Image;m.onload=()=>{const f=document.createElement("canvas");f.width=s*2,f.height=r*2;const v=f.getContext("2d");if(!v){URL.revokeObjectURL(p),u(null);return}v.scale(2,2),v.fillStyle="#ffffff",v.fillRect(0,0,s,r),v.drawImage(m,0,0,s,r),URL.revokeObjectURL(p),u(f.toDataURL("image/png"))},m.onerror=()=>{URL.revokeObjectURL(p),u(null)},m.src=p})}const wr="#072034",Oo="#1B4D6E",Ws="#C5A572",ey="#A18A60",ef="#FAF9F7",en="#EDE8E4",Es="#6B7280",M0="#16A34A",kv="#DC2626",Qf=[{id:"priceTrend",label:"Price Trends",description:"Median sale price over time",appraiserNote:"The most important indicator for your value opinion — shows whether prices are going up, down, or holding steady.",alwaysOn:!0},{id:"inventory",label:"Inventory Activity",description:"Active, sold & pending listings",appraiserNote:"Shows if there are more homes for sale than buyers — directly supports your demand/supply field.",alwaysOn:!0},{id:"domDistribution",label:"Days on Market",description:"How long homes sit before selling",appraiserNote:"Shows the typical marketing time — helps you fill in the marketing time field.",alwaysOn:!0},{id:"priceDistribution",label:"Price Distribution",description:"Where most sales fall by price range",appraiserNote:"Helps you set the low/high/predominant price fields."},{id:"saleToList",label:"Sale-to-List Ratio",description:"Gap between asking and actual sale prices",appraiserNote:"Shows negotiation trends — a shrinking gap means sellers are getting closer to asking price."},{id:"absorptionRate",label:"Absorption & Supply",description:"How fast homes are being absorbed",appraiserNote:"Under 4 months = seller's market. 4-6 = balanced. Over 6 = buyer's market."},{id:"ppsfTrend",label:"Price Per Sq Ft",description:"PPSF trend over time",appraiserNote:"Helps with adjustment support — shows the $/sqft trajectory."},{id:"domTrend",label:"DOM Trend",description:"Marketing time trends",appraiserNote:"Shows whether marketing times are getting longer or shorter."}],Az=["priceTrend","inventory","domDistribution"],Vd=6;function jz(t,a){return!!t[a]||Object.values(t).filter(Boolean).length<Vd}function Aw(t){const a=new Set(t.slice(0,Vd));return Object.fromEntries(Qf.map(({id:s})=>[s,a.has(s)]))}function Tz(t,a,s){return t==="eval"&&(a||s)}const jw=[{id:"1004",label:"1004 (URAR)"},{id:"1073",label:"1073 (Condo)"},{id:"eval",label:"Eval (IAEG)"},{id:"str",label:"STR"},{id:"3.6",label:"UAD 3.6 (URAR)"}];function dl(t){return t==null?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t)}function Gx(t,a=0){return t==null?"—":t.toLocaleString("en-US",{maximumFractionDigits:a})}function ej(t,a=1){return t==null?"—":`${t.toFixed(a)}%`}function rd(t){if(t.length===0)return 0;const a=[...t].sort((r,n)=>r-n),s=Math.floor(a.length/2);return a.length%2?a[s]:(a[s-1]+a[s])/2}function Tw(t){if(t.length<4)return{low:-1/0,high:1/0};const a=[...t].sort((c,d)=>c-d),s=Math.floor(a.length*.25),r=Math.floor(a.length*.75),n=a[s],i=a[r],l=i-n;return{low:n-1.5*l,high:i+1.5*l}}function Iz(t,a,s){let r=!1;for(let n=0,i=s.length-1;n<s.length;i=n++){const l=s[n].lat,c=s[n].lng,d=s[i].lat,p=s[i].lng;c>a!=p>a&&t<(d-l)*(a-c)/(p-c)+l&&(r=!r)}return r}function Cz(t,a,s,r){const i=(t-s.lat)*Math.PI/180,l=(a-s.lng)*Math.PI/180,c=Math.sin(i/2)**2+Math.cos(s.lat*Math.PI/180)*Math.cos(t*Math.PI/180)*Math.sin(l/2)**2;return 3958.8*2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))<=r}function Rz(t,a,s=!1){if(s)return{score:null,label:"Insufficient data",insufficient:!0,breakdown:{monthsOfSupply:{value:t.monthsOfSupply,points:0,max:35,label:"No data"},saleToList:{value:t.medCloseToList,points:0,max:25,label:"No data"},medianDOM:{value:t.medDOM,points:0,max:20,label:"No data"},absorptionRate:{value:t.absorptionRate,points:0,max:10,label:"No data"},priceTrend:{value:a,points:0,max:10,label:"No data"}}};let r,n;const i=t.monthsOfSupply;i<3?(r=35,n="Strong seller's"):i<4?(r=28,n="Moderate seller's"):i<=6?(r=18,n="Balanced"):i<=8?(r=8,n="Moderate buyer's"):(r=0,n="Strong buyer's");let l,c;const d=t.medCloseToList;d==null?(l=12,c="N/A"):d>100?(l=25,c="Highly competitive"):d>=97?(l=18,c="Healthy"):d>=95?(l=8,c="Softening"):(l=0,c="Weak");let p,u;const m=t.medDOM;m<30?(p=20,u="Hot"):m<=60?(p=13,u="Active"):m<=90?(p=5,u="Normal"):(p=0,u="Slow");let h,f;const v=t.absorptionRate;v>=70?(h=10,f="Rapid absorption"):v>=50?(h=7,f="Moderate absorption"):v>=30?(h=3,f="Low absorption"):(h=0,f="Very low");let S,N;const x=a;x>=5?(S=10,N="Appreciating"):x>=0?(S=6,N="Stable"):x>=-5?(S=3,N="Softening"):(S=0,N="Depreciating");const y=Math.max(0,Math.min(100,r+l+p+h+S));let b;return y>=80?b="Strong Seller's Market":y>=60?b="Moderate Seller's Market":y>=40?b="Balanced Market":y>
4=20?b="Moderate Buyer's Market":b="Strong Buyer's Market",{score:y,label:b,insufficient:!1,breakdown:{monthsOfSupply:{value:i,points:r,max:35,label:n},saleToList:{value:d,points:l,max:25,label:c},medianDOM:{value:m,points:p,max:20,label:u},absorptionRate:{value:v,points:h,max:10,label:f},priceTrend:{value:x,points:S,max:10,label:N}}}}function bh({active:t,payload:a,label:s,formatter:r}){return!t||!a?.length?null:e.jsxs("div",{className:"bg-white border rounded-lg shadow-lg px-3 py-2",style:{borderColor:en},children:[e.jsx("p",{className:"text-[12px] font-medium mb-1",style:{color:wr},children:s}),a.map((n,i)=>e.jsxs("div",{className:"flex items-center gap-1.5 text-[12px]",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:n.color}}),e.jsxs("span",{className:"text-[#6B7280]",children:[n.name,":"]}),e.jsx("span",{className:"font-medium",style:{color:wr},children:r?r(n.value,n.name):n.value})]},i))]})}function Ez({marketStats:t,subMarketStats:a,properties:s,subMarketProperties:r,subjectPrice:n,subjectYearBuilt:i,subjectGla:l,subjectLotSize:c,subjectBeds:d,subjectBaths:p,subjectListing:u,onFormFieldsUpdate:m,analyticsState:h,onAnalyticsStateChange:f,neighborhoodInfo:v,onNeighborhoodInfoChange:S,neighborhoodAiGenerated:N,onNeighborhoodAiGeneratedChange:x,subjectAddress:y,subjectCity:b,subjectCounty:j,subjectState:T,subMarketGeometry:O,reportFormType:E,assignmentId:R,onApplyChartsToReport:G,onAutoCaptureSave:U,marketDataSignature:C}){const F=E??"1004",A=Tz(F,!!G,!!U),{profile:M}=jI(),B=F==="3.6"&&!!R,[oe,ae]=o.useState({}),D=o.useRef({}),_=o.useRef(!1);o.useEffect(()=>{!B||_.current||(_.current=!0,fetch(`/api/market-session/uad36-market-overrides/${R}`,{credentials:"include"}).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{Ee?.success&&Ee.overrides&&typeof Ee.overrides=="object"&&(D.current=Ee.overrides,ae(Ee.overrides))}).catch(()=>{}))},[B,R]);const $=o.useCallback((Ee,dt)=>{const ot={...D.current};dt==null||dt===""?delete ot[Ee]:ot[Ee]=dt,D.current=ot,ae(ot),R&&fetch("/api/market-session/uad36-market-overrides",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({assignmentId:R,overrides:ot})}).catch(xa=>console.error("[Market] Failed to save §17 override:",xa))},[R]),[z,V]=o.useState({scope:"market",dateRange:"1yr",excludedIds:[],visibleSections:{},reportSections:{},formOverrides:{},sortField:"salePrice",sortDir:"desc",outliersHidden:!0}),le=h||z,W=o.useCallback(Ee=>{f?f(Ee(le)):V(Ee)},[le,f]),[me,Z]=o.useState(!1),[pe,se]=o.useState(!1),[fe,ue]=o.useState(!1),be=G?Qf.map(Ee=>Ee.id):Az,[H,ye]=o.useState(be),[de,ge]=o.useState(!1),[Be,He]=o.useState(!1),Ie=o.useRef(null),ce=o.useRef(""),Pe=o.useRef(null),[We,Re]=o.useState(A?Aw(be):G?Object.fromEntries(Qf.map(({id:Ee})=>[Ee,!0])):{priceTrend:!0});o.useEffect(()=>{!M?.id||de||fetch(`/api/profile/${M.id}/defaults`,{credentials:"include"}).then(Ee=>Ee.ok?Ee.json():null).then(Ee=>{const dt=Ee,ot=dt?.defaults?.marketChartDefaults??dt?.marketChartDefaults;if(Array.isArray(ot)&&ot.length>0){const xa=new Set(Qf.map(({id:ba})=>ba)),rs=ot.filter(ba=>typeof ba=="string"&&xa.has(ba)),Gs=Qf.filter(ba=>ba.alwaysOn).map(ba=>ba.id),bs=Array.from(new Set([...Gs,...rs]));ye(bs),A&&Re(Aw(bs))}ge(!0)}).catch(()=>ge(!0))},[M?.id,de,A]);const[ne,Me]=o.useState(!1),[lt,Tt]=o.useState(!1),je=o.useRef(null),Le=o.useRef({}),ut=o.useCallback(Ee=>dt=>{Le.current[Ee]=dt},[]);o.useEffect(()=>()=>{Ie.current&&clearTimeout(Ie.current),je.current&&clearTimeout(je.current),Pe.current&&clearTimeout(Pe.current)},[]);const st=o.useCallback(async()=>{if(!G||!Object.values(We).some(Boolean))return;const Ee=le.scope==="market"?"Broad Market":"Submarket";Me(!0);try{const dt=[];for(const ot of H){if(!We[ot])continue;const xa=Le.current[ot]??null;if(!xa)continue;const rs=await Nw(xa);if(!rs)continue;const Gs=S_[ot]??ot,bs=v_[ot];if(dt.push({src:rs,caption:`${Gs} — ${Ee}`,additionalCaption:Ee,imageType:bs,chartId:ot}),A&&dt.length===Vd)break}dt.length>0&&(await G(dt),Tt(!0),je.current&&clearTimeout(je.current),je.current=setTimeout(()=>Tt(!1),2500))}catch(dt){console.error("[Market] Failed to apply charts to report:",dt)}finally{Me(!1)}},[G,le.scope,H,We,A]),Xt=o.useRef(st);o.useEffect(()=>{Xt.current=st},[st]);const ua=o.useCallback(Ee=>{M?.id&&fetch(`/api/profile/${M.id}/defaults`,{credentials:"include"}).then(dt=>dt.ok?dt.json():{}).then(dt=>{const ot=dt?.defaults||{};return fetch(`/api/profile/${M.id}/defaults`,{method:"PUT",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({...ot,marketChartDefaults:Ee})})}).then(dt=>{if(!dt||!dt.ok)throw new Error("Failed to save defaults");He(!0),Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>He(!1),2e3)}
4).catch(console.error)},[M?.id]),Oa=o.useCallback(Ee=>{Qf.find(ot=>ot.id===Ee)?.alwaysOn||ye(ot=>{const xa=ot.includes(Ee);return A&&Re(Gs=>({...Gs,[Ee]:!1})),xa?ot.filter(Gs=>Gs!==Ee):[...ot,Ee]})},[A]),[Xa,qa]=o.useState(v?.boundaries||""),[os,ya]=o.useState(v?.description||""),[At,Fe]=o.useState(v?.marketConditions||""),[Oe,rt]=o.useState(!1);o.useEffect(()=>{v&&(qa(v.boundaries||""),ya(v.description||""),Fe(v.marketConditions||""))},[v]);const $t=o.useCallback((Ee,dt)=>{Ee==="boundaries"?qa(dt):Ee==="description"?ya(dt):Fe(dt),S?.({boundaries:Ee==="boundaries"?dt:Xa,description:Ee==="description"?dt:os,marketConditions:Ee==="marketConditions"?dt:At}),x?.(!1)},[Xa,os,At,S,x]),na=o.useCallback(async()=>{if(y){rt(!0);try{const Ee={address:y,city:b,county:j,state:T,marketStats:a||t};O&&(O.polygon&&(Ee.polygon=O.polygon),O.appliedBoundaries&&(Ee.appliedBoundaries=O.appliedBoundaries),O.radiusMiles&&(Ee.radiusMiles=O.radiusMiles),O.center&&(Ee.center=O.center));const ot=await(await fetch("/api/neighborhood/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ee)})).json();if(ot.success){const xa={boundaries:ot.boundaries||"",description:ot.description||"",marketConditions:ot.marketConditions||""};qa(xa.boundaries),ya(xa.description),Fe(xa.marketConditions),S?.(xa),x?.(!0)}}catch(Ee){console.error("[MarketDashboard] Failed to generate neighborhood info:",Ee)}finally{rt(!1)}}},[y,b,j,T,a,t,O,S,x]),zt=le.scope==="market"?t:a,Ua=le.dateRange==="6mo"?6:le.dateRange==="1yr"?12:le.dateRange==="2yr"?24:36,Ce=o.useMemo(()=>le.scope==="submarket"&&r&&r.length>0?r:s,[le.scope,r,s]),St=le.scope==="submarket"&&!!r&&r.length>0,vt=o.useMemo(()=>{const Ee=new Date;Ee.setMonth(Ee.getMonth()-Ua);const dt=le.scope==="submarket"&&!St&&O&&(O.polygon?.path&&O.polygon.path.length>=3||O.radiusMiles&&O.center);return Ce.filter(ot=>{const xa=ot.closeDate||ot.listDate;if(xa&&new Date(xa)<Ee)return!1;if(dt){const rs=ot.latitude,Gs=ot.longitude;return!Number.isFinite(rs)||!Number.isFinite(Gs)?!1:O.polygon?.path&&O.polygon.path.length>=3?Iz(rs,Gs,O.polygon.path):O.radiusMiles&&O.center?Cz(rs,Gs,O.center,O.radiusMiles):!1}return!0})},[Ce,Ua,le.scope,O,St]),Ve=o.useMemo(()=>{const Ee=vt.map(ot=>ot.salePrice).filter(ot=>ot!=null&&ot>0),dt=vt.map(ot=>ot.ppsf).filter(ot=>ot!=null&&ot>0);return{priceBounds:Tw(Ee),ppsfBounds:Tw(dt)}},[vt]),sa=o.useMemo(()=>{const Ee=new Set;return vt.forEach(dt=>{dt.salePrice!=null&&(dt.salePrice<Ve.priceBounds.low||dt.salePrice>Ve.priceBounds.high)&&Ee.add(dt.id),dt.ppsf!=null&&(dt.ppsf<Ve.ppsfBounds.low||dt.ppsf>Ve.ppsfBounds.high)&&Ee.add(dt.id)}),Ee},[vt,Ve]),tt=o.useRef(!1);o.useEffect(()=>{!tt.current&&vt.length>0&&le.outliersHidden&&sa.size>0&&(tt.current=!0,W(Ee=>({...Ee,excludedIds:Array.from(new Set([...Ee.excludedIds,...Array.from(sa)]))})))},[vt.length,le.outliersHidden,sa]);const it=o.useMemo(()=>new Set(le.excludedIds),[le.excludedIds]),Je=o.useMemo(()=>vt.filter(Ee=>!it.has(Ee.id)),[vt,it]),ht=o.useMemo(()=>Je.filter(Ee=>{const dt=Ee.status.toLowerCase();return dt.includes("sold")||dt.includes("closed")||dt==="clsd"}),[Je]),Kt=o.useMemo(()=>Je.filter(Ee=>{const dt=Ee.status.toLowerCase();return(dt.includes("active")||dt==="actv")&&!dt.includes("contract")}),[Je]),Sa=o.useMemo(()=>Je.filter(Ee=>{const dt=Ee.status.toLowerCase();return dt.includes("pending")||dt.includes("contract")||dt==="pend"}),[Je]),Qt=o.useMemo(()=>{const Ee=le.dateRange==="6mo"?"last 6 months":le.dateRange==="1yr"?"last 12 months":le.dateRange==="2yr"?"last 24 months":"last 36 months";let dt,ot,xa;if(le.scope==="market")dt="Broad market",ot="Broad market source set",xa="the broad market area";else if(St)dt="Submarket",ot=`Appraiser-curated submarket selection (${r.length} properties)`,xa="the appraiser-curated submarket selection";else if(O?.polygon?.path&&O.polygon.path.length>=3){const bs=O.polygon.path.length;dt="Submarket",ot=`Submarket polygon (${bs} vertices)`,xa=`the defined submarket polygon (${bs} vertices)`}else if(O?.radiusMiles&&O.center){const bs=O.radiusMiles,ba=Number.isInteger(bs)?`${bs}`:bs.toFixed(2).replace(/0+$/,"").replace(/\.$/,"");dt="Submarket",ot=`${ba}-mile radius from center`,xa=`a ${ba}-mile radius submarket from the center point`}else dt="Submarket",ot="Submarket area not yet defined",xa="the submarket area";const rs=le.outliersHidden?Array.from(sa).filter(bs=>it.has(bs)).length:0,Gs=Math.max(0,le.excludedIds.length-rs);return{scopeLabel:dt,dateRangeLabel:Ee,geometryLabel:ot,scopePhrase:xa,preFilterCount:Ce.length,postFilterCount:vt.length,outlierExcludedCount:rs,manualExcludedCount:Gs,includedCount:Je.length,soldCount:ht.length,activeCount:Kt.length,pendingCount:Sa.length,outliersHidden:le.outliersHidden}},[le.scope,le.dateRange,le.outliersHidden,le.excludedIds,Ce,vt,Je,ht,Kt,Sa,sa,it,O,r,St]),ea=o.useMemo(()=>{const Ee=ht.map(Qa=>Qa.salePrice).filter(Qa=>Qa!=null&&Qa>0),dt=Je.map(Qa=>Qa.gla).filter(Qa=>Qa!=null&&Qa>0),ot=Je.map(Qa=>Qa.beds).filter(Qa=>Qa!=null),xa=Je.map(Qa=>Qa.baths).filter(Qa=>Qa!=null),rs=Je.map(Qa=>Qa.yearBuilt).filter(Qa=>Qa!=null&&Qa>1800),Gs=ht.map(Qa=>Qa.dom).filter(Qa=>Qa!=null),bs=ht.map(Qa=>Qa.ppsf).filter(Qa=>Qa!=null&&Qa>0),ba=ht.map(Qa=>Qa.salePrice&&Qa.listPrice&&Qa.listPrice>0?Qa.salePrice/Qa.listPrice:null).filter(Qa=>Qa!=null&&Qa>0&&Qa<2),ln=rd(Ee),zn=rd(dt),fd=rd(ot),go=rd(xa),Zd=rd(Gs),Mu=rd(bs),hp=ba.length>0?rd(ba)*100:null,qn=bs.length>0?bs.reduce((Qa,Xi)=>Qa+Xi,0)/bs.length:0,gd=bs.length>1?Math.sqrt(bs.reduce((Qa,Xi)=>Qa+Math.pow(Xi-qn,2),0)/(bs.length-1)):0,Bi=[...rs].sort((Qa,Xi)=>Qa-Xi),xd=[...Ee].sort((Qa,Xi)=>Qa-Xi),Jp=ht.map(Qa=>Qa.listPrice).filter(Qa=>Qa!=null&&Qa>0),hf=rd(Jp),_c=ht.length/Math.max(Ua,1),bd=_c>0?Kt.length/_c:0,In=Kt.map(Qa=>Qa.listPrice??Qa.salePrice).filter(Qa=>Qa!=null&&Qa>0).sort((Qa,Xi)=>Qa-Xi),Yn=Kt.map(Qa=>Qa.dom).filter(Qa=>Qa!=null&&Qa>=0);return{compCount:Je.length,soldCount:ht.length,activeCount:Kt.length,pendingCount:Sa.length,medSalePrice:ln,medListPrice:hf,medGLA:Math.round(zn),medBeds:Math.round(fd),medBaths:Math.round(go*2)/2,medDOM:Math.round(Zd),medPPSF:Math.round(Mu),medCloseToList:hp,ppsfStdDev:Math.round(gd*10)/10,yearBuiltLow:Bi[0]||0,yearBuiltHigh:Bi[Bi.length-1]||0,priceLow:xd[0]||0,priceHigh:xd[xd.length-1]||0,priceMed:Math.round(ln),monthsOfSupply:Math.round(bd*10)/10,absorptionRate:_c>0?Math.round(ht.length/(ht.length+Kt.length)*100):0,avgDOM:Gs.length>0?Math.round(Gs.reduce((Qa,Xi)=>Qa+Xi,0)/Gs.length):0,activeListLow:In[0]||0,activeListHigh:In[In.length-1]||0,activeListMed:Math.round(rd(In)),activeMedDOM:Math.round(rd(Yn)),salePrice
4s:Ee,ppsfs:bs}},[Je,ht,Kt,Sa,Ua]),tr=o.useMemo(()=>gz(Je,Ua),[Je,Ua]),ir=o.useMemo(()=>{const Ee=Je.map(rs=>rs.gla).filter(rs=>rs!=null&&rs>0),dt=Je.map(rs=>rs.beds).filter(rs=>rs!=null),ot=Je.map(rs=>rs.baths).filter(rs=>rs!=null),xa=Je.map(rs=>rs.yearBuilt).filter(rs=>rs!=null&&rs>1800);return xz({subjectGla:l,subjectBeds:d,subjectBaths:p,subjectYearBuilt:i,poolGlas:Ee,poolBeds:dt,poolBaths:ot,poolYearBuilts:xa,medGla:ea.medGLA,medBeds:ea.medBeds,medBaths:ea.medBaths,medYearBuilt:rd(xa)})},[Je,l,d,p,i,ea]),zs=o.useMemo(()=>u?bz(u.dom,ea.medDOM):null,[u,ea.medDOM]),pr=o.useMemo(()=>{const dt=zt?.inventoryAnalysis?.trend||"Stable",ot=ea.monthsOfSupply<4?"Shortage":ea.monthsOfSupply>7?"OverSupply":"InBalance",xa=ea.medDOM<90?"Under3Months":ea.medDOM<=180?"3to6Months":"Over6Months";return{propertyValues:dt,demandSupply:ot,marketingTime:xa,priceLow:ea.priceLow,priceHigh:ea.priceHigh,pricePredominant:ea.priceMed,ageLow:ea.yearBuiltLow?new Date().getFullYear()-ea.yearBuiltHigh:0,ageHigh:ea.yearBuiltHigh?new Date().getFullYear()-ea.yearBuiltLow:0,agePredominant:ea.yearBuiltLow?new Date().getFullYear()-Math.round((ea.yearBuiltLow+ea.yearBuiltHigh)/2):0,...le.formOverrides}},[zt,ea,le.formOverrides]);o.useEffect(()=>{m?.(pr)},[pr,m]);const $e=o.useCallback(()=>{W(Ee=>{if(Ee.outliersHidden)return{...Ee,outliersHidden:!1,excludedIds:Ee.excludedIds.filter(dt=>!sa.has(dt))};{const dt=new Set(Ee.excludedIds);return sa.forEach(ot=>dt.add(ot)),{...Ee,outliersHidden:!0,excludedIds:Array.from(dt)}}})},[W,sa]),Ot=o.useCallback(Ee=>{W(dt=>{const ot=new Set(dt.excludedIds);return ot.has(Ee)?ot.delete(Ee):ot.add(Ee),{...dt,excludedIds:Array.from(ot)}})},[W]),_e=o.useMemo(()=>[...vt].sort((dt,ot)=>{const xa=dt[le.sortField],rs=ot[le.sortField];return xa==null&&rs==null?0:xa==null?1:rs==null?-1:le.sortDir==="asc"?xa>rs?1:-1:xa<rs?1:-1}),[vt,le.sortField,le.sortDir]),ma=o.useCallback(Ee=>{W(dt=>({...dt,sortField:Ee,sortDir:dt.sortField===Ee&&dt.sortDir==="desc"?"asc":"desc"}))},[W]),pt=o.useMemo(()=>{const Ee=ht.map(ba=>ba.salePrice).filter(ba=>ba!=null&&ba>0);if(Ee.length===0)return[];const dt=Math.min(...Ee),ot=Math.max(...Ee),xa=ot-dt;if(xa===0)return[{label:dl(dt),count:Ee.length,binStart:dt,binEnd:ot+1}];const rs=Math.min(20,Math.max(5,Math.ceil(Ee.length/5))),Gs=xa/rs,bs=[];for(let ba=0;ba<rs;ba++){const ln=dt+ba*Gs,zn=dt+(ba+1)*Gs,fd=Ee.filter(go=>go>=ln&&(ba===rs-1?go<=zn:go<zn)).length;bs.push({label:dl(Math.round(ln/1e3)*1e3),count:fd,binStart:ln,binEnd:zn})}return bs},[ht]),re=o.useMemo(()=>{const Ee={},dt=new Date;for(let ot=Ua-1;ot>=0;ot--){const xa=new Date(dt);xa.setMonth(xa.getMonth()-ot);const rs=`${xa.getFullYear()}-${String(xa.getMonth()+1).padStart(2,"0")}`,Gs=xa.toLocaleDateString("en-US",{month:"short",year:"2-digit"});Ee[rs]={month:Gs,soldCount:0,activeCount:0,totalDOM:0,domCount:0,ratios:[],salePrices:[],ppsfs:[],pendingCount:0,distressedSoldCount:0}}return Je.forEach(ot=>{const xa=ot.closeDate||ot.listDate;if(!xa)return;const rs=new Date(xa),Gs=`${rs.getFullYear()}-${String(rs.getMonth()+1).padStart(2,"0")}`;if(!Ee[Gs])return;const bs=ot.status.toLowerCase();bs.includes("sold")||bs.includes("closed")||bs==="clsd"?(Ee[Gs].soldCount++,ot.isDistressed&&Ee[Gs].distressedSoldCount++,ot.listPrice&&ot.salePrice&&Ee[Gs].ratios.push(ot.salePrice/ot.listPrice),ot.salePrice&&ot.salePrice>
40&&Ee[Gs].salePrices.push(ot.salePrice),ot.ppsf&&ot.ppsf>0&&Ee[Gs].ppsfs.push(ot.ppsf)):bs.includes("active")||bs==="actv"?Ee[Gs].activeCount++:(bs.includes("pending")||bs.includes("contract")||bs==="pend")&&Ee[Gs].pendingCount++,ot.dom!=null&&(Ee[Gs].totalDOM+=ot.dom,Ee[Gs].domCount++)}),Object.values(Ee).filter(ot=>ot.soldCount>0||ot.activeCount>0||ot.pendingCount>0).map(ot=>({month:ot.month,soldCount:ot.soldCount,activeCount:ot.activeCount,pendingCount:ot.pendingCount,avgDOM:ot.domCount>0?Math.round(ot.totalDOM/ot.domCount):null,absorptionRate:ot.soldCount+ot.activeCount>0?Math.round(ot.soldCount/(ot.soldCount+ot.activeCount)*100):0,saleToListRatio:ot.ratios.length>0?Math.round(rd(ot.ratios)*1e3)/10:null,medianPrice:ot.salePrices.length>0?Math.round(rd(ot.salePrices)):null,medianPPSF:ot.ppsfs.length>0?Math.round(rd(ot.ppsfs)):null,distressedSharePct:ot.soldCount>0?Math.round(ot.distressedSoldCount/ot.soldCount*1e3)/10:null}))},[Je,Ua]);o.useEffect(()=>{if(!G&&!U||re.length===0)return;const Ee=`${le.scope}|${le.dateRange}|${[...H].sort().join(",")}|${C||re.length}`;if(Ee!==ce.current)return Pe.current&&clearTimeout(Pe.current),Pe.current=setTimeout(()=>{ce.current=Ee,U?(async()=>{try{const dt={};for(const ot of H){if(!We[ot])continue;const xa=Le.current[ot]??null;if(!xa)continue;const rs=await Nw(xa);if(rs&&(dt[ot]=rs),A&&Object.keys(dt).length===Vd)break}Object.keys(dt).length>0&&U(dt,C)}catch(dt){console.error("[Market] Auto-capture (silent) failed:",dt)}})():Xt.current()},900),()=>{Pe.current&&clearTimeout(Pe.current)}},[G,U,re.length,H,We,le.scope,le.dateRange,C,A]),o.useMemo(()=>{const Ee={},dt=i?`${Math.floor(i/10)*10}s`:null;return ht.forEach(ot=>{if(ot.yearBuilt&&ot.yearBuilt>1800){const xa=`${Math.floor(ot.yearBuilt/10)*10}s`;Ee[xa]=(Ee[xa]||0)+1}}),Object.keys(Ee).sort().map(ot=>({decade:ot,count:Ee[ot],isSubject:ot===dt}))},[ht,i]);const qe=o.useMemo(()=>{const Ee=[{range:"0-15",min:0,max:15,count:0},{range:"16-30",min:16,max:30,count:0},{range:"31-60",min:31,max:60,count:0},{range:"61-90",min:61,max:90,count:0},{range:"90+",min:91,max:1/0,count:0}];return ht.forEach(dt=>{if(dt.dom!=null){const ot=Ee.find(xa=>dt.dom>=xa.min&&dt.dom<=xa.max);ot&&ot.count++}}),Ee.map(dt=>({range:dt.range,count:dt.count}))},[ht]),Ze=o.useMemo(()=>{const Ee=new Set;return re.some(dt=>dt.medianPrice!=null)&&Ee.add("priceTrend"),re.length>0&&(Ee.add("inventory"),Ee.add("absorptionRate")),qe.some(dt=>dt.count>0)&&Ee.add("domDistribution"),pt.length>0&&Ee.add("priceDistribution"),re.some(dt=>dt.saleToListRatio!=null)&&Ee.add("saleToList"),re.some(dt=>dt.medianPPSF!=null)&&Ee.add("ppsfTrend"),re.some(dt=>dt.avgDOM!=null)&&Ee.add("domTrend"),Ee},[qe,re,pt]),It=o.useMemo(()=>Object.fromEntries(H.filter(Ee=>Ze.has(Ee)).map(Ee=>[Ee,!!We[Ee]])),[H,Ze,We]),Ne=Object.values(It).filter(Boolean).length,Ue=Ne,ct=o.useCallback((Ee,dt)=>{A&&dt&&!jz(It,Ee)||Re(ot=>({...ot,[Ee]:dt}))},[A,It]),xt=o.useMemo(()=>{const Ee=ht.map(ba=>ba.gla).filter(ba=>ba!=null&&ba>0),dt=hg(Ee,"above-grade finished area");if(!dt||!l)return null;const ot=ht.filter(ba=>ba.gla!=null&&ba.gla>0).map(ba=>({id:ba.id,address:ba.address,value:ba.gla,tier:Yx(ba.gla,dt)})),xa=ot.filter(ba=>ba.tier==="green").length,rs=ot.filter(ba=>ba.tier==="yellow").length,Gs=ot.filter(ba=>ba.tier==="red").length,bs=XA(dt,l,"above-grade finished area");return{band:dt,compDots:ot,greenCount:xa,yellowCount:rs,redCount:Gs,narrative:bs}},[ht,l]),Na=o.useMemo(()=>{const Ee=ht.map(ba=>ba.lotSqft).filter(ba=>ba!=null&&ba>0),dt=hg(Ee,"site size");if(!dt||!c)return null;const ot=ht.filter(ba=>ba.lotSqft!=null&&ba.lotSqft>0).map(ba=>({id:ba.id,address:ba.address,value:ba.lotSqft,tier:Yx(ba.lotSqft,dt)})),xa=ot.filter(ba=>ba.tier==="green").length,rs=ot.filter(ba=>ba.tier==="yellow").length,Gs=ot.filter(ba=>ba.tier==="red").length,bs=XA(dt,c,"site size",{unit:"square feet",adjustmentNoun:"site size"});return{band:dt,compDots:ot,greenCount:xa,yellowCount:rs,redCount:Gs,narrative:bs}},[ht,c]),qt=o.useMemo(()=>{const Ee=ht.map(ba=>ba.yearBuilt).filter(ba=>ba!=null&&ba>1800),dt=hg(Ee,"year built");if(!dt||!i)return null;const ot=ht.filter(ba=>ba.yearBuilt!=null&&ba.yearBuilt>1800).map(ba=>({id:ba.id,address:ba.address,value:ba.yearBuilt,tier:Yx(ba.yearBuilt,dt)})),xa=ot.filter(ba=>ba.tier==="green").length,rs=ot.filter(ba=>ba.tier==="yellow").length,Gs=ot.filter(ba=>ba.tier==="red").length,bs=XA(dt,i,"year built",{unit:"years",adjustmentNoun:"age/condition"});return{band:dt,compDots:ot,greenCount:xa,yellowCount:rs,redCount:Gs,narrative:bs}},[ht,i]),[la,fs]=o.useState(!1),[ps,Te]=o.useState(!1),[at,yt]=o.useState(!1),[nt,Wt]=o.useState(!1);o.useCallback(()=>{xt?.narrative&&navigator.clipboard.writeText(xt.narrative).then(()=>
4{fs(!0),setTimeout(()=>fs(!1),2e3)})},[xt]),o.useCallback(()=>{Na?.narrative&&navigator.clipboard.writeText(Na.narrative).then(()=>{Te(!0),setTimeout(()=>Te(!1),2e3)})},[Na]),o.useCallback(()=>{qt?.narrative&&navigator.clipboard.writeText(qt.narrative).then(()=>{yt(!0),setTimeout(()=>yt(!1),2e3)})},[qt]);const ts=o.useMemo(()=>ea.soldCount===0&&ea.activeCount===0&&ea.pendingCount===0,[ea]),gs=o.useMemo(()=>{if(ts)return`Not enough closed sales or active listings in ${le.scope==="market"?"the broad market":"this submarket"} for the current selection to compute a market score. Adjust the date range, scope, or exclusion filters to bring in more data.`;const Ee=pr.propertyValues,dt=Ee==="Increasing"?"increased":Ee==="Declining"?"decreased":"remained stable",ot=dl(ea.priceMed),xa=ea.monthsOfSupply<3?"below the 4-month threshold typically associated with limited supply conditions":ea.monthsOfSupply<6?"within the 4-to-6-month range typically associated with balanced conditions":"above the 6-month threshold typically associated with elevated supply conditions",rs=[];Qt.outlierExcludedCount>0&&rs.push(`${Qt.outlierExcludedCount} ${Qt.outlierExcludedCount===1?"outlier":"outliers"} removed via IQR analysis on sale price and $/sqft`),Qt.manualExcludedCount>0&&rs.push(`${Qt.manualExcludedCount} manually excluded`);const Gs=rs.length>0?`, with ${rs.join(" and ")}`:"",bs=`Based on a ${Qt.dateRangeLabel} search of ${Qt.scopePhrase}, the appraiser identified ${Qt.preFilterCount} ${Qt.preFilterCount===1?"property":"properties"} returned by the search${Gs}.`;if(Qt.includedCount===0)return`${bs} No comparable properties remain after filtering, so market statistics cannot be summarized for this scope.`;const ba=`${Qt.includedCount} ${Qt.includedCount===1?"comp":"comps"} (${Qt.soldCount} closed, ${Qt.activeCount} active, ${Qt.pendingCount} pending)`;return Qt.soldCount===0?`${bs} The remaining ${ba} include no closed sales, so a median sale price cannot be reported. Current inventory stands at ${Qt.activeCount} active listings with ${Qt.pendingCount} pending.`:`${bs} Of the remaining ${ba}, the median sale price is ${ot}. Prices have ${dt} year-over-year. Current inventory stands at ${Qt.activeCount} active listings with ${Qt.pendingCount} pending. Median days on market is ${ea.medDOM} days. The sale-to-list price ratio is ${ea.medCloseToList!=null?ej(ea.medCloseToList):"—"}, and the absorption rate is ${ea.absorptionRate}%. Months of supply is ${Gx(ea.monthsOfSupply,1)}, which is ${xa}.`},[pr,ea,Qt]),Va=o.useCallback(()=>{gs&&navigator.clipboard.writeText(gs).then(()=>{Wt(!0),setTimeout(()=>Wt(!1),2e3)})},[gs]),Mr=o.useMemo(()=>{const Ee=re.filter(xa=>xa.medianPrice!=null);if(Ee.length<2)return 0;const dt=Ee[0].medianPrice,ot=Ee[Ee.length-1].medianPrice;return dt>0?Math.round((ot-dt)/dt*1e3)/10:0},[re]),{score:xs,label:Sn,insufficient:ds,breakdown:Zt}=o.useMemo(()=>Rz(ea,Mr,ts),[ea,Mr,ts]),[Rs,Os]=o.useState(!1),qs=le.excludedIds.length,Ks=Je.length,Tn=pr.demandSupply==="Shortage"?"Shortage":pr.demandSupply==="OverSupply"?"Over Supply":"In Balance",Bn=pr.marketingTime==="Under3Months"?"Under 3 mths":pr.marketingTime==="3to6Months"?"3-6 mths":"Over 6 mths",Ka=n&&l&&l>0?Math.round(n/l):void 0;return e.jsx(gr,{children:e.jsxs("div",{className:"flex flex-col w-full relative",style:{fontFamily:"'Inter', sans-serif",backgroundColor:ef,color:wr},"data-testid":"market-analytics-dashboard",children:[e.jsx("header",{className:"bg-white shrink-0",style:{borderBottom:`1px solid ${en}`},children:e.jsxs("div",{className:"flex items-center justify-between px-5 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-7 h-7 rounded flex items-center justify-center",style:{backgroundColor:wr},children:e.jsx(W0,{size:14,style:{color:Ws}})}),e.jsx("h1",{className:"text-[13px] font-semibold uppercase tracking-wide",style:{color:wr},children:"Market Analysis"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex p-0.5 rounded-md",style:{backgroundColor:`${en}80`,border:`1px solid ${en}`},children:["market","submarket"].map(Ee=>{const dt=Ee==="market"?s.length:r?.length||0,ot=Ee==="market"?"Broad Market":"Submarket";return e.jsx("button",{onClick:()=>W(xa=>({...xa,scope:Ee})),className:"px-3 py-1.5 rounded text-[13px] font-medium transition-all",style:{backgroundColor:le.scope===Ee?"#fff":"transparent",color:le.scope===Ee?wr:Es,boxShadow:le.scope===Ee?"0 1px 2px rgba(0,0,0,0.06)":"none"},"data-testid":`btn-scope-${Ee}`,children:dt>0?`${ot} (${dt})`:ot},Ee)})}),e.jsxs("button",{onClick:()=>ue(!fe),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-md text-[13px] font-medium transition-all",style:{border:`1px solid ${fe?Ws:en}`,backgroundColor:fe?`${Ws}15`:"transparent",color:fe?wr:Es},"data-testid":"btn-view-data",children:[e.jsx(Jx,{size:11}),"View Data",e.jsx("span",{className:"text-[11px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:en,color:Es},children:Ks})]}),e.jsx("div",{style:{width:1,height:20,backgroundColor:en}}),e.jsx("div",{className:"flex items-center gap-0.5 p-0.5 rounded-md",style:{backgroundColor:`${en}80`,border:`1px solid ${en}`},"data-testid":"date-range-toggle",children:["6mo","1yr","2yr","3yr"].map(Ee=>e.jsx("button",{className:"px-2.5 py-1 rounded text-[13px] font-medium transition-all",style:{backgroundColor:le.dateRange===Ee?"#fff":"transparent",color:le.dateRange===Ee?wr:Es,boxShadow:le.dateRange===Ee?"0 1px 2px rgba(0,0,0,0.06)":"none"},onClick:()=>W(dt=>({...dt,dateRange:Ee})),"data-testid":`btn-range-${Ee}`,children:Ee},Ee))}),e.jsxs("div",{className:"flex items-center gap-1.5 bg-white rounded-md px-3 py-1.5 text-[13px] font-medium",style:{border:`1px solid ${en}`,color:wr},"data-testid":"text-form-type",children:[e.jsx(gn,{size:11,style:{color:Ws}}),jw.find(Ee=>Ee.id===F)?.label??F]})]})]})}),fe&&e.jsx(Pz,{properties:_e,excludedSet:it,outlierIds:sa,toggleProperty:Ot,onRestoreAll:()=>W(Ee=>({...Ee,excludedIds:[],outliersHidden:!1})),toggleOutliers:$e,outliersHidden:le.outliersHidden,excludedCount:qs,handleSort:ma,sortField:le.sortField,sortDir:le.sortDir,scope:le.scope,onClose:()=>ue(!1)}),e.jsxs("main",{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"rounded-lg p-5 text-white",style:{background:`linear-gradient(135deg, ${wr} 0%, #0A2D47 100%)`},children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"text-3xl font-light tabular-nums","data-testid":"text-market-score",children:[ds?"—":xs,e.jsx("span",{className:"text-lg",style:{color:"rgba(255,255,255,0.8)"},children:"/100"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"text-[13px] font-medium uppercase tracking-wider",style:{color:Ws},children:"Market Score"}),e.jsx("button",{onClick:()=>Os(!Rs),className:"w-4 h-4 rounded-full flex items-center justify-center transition-colors hover:bg-white/20",style:{backgroundColor:Rs?"rgba(255,255,255,0.2)":"rgba(255,255,255,0.08)"},"data-testid":"btn-score-info",children:e.jsx(on,{size:9,style:{color:Ws}})})]}),e.jsx("div",{className:"text-[12px]",style:{color:"rgba(255,255,255,0.8)"}
4,children:le.scope==="market"?"Broad Market":"Submarket"})]}),e.jsx("div",{className:"ml-2 px-2 py-0.5 rounded text-[12px] font-medium",style:{backgroundColor:ds?"rgba(255,255,255,0.12)":(xs??0)>=60?"rgba(22,163,74,0.2)":(xs??0)>=40?"rgba(197,165,114,0.2)":"rgba(220,38,38,0.2)",color:ds?"rgba(255,255,255,0.85)":(xs??0)>=60?"#4ADE80":(xs??0)>=40?Ws:"#FCA5A5"},"data-testid":"text-market-score-label",children:Sn})]}),qs>0&&e.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[12px]",style:{backgroundColor:"rgba(217,119,6,0.15)",color:"#FBBF24"},children:[e.jsx(Ns,{size:10}),qs," excluded · ",Ks," remain",e.jsx("button",{onClick:()=>ue(!0),className:"underline ml-1 cursor-pointer",children:"View Data"})]})]}),Rs&&e.jsxs("div",{className:"rounded-md p-4 space-y-3 text-[13px]",style:{backgroundColor:"rgba(255,255,255,0.08)",border:"1px solid rgba(255,255,255,0.1)"},"data-testid":"panel-score-methodology",children:[e.jsx("div",{className:"font-medium text-[14px]",style:{color:Ws},children:"Score Breakdown"}),e.jsxs("div",{className:"space-y-2",children:[[{key:"monthsOfSupply",name:"Months of Supply",display:ds?"No input":`${Zt.monthsOfSupply.value.toFixed(1)} months`},{key:"saleToList",name:"Sale-to-List Ratio",display:ds?"No input":Zt.saleToList.value!=null?`${Zt.saleToList.value.toFixed(1)}%`:"N/A"},{key:"medianDOM",name:"Median DOM",display:ds?"No input":`${Math.round(Zt.medianDOM.value)} days`},{key:"absorptionRate",name:"Absorption Rate",display:ds?"No input":`${Math.round(Zt.absorptionRate.value)}%`},{key:"priceTrend",name:"Price Trend",display:ds?"No input":`${Zt.priceTrend.value>0?"+":""}${Zt.priceTrend.value.toFixed(1)}%`}].map(({key:Ee,name:dt,display:ot})=>{const xa=Zt[Ee];return e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{style:{color:"rgba(255,255,255,0.8)"},children:dt}),e.jsx("span",{className:"font-medium",style:{color:"rgba(255,255,255,0.9)"},children:ot})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{style:{color:"rgba(255,255,255,0.8)"},children:xa.label}),e.jsx("span",{className:"font-mono font-medium",style:{color:Ws},children:ds?`—/${xa.max}`:`${xa.points}/${xa.max}`})]})]},Ee)}),e.jsxs("div",{className:"flex items-center justify-between pt-2",style:{borderTop:"1px solid rgba(255,255,255,0.1)"},children:[e.jsx("span",{className:"font-medium",style:{color:"rgba(255,255,255,0.9)"},children:"Total Score"}),e.jsx("span",{className:"font-mono font-semibold text-[13px]",style:{color:Ws},children:ds?"—/100":`${xs}/100`})]})]}),e.jsxs("div",{className:"pt-2 space-y-1.5",style:{borderTop:"1px solid rgba(255,255,255,0.1)"},children:[e.jsx("div",{className:"font-medium",style:{color:Ws},children:"Score Ranges"}),e.jsx("div",{className:"grid grid-cols-5 gap-1",children:[{range:"80–100",label:"Strong Seller's",color:"#4ADE80"},{range:"60–79",label:"Mod. Seller's",color:"#86EFAC"},{range:"40–59",label:"Balanced",color:Ws},{range:"20–39",label:"Mod. Buyer's",color:"#FCA5A5"},{range:"0–19",label:"Strong Buyer's",color:"#F87171"}].map(Ee=>e.jsxs("div",{className:"text-center px-1 py-1 rounded",style:{backgroundColor:Sn===(Ee.range==="80–100"?"Strong Seller's Market":Ee.range==="60–79"?"Moderate Seller's Market":Ee.range==="40–59"?"Balanced Market":Ee.range==="20–39"?"Moderate Buyer's Market":"Strong Buyer's Market")?"rgba(255,255,255,0.12)":"transparent"},children:[e.jsx("div",{className:"text-[11px] font-mono",style:{color:Ee.color},children:Ee.range}),e.jsx("div",{className:"text-[10px]",style:{color:"rgba(255,255,255,0.8)"},children:Ee.label})]},Ee.range))})]}),e.jsxs("div",{className:"text-[11px] leading-relaxed",style:{color:"rgba(255,255,255,0.8)"},children:["Methodology based on NAR months-of-supply benchmarks, standard sale-to-list ratio thresholds, and DOM velocity norms used in residential market analysis.",ds?" No closed sales, active listings, or pending sales were found in the current scope, so each component is shown as no input rather than a scored value.":Zt.saleToList.value==null&&" Sale-to-list ratio data unavailable; a neutral mid-range value is applied pending sufficient closed sale data."]})]}),e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md text-[13px] leading-relaxed",style:{backgroundColor:"rgba(255,255,255,0.06)"}
4,children:[e.jsx(Ng,{size:10,className:"mt-0.5 shrink-0",style:{color:Ws}}),e.jsx("p",{className:"flex-1",style:{color:"rgba(255,255,255,0.8)"},"data-testid":"text-market-summary",children:gs}),e.jsxs("button",{onClick:Va,className:"shrink-0 flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-medium transition-colors",style:{backgroundColor:nt?"rgba(16,185,129,0.18)":"rgba(255,255,255,0.08)",color:nt?"#4ADE80":"rgba(255,255,255,0.85)",border:`1px solid ${nt?"#4ADE80":"rgba(255,255,255,0.15)"}`},"data-testid":"btn-copy-market-summary",title:"Copy narrative to clipboard",children:[nt?e.jsx(kr,{className:"w-3 h-3"}):e.jsx(jr,{className:"w-3 h-3"}),nt?"Copied!":"Copy"]})]})]}),e.jsxs("div",{className:"rounded-lg p-4 space-y-3",style:{border:`1px solid ${en}`,backgroundColor:"#FEFDFB"},"data-testid":"panel-search-criteria",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pf,{size:12,style:{color:Ws}}),e.jsx("span",{className:"text-[12px] font-semibold uppercase tracking-wider",style:{color:wr},children:"Search Criteria"}),e.jsxs("span",{className:"text-[11px]",style:{color:Es},children:["· ",Qt.scopeLabel]})]}),e.jsxs("dl",{className:"grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-1.5 text-[12px]",children:[e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("dt",{style:{color:Es},children:"Date range"}),e.jsx("dd",{className:"font-medium text-right",style:{color:wr},"data-testid":"text-criteria-date-range",children:Qt.dateRangeLabel.charAt(0).toUpperCase()+Qt.dateRangeLabel.slice(1)})]}),e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("dt",{style:{color:Es},children:"Geographic scope"}),e.jsx("dd",{className:"font-medium text-right",style:{color:wr},"data-testid":"text-criteria-geometry",children:Qt.geometryLabel})]}),e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("dt",{style:{color:Es},children:"Properties returned by search"}),e.jsx("dd",{className:"font-medium text-right tabular-nums",style:{color:wr},"data-testid":"text-criteria-pre-filter-count",children:Qt.preFilterCount})]}),e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("dt",{style:{color:Es},children:"Outlier rule (IQR on sale price & $/sqft)"}),e.jsx("dd",{className:"font-medium text-right tabular-nums",style:{color:wr},"data-testid":"text-criteria-outliers-removed",children:Qt.outliersHidden?`${Qt.outlierExcludedCount} removed`:"Disabled"})]}),e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("dt",{style:{color:Es},children:"Manually excluded comps"}),e.jsx("dd",{className:"font-medium text-right tabular-nums",style:{color:wr},"data-testid":"text-criteria-manual-excluded",children:Qt.manualExcludedCount})]}),e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("dt",{style:{color:Es},children:"Final included comps"}),e.jsxs("dd",{className:"font-medium text-right tabular-nums",style:{color:wr},"data-testid":"text-criteria-included-count",children:[Qt.includedCount,e.jsxs("span",{className:"ml-1 text-[11px]",style:{color:Es},children:["(",Qt.soldCount," sold · ",Qt.activeCount," active · ",Qt.pendingCount," pending)"]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3","data-testid":"kpi-cards",children:[e.jsx(dS,{label:"Median Sale Price",value:dl(ea.priceMed),trend:Mr,sub:`List: ${dl(ea.medListPrice)}`}),e.jsx(dS,{label:"Median DOM",value:`${ea.medDOM} days`,trend:null,sub:`Avg: ${ea.avgDOM} days`,inverseTrend:!0}),e.jsx(dS,{label:"SP/LP Ratio",value:ea.medCloseToList!=null?ej(ea.medCloseToList):"—",trend:null,sub:`${ea.soldCount} closed sales`}),e.jsx(dS,{label:"Months of Supply",value:Gx(ea.monthsOfSupply,1),trend:null,sub:`${Tn} · ${Bn}`,inverseTrend:!0})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 shadow-sm",style:{border:`1px solid ${en}`},"data-testid":"market-activity-row",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold mb-2",style:{color:Es},children:"Market Activity"}),e.jsxs("div",{className:"grid grid-cols-3 md:grid-cols-6 gap-2",children:[e.jsx(px,{label:"New Listings",value:tr.newListings!=null?String(tr.newListings):"N/A",testId:"indicator-new-listings",tooltip:tr.newListings!=null?"Currently active listings that hit the market within the selected date range — always a subset of the Active count. Rising new-listing counts add supply and can soften prices.":"List dates are not available for this pool, so new listings cannot be counted."}),e.jsx(px,{label:"Active",value:String(tr.active),testId:"indicator-active-count",tooltip:"Everything currently listed and available (active status) in the filtered pool."}),e.jsx(px,{label:"Under Contract",value:String(tr.underContract),testId:"indicator-under-contract",tooltip:`Listings with an accepted offer that haven't closed — pending, contingent, and under-contract statuses combined.${tr.active>0?` That's ${Gx(tr.underContract/tr.active,2)} under contract per active listing; above ~1.0 means demand is outpacing available supply.`:""}`}),e.jsx(px,{label:"Total Sold",value:String(ea.soldCount),testId:"indicator-sold-count",tooltip:"
4Closed sales in the current filtered pool and date range."}),e.jsx(px,{label:"Absorption Rate",value:`${ea.absorptionRate}%`,testId:"indicator-absorption-rate",tooltip:"Share of inventory being absorbed (sold ÷ sold + active). Higher absorption supports an Increasing/Shortage conclusion."}),e.jsx(px,{label:"Distressed",value:tr.distressedSharePct!=null?ej(tr.distressedSharePct):"—",testId:"indicator-distressed-share",tooltip:"Share of the pool that is REO, foreclosure, or short-sale. A meaningful distressed share can drag values and must be addressed in the report."})]})]}),e.jsxs("div",{className:"bg-white rounded-lg p-3 shadow-sm",style:{border:`1px solid ${en}`},"data-testid":"subject-vs-market",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 gap-2 flex-wrap",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold",style:{color:Es},children:"Subject vs. Market"}),ir.conclusion!=="unknown"&&e.jsx("span",{className:"text-[11px] font-semibold px-2 py-0.5 rounded-full",style:{color:ir.conclusion==="conforms"?M0:ey,backgroundColor:ir.conclusion==="conforms"?"#F0FDF4":"#FDF8EF",border:`1px solid ${ir.conclusion==="conforms"?"#BBF7D0":"#EADFC8"}`},"data-testid":"badge-subject-fit",children:ir.conclusion==="conforms"?"Conforms to market":ir.conclusion==="over-improvement"?"Potential over-improvement":"Potential under-improvement"})]}),ir.conclusion==="unknown"?e.jsx("div",{className:"text-[12px]",style:{color:Es},"data-testid":"text-subject-fit-unavailable",children:"Subject details not available"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:ir.attributes.map(Ee=>e.jsx(wz,{attr:Ee},Ee.key))}),e.jsx("div",{className:"text-[11px] mt-2",style:{color:Es},"data-testid":"text-subject-fit-explanation",children:ir.explanation})]})]}),zs&&e.jsxs("div",{className:"bg-white rounded-lg p-3 shadow-sm flex items-center gap-3 flex-wrap",style:{border:`1px solid ${en}`},"data-testid":"subject-marketing-time",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold",style:{color:Es},children:"Subject Marketing Time"}),u?.isPrior&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-semibold px-1.5 py-0.5 rounded",style:{color:Es,backgroundColor:"#F1F5F9",border:`1px solid ${en}`},"data-testid":"badge-subject-prior-listing",children:"Prior listing"}),e.jsxs("div",{className:"text-[13px]",style:{color:wr},"data-testid":"text-subject-dom",children:[e.jsxs("span",{className:"font-semibold tabular-nums",children:[zs.subjectDom," days"]}),e.jsxs("span",{style:{color:Es},children:[" on market",u?.status?` (${u.status})`:""," · market median ",zs.marketMedianDom," days"]})]}),e.jsx("span",{className:"text-[11px] font-semibold px-2 py-0.5 rounded-full",style:{color:zs.inRange?M0:kv,backgroundColor:zs.inRange?"#F0FDF4":"#FEF2F2",border:`1px solid ${zs.inRange?"#BBF7D0":"#FECACA"}`},"data-testid":"badge-subject-dom-range",children:zs.inRange?"Within typical marketing time":`Exceeds typical marketing time (≤${zs.typicalUpperBound} days)`})]}),le.scope==="submarket"&&e.jsx(Oz,{localBoundaries:Xa,localDescription:os,localConditions:At,handleNbhdFieldChange:$t,handleGenerateNbhd:na,isGeneratingNbhd:Oe,neighborhoodAiGenerated:N,subjectAddress:y}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-[13px] font-semibold uppercase tracking-wide",style:{color:wr},children:"Charts"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>se(!pe),className:"flex items-center gap-1.5 text-[13px] font-medium transition-colors",style:{color:Ws},"data-testid":"btn-add-charts",children:[e.jsx(un,{size:14})," Add Charts"]}),e.jsx("button",{onClick:()=>ua(H),className:"flex items-center gap-1.5 text-[12px] font-medium px-2 py-1 rounded-md transition-colors",style:{border:`1px solid ${Be?"#22c55e":en}`,color:Be?"#22c55e":Es},"data-testid":"btn-save-chart-defaults",disabled:Be,children:Be?e.jsxs(e.Fragment,{children:[e.jsx(kr,{size:12})," Saved!"]}):"Save as Default"}),G&&(ne||lt)&&e.jsx("span",{className:"flex items-center gap-1 text-[11px] font-medium",style:{color:lt?"#22c55e":Es},"data-testid":"badge-auto-capture-status",children:lt?e.jsxs(e.Fragment,{children:[e.jsx(kr,{size:11})," Charts applied"]}):"Applying charts…"}),A&&e.jsxs("span",{className:"text-[11px]",style:{color:Es},"data-testid":"eval-pdf-chart-limit",children:["Choose up to ",Vd," charts for the PDF"]}),G&&e.jsx("button",{onClick:st,disabled:Ne===0||ne,className:"flex items-center gap-1.5 text-[12px] font-medium px-2.5 py-1 rounded-md transition-colors",style:{border:`1px solid ${lt?"#22c55e":Ne>0?wr:en}`,backgroundColor:lt?"#F0FDF4":Ne>0?wr:"transparent",color:lt?"#22c55e":Ne>0?"#fff":Es,opacity:Ne===0?.5:1,cursor:Ne===0?"not-allowed":"pointer"},"data-testid":"btn-apply-charts-to-report",children:lt?e.jsxs(e.Fragment,{children:[e.jsx(kr,{size:12})," Applied!"]}):ne?"Capturing…":e.jsxs(e.Fragment,{children:[e.jsx(gn,{size:12})," Apply to Report",Ne>0?` (${Ne})`:""]})})]})]}),pe&&e.jsxs("div",{className:"bg-white rounded-lg p-4 space-y-2",style:{border:`1px solid ${en}`},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-[13px] font-semibold uppercase tracking-wide",style:{color:wr},children:"Available Charts"}),e.jsx("button",{onClick:()=>se(!1),className:"p-1 rounded hover:bg-[#f0ede8]",children:e.jsx(ur,{size:14,style:{color:Es}})})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Qf.map(Ee=>{const dt=H.includes(Ee.id);return e.jsxs("button",{onClick:()=>Oa(Ee.id),className:"flex items-start gap-2.5 p-2.5 rounded-md text-left transition-all",style:{border:`1px solid ${dt?Ws:en}`,backgroundColor:dt?`${Ws}08`:"#fff",opacity:Ee.alwaysOn?.7:1},"data-testid":`chart-toggle-${Ee.id}`,children:[e.jsx("div",{className:"w-4 h-4 rounded border flex items-center justify-center mt-0.5 shrink-0",style:{borderColor:dt?Ws:en,backgroundColor:dt?Ws:"transparent"},children:dt&&e.jsx("span",{className:"text-white text-[11px]",children:"✓"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[13px] font-medium",style:{color:wr},children:[Ee.label,Ee.alwaysOn&&e.jsx("span",{className:"text-[11px] ml-1",style:{color:Es},children:"(always on)"})]}),e.jsx("div",{className:"text-[11px]",style:{color:Es},children:Ee.appraiserNote})]})]},Ee.id)})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[H.includes("priceTrend")&&re.some(Ee=>Ee.medianPrice!=null)&&e.jsx(yh,{title:"Price Trends",description:"Median sale price over time",chartId:"priceTrend",included:!!We.priceTrend,onToggleInclusion:ct,inclusionDisabled:A&&!We.priceTrend&&Ue>=Vd,scopeLabel:le.scope==="market"?"Broad Market":"Submarket",containerRef:ut("priceTrend"),children:e.jsx("div",{className:"h-[200px]","data-testid":"chart-price-trend",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(Fh,{data:re.filter(Ee=>Ee.medianPrice!=null),margin:{top:5,right:10,left:10,bottom:5},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"priceAreaGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Oo,stopOpacity:.15}),e.jsx("stop",{offset:"100%",stopColor:Oo,stopOpacity:.02})]})}),e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"month",tick:{fontSize:11,fill:Es}
4,axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"},tickFormatter:Ee=>`$${(Ee/1e3).toFixed(0)}K`}),e.jsx(uc,{content:e.jsx(bh,{formatter:Ee=>dl(Ee)})}),e.jsx(KS,{type:"monotone",dataKey:"medianPrice",fill:"url(#priceAreaGrad)",stroke:"none",name:"Median Price"}),e.jsx(np,{type:"monotone",dataKey:"medianPrice",stroke:Oo,strokeWidth:2,name:"Median Price",dot:{r:3,fill:Oo},activeDot:{r:5,fill:Ws}}),n&&e.jsx(wu,{y:n,stroke:Ws,strokeDasharray:"5 5",strokeWidth:1.5,label:{value:`Subject: ${dl(n)}`,position:"right",fontSize:11,fill:Ws}})]})})})}),H.includes("inventory")&&re.length>0&&e.jsx(yh,{title:"Inventory Activity",description:"Active, sold & pending listings",chartId:"inventory",included:!!We.inventory,onToggleInclusion:ct,inclusionDisabled:A&&!We.inventory&&Ue>=Vd,scopeLabel:le.scope==="market"?"Broad Market":"Submarket",containerRef:ut("inventory"),children:e.jsx("div",{className:"h-[200px]","data-testid":"chart-inventory",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(QS,{data:re,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"month",tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(uc,{content:e.jsx(bh,{})}),e.jsx(Xj,{wrapperStyle:{fontSize:11}}),e.jsx(Rh,{dataKey:"soldCount",fill:Oo,name:"Sold",radius:[2,2,0,0]}),e.jsx(Rh,{dataKey:"activeCount",fill:"#93C5FD",name:"Active",radius:[2,2,0,0]}),e.jsx(Rh,{dataKey:"pendingCount",fill:Ws,name:"Pending",radius:[2,2,0,0]})]})})})}),H.includes("domDistribution")&&qe.some(Ee=>Ee.count>0)&&e.jsx(yh,{title:"Days on Market",description:"How long homes sit before selling",chartId:"domDistribution",included:!!We.domDistribution,onToggleInclusion:ct,inclusionDisabled:A&&!We.domDistribution&&Ue>=Vd,scopeLabel:le.scope==="market"?"Broad Market":"Submarket",containerRef:ut("domDistribution"),children:e.jsx("div",{className:"h-[200px]","data-testid":"chart-dom-distribution",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(QS,{data:qe,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"range",tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(uc,{content:e.jsx(bh,{formatter:Ee=>`${Ee} sales`})}),e.jsx(Rh,{dataKey:"count",name:"Sales",radius:[3,3,0,0],children:qe.map((Ee,dt)=>e.jsx($x,{fill:dt<2?M0:dt<3?Ws:Oo},dt))})]})})})}),H.includes("priceDistribution")&&pt.length>0&&e.jsx(yh,{title:"Price Distribution",description:`${ea.soldCount} sales`,chartId:"priceDistribution",included:!!We.priceDistribution,onToggleInclusion:ct,inclusionDisabled:A&&!We.priceDistribution&&Ue>=Vd,scopeLabel:le.scope==="market"?"Broad Market":"Submarket",containerRef:ut("priceDistribution"),children:e.jsx("div",{className:"h-[200px]","data-testid":"chart-price-distribution",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(QS,{data:pt,margin:{top:10,right:10,left:10,bottom:5},children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"navyGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Oo,stopOpacity:.9}),e.jsx("stop",{offset:"100%",stopColor:Oo,stopOpacity:.6})]}),e.jsxs("linearGradient",{id:"goldGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Ws,stopOpacity:.9}),e.jsx("stop",{offset:"100%",stopColor:Ws,stopOpacity:.6})]})]}),e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"label",tick:{fontSize:11,fill:Es},angle:-30,textAnchor:"end",height:50,axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(uc,{content:e.jsx(bh,{})}),e.jsx(Rh,{dataKey:"count",radius:[3,3,0,0],children:pt.map((Ee,dt)=>e.jsx($x,{fill:n&&n>=Ee.binStart&&n<Ee.binEnd?"url(#goldGrad)":"url(#navyGrad)"},dt))})]})})})}),H.includes("saleToList")&&re.some(Ee=>Ee.saleToListRatio!=null)&&e.jsx(yh,{title:"Sale-to-List Ratio",description:"Negotiation trends over time",chartId:"saleToList",included:!!We.saleToList,onToggleInclusion:ct,inclusionDisabled:A&&!We.saleToList&&Ue>=Vd,scopeLabel:le.scope==="market"?"Broad Market":"Submarket",containerRef:ut("saleToList"),children:e.jsx("div",{className:"h-[200px]","data-testid":"chart-sale-to-list",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(xI,{data:re.filter(Ee=>Ee.saleToListRatio!=null),margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"month",tick:{fontSize:11,fill:Es}
4,axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{tick:{fontSize:11,fill:Es},unit:"%",domain:["auto","auto"],axisLine:{stroke:"#cbd5e1"}}),e.jsx(uc,{content:e.jsx(bh,{formatter:Ee=>`${Ee}%`})}),e.jsx(np,{type:"monotone",dataKey:"saleToListRatio",stroke:Oo,strokeWidth:2,name:"SP/LP %",dot:{r:3,fill:Oo},activeDot:{r:5,fill:Ws},connectNulls:!0})]})})})}),H.includes("absorptionRate")&&re.length>0&&e.jsx(yh,{title:"Absorption & Supply",description:"How fast homes are being absorbed",chartId:"absorptionRate",included:!!We.absorptionRate,onToggleInclusion:ct,inclusionDisabled:A&&!We.absorptionRate&&Ue>=Vd,scopeLabel:le.scope==="market"?"Broad Market":"Submarket",containerRef:ut("absorptionRate"),children:e.jsx("div",{className:"h-[200px]","data-testid":"chart-absorption-rate",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(Fh,{data:re,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"month",tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{yAxisId:"left",tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{yAxisId:"right",orientation:"right",tick:{fontSize:11,fill:Es},unit:"%",axisLine:{stroke:"#cbd5e1"}}),e.jsx(uc,{content:e.jsx(bh,{})}),e.jsx(Xj,{wrapperStyle:{fontSize:11}}),e.jsx(Rh,{yAxisId:"left",dataKey:"activeCount",fill:"#93C5FD",name:"Active",radius:[2,2,0,0]}),e.jsx(Rh,{yAxisId:"left",dataKey:"soldCount",fill:Oo,name:"Sold",radius:[2,2,0,0]}),e.jsx(np,{yAxisId:"right",type:"monotone",dataKey:"absorptionRate",stroke:Ws,strokeWidth:2,name:"Rate %",dot:!1})]})})})}),H.includes("ppsfTrend")&&re.some(Ee=>Ee.medianPPSF!=null)&&e.jsx(yh,{title:"Price Per Sq Ft",description:"PPSF trend over time",chartId:"ppsfTrend",included:!!We.ppsfTrend,onToggleInclusion:ct,inclusionDisabled:A&&!We.ppsfTrend&&Ue>=Vd,scopeLabel:le.scope==="market"?"Broad Market":"Submarket",containerRef:ut("ppsfTrend"),children:e.jsx("div",{className:"h-[200px]","data-testid":"chart-ppsf-trend",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(Fh,{data:re.filter(Ee=>Ee.medianPPSF!=null),margin:{top:5,right:10,left:10,bottom:5},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"ppsfAreaGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Oo,stopOpacity:.15}),e.jsx("stop",{offset:"100%",stopColor:Oo,stopOpacity:.02})]})}),e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"month",tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"},tickFormatter:Ee=>`$${Ee}`}),e.jsx(uc,{content:e.jsx(bh,{formatter:Ee=>`${dl(Ee)}/sqft`})}),e.jsx(KS,{type:"monotone",dataKey:"medianPPSF",fill:"url(#ppsfAreaGrad)",stroke:"none",name:"Med PPSF"}),e.jsx(np,{type:"monotone",dataKey:"medianPPSF",stroke:Oo,strokeWidth:2,name:"Med PPSF",dot:{r:3,fill:Oo},activeDot:{r:5,fill:Ws}}),Ka&&e.jsx(wu,{y:Ka,stroke:Ws,strokeDasharray:"5 5",strokeWidth:1.5,label:{value:`Subject: ${dl(Ka)}/sqft`,position:"right",fontSize:11,fill:Ws}})]})})})}),H.includes("domTrend")&&re.some(Ee=>Ee.avgDOM!=null)&&e.jsx(yh,{title:"DOM Trend",description:"Marketing time trends",chartId:"domTrend",included:!!We.domTrend,onToggleInclusion:ct,inclusionDisabled:A&&!We.domTrend&&Ue>=Vd,scopeLabel:le.scope==="market"?"Broad Market":"Submarket",containerRef:ut("domTrend"),children:e.jsx("div",{className:"h-[200px]","data-testid":"chart-dom-trend",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(Fh,{data:re.filter(Ee=>Ee.avgDOM!=null),margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"domAreaGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:Oo,stopOpacity:.15}),e.jsx("stop",{offset:"100%",stopColor:Oo,stopOpacity:.02})]})}),e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"month",tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{tick:{fontSize:11,fill:Es},axisLine:{stroke:"#cbd5e1"}}),e.jsx(uc,{content:e.jsx(bh,{formatter:Ee=>`${Ee} days`})}),e.jsx(KS,{type:"monotone",dataKey:"avgDOM",fill:"url(#domAreaGrad)",stroke:"none"}),e.jsx(np,{type:"monotone",dataKey:"avgDOM",stroke:Oo,strokeWidth:2,name:"Avg DOM",dot:{r:3,fill:Oo},activeDot:{r:5,fill:Ws}})]})})})})]})]}),e.jsxs("div",{className:"sticky bottom-0 bg-white shadow-[0_-8px_30px_rgba(0,0,0,0.06)] transition-all duration-300 flex flex-col z-20",style:{borderTop:`1px solid ${en}`},children:[e.jsxs("button",{onClick:()=>Z(!me),className:"flex-none h-[52px] w-full px-6 flex items-center justify-between transition-colors",style:{":hover":{backgroundColor:ef}},"data-testid":"btn-toggle-form-drawer",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full flex items-center justify-center",style:{backgroundColor:en},children:e.jsx(mN,{size:12,style:{color:wr}})}),e.jsxs("h2",{className:"text-[12px] font-semibold uppercase tracking-wide",style:{color:wr},children:[jw.find(Ee=>Ee.id===F)?.label??F," Fields"]}),e.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:en,color:Es}
4,children:le.scope==="market"?"Broad Market":"Submarket"})]}),e.jsx("span",{className:"flex items-center gap-1 text-[12px] font-medium",style:{color:Ws},children:me?e.jsxs(e.Fragment,{children:["Collapse ",e.jsx(Rr,{size:13})]}):e.jsxs(e.Fragment,{children:["Review Fields ",e.jsx(Du,{size:13})]})})]}),me&&e.jsx("div",{className:"overflow-auto px-6 py-4 space-y-4",style:{backgroundColor:ef,maxHeight:"min(60vh, 500px)"},children:e.jsx(Fz,{derivedFormFields:pr,computedStats:ea,demandLabel:Tn,marketTimeLabel:Bn,formType:F,uad36Editable:B,uad36Overrides:oe,onUad36OverrideChange:$})})]})]})})}function dS({label:t,value:a,trend:s,sub:r,inverseTrend:n}){const i=s!==null&&s>0,l=s!==null?n?!i:i:null;return e.jsxs("div",{className:"bg-white rounded-lg p-3.5 shadow-sm",style:{border:`1px solid ${en}`},"data-testid":`kpi-${t.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wider font-medium mb-1",style:{color:Es},children:t}),e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"text-xl font-semibold",style:{color:wr},children:a}),s!==null&&e.jsxs("span",{className:"flex items-center gap-0.5 text-[11px] font-medium",style:{color:l?M0:kv},children:[i?e.jsx(YO,{size:12}):e.jsx(GO,{size:12}),Math.abs(s),"%"]})]}),e.jsx("div",{className:"text-[11px] mt-1",style:{color:Es},children:r})]})}function px({label:t,value:a,tooltip:s,testId:r}){return e.jsx(gr,{delayDuration:200,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("div",{className:"rounded-md px-2.5 py-2 text-center cursor-default",style:{border:`1px solid ${en}`,backgroundColor:ef},"data-testid":r,children:[e.jsx("div",{className:"text-[15px] font-semibold tabular-nums",style:{color:wr},children:a}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-medium",style:{color:Es},children:t})]})}),e.jsx(Wa,{side:"bottom",className:"max-w-[260px] text-[11px]",children:s})]})})}function wz({attr:t}){const a=n=>t.key==="gla"?Math.round(n).toLocaleString():t.key==="baths"?Gx(Math.round(n*2)/2,1):String(Math.round(n)),s=t.direction==="within"?M0:ey,r=t.band;return t.noData||t.subjectValue==null||t.typicalValue==null?e.jsxs("div",{className:"rounded-md px-2.5 py-2",style:{border:`1px solid ${en}`,backgroundColor:ef},"data-testid":`fit-attr-${t.key}`,children:[e.jsx("div",{className:"flex items-center justify-between gap-1",children:e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-medium",style:{color:Es},children:t.label})}),e.jsx("div",{className:"text-[13px] font-semibold",style:{color:Es},"data-testid":`fit-no-data-${t.key}`,children:"No data"}),e.jsx("div",{className:"text-[10px]",style:{color:Es},"data-testid":`fit-band-unavailable-${t.key}`,children:"Market range unavailable"})]}):e.jsxs("div",{className:"rounded-md px-2.5 py-2",style:{border:`1px solid ${en}`,backgroundColor:ef},"data-testid":`fit-attr-${t.key}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider font-medium",style:{color:Es},children:t.label}),e.jsx("div",{className:"text-[10px] font-medium",style:{color:s},children:t.direction==="within"?"Within range":t.direction==="above"?"Above typical":"Below typical"})]}),e.jsxs("div",{className:"text-[13px] font-semibold tabular-nums",style:{color:wr},children:[t.key==="gla"?t.subjectValue.toLocaleString():t.key==="baths"?Gx(t.subjectValue,1):String(t.subjectValue),e.jsxs("span",{className:"font-normal text-[11px]",style:{color:Es},children:[" vs ",a(t.typicalValue)," typical"]})]}),r?e.jsxs("div",{className:"mt-1.5","data-testid":`fit-band-${t.key}`,children:[e.jsxs("div",{className:"relative h-[14px]",children:[e.jsx("div",{className:"absolute left-0 right-0 top-1/2 -translate-y-1/2 h-[3px] rounded-full",style:{backgroundColor:en}}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 h-[7px] rounded-full",style:{left:`${$b(r.low,r)*100}%`,width:`${Math.max(0,($b(r.high,r)-$b(r.low,r))*100)}%`,backgroundColor:"#D6E8DC",border:"1px solid #A7CDB4"}}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 w-[2px] h-[11px] rounded-sm",style:{left:`calc(${$b(r.median,r)*100}% - 1px)`,backgroundColor:Oo,opacity:.75},"data-testid":`fit-median-${t.key}`}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 w-[9px] h-[9px] rounded-full",style:{left:`calc(${$b(t.subjectValue,r)*100}% - 4.5px)`,backgroundColor:s,border:"1.5px solid #FFFFFF",boxShadow:"0 0 0 1px rgba(0,0,0,0.15)"},"data-testid":`fit-marker-${t.key}`})]}),e.jsxs("div",{className:"flex justify-between text-[9px] tabular-nums leading-none",style:{color:Es},children:[e.jsx("span",{"data-testid":`fit-band-low-${t.key}`,children:a(r.low)}),e.jsx("span",{"data-testid":`fit-band-high-${t.key}`,children:a(r.high)})]})]}):e.jsx("div",{className:"text-[10px]",style:{color:Es},"data-testid":`fit-band-unavailable-${t.key}`,children:"Market range unavailable"})]})}function yh({title:t,description:a,children:s,fullWidth:r,chartId:n,included:i,onToggleInclusion:l,scopeLabel:c,containerRef:d,inclusionDisabled:p}){return e.jsxs("div",{ref:d,className:`bg-white rounded-lg p-4 shadow-sm ${r?"col
4-span-1 lg:col-span-2":""}`,style:{border:`1px solid ${i?Ws:en}`},children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[13px] font-semibold uppercase tracking-wide",style:{color:wr},children:t}),e.jsx("p",{className:"text-[11px]",style:{color:Es},children:a})]}),n&&l&&e.jsxs("label",{className:`flex items-center gap-1.5 select-none shrink-0 ml-3 ${p?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[e.jsx("input",{type:"checkbox",className:"w-3.5 h-3.5 rounded accent-[#C5A572] cursor-pointer disabled:cursor-not-allowed",checked:!!i,disabled:p,onChange:u=>l(n,u.target.checked),"aria-label":`Include ${t} in report`,"data-testid":`chart-include-${n}`}),e.jsx("span",{className:"text-[11px] font-medium",style:{color:i?ey:Es},children:"Include in report"}),i&&c&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-medium",style:{backgroundColor:`${Ws}18`,color:ey,border:`1px solid ${Ws}40`},children:c})]})]}),s]})}function Pz({properties:t,excludedSet:a,outlierIds:s,toggleProperty:r,onRestoreAll:n,toggleOutliers:i,outliersHidden:l,excludedCount:c,handleSort:d,sortField:p,sortDir:u,scope:m,onClose:h}){const f=t.filter(v=>!a.has(v.id)).length;return e.jsxs("div",{className:"bg-white shrink-0 max-h-[50vh] flex flex-col",style:{borderBottom:`1px solid ${en}`},children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-2.5 shrink-0",style:{backgroundColor:ef,borderBottom:`1px solid ${en}`},children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("h3",{className:"text-[11px] font-semibold uppercase tracking-wide",style:{color:wr},children:["Sales Data · ",m==="market"?"Broad Market":"Submarket"]}),e.jsxs("span",{className:"text-[11px] px-2 py-0.5 rounded-full",style:{backgroundColor:en,color:Es},children:[f," of ",t.length]}),c>0&&e.jsxs("span",{className:"flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full",style:{backgroundColor:"#FEF3C7",color:"#D97706"},children:[e.jsx(Ns,{size:9})," Stats recalculated"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:i,className:"flex items-center gap-1 px-2.5 py-1 rounded-md text-[12px] font-medium transition-colors",style:{border:`1px solid ${l?Ws:en}`,backgroundColor:l?`${Ws}12`:"transparent",color:l?ey:Es},"data-testid":"btn-toggle-outliers",children:[e.jsx(pf,{size:10})," ",l?`Outliers Hidden (${s.size})`:"Show Outliers"]}),c>0&&e.jsxs("button",{onClick:n,className:"flex items-center gap-1 px-2.5 py-1 rounded-md text-[12px] font-medium transition-colors",style:{border:`1px solid ${en}`,color:Es},"data-testid":"btn-restore-all",children:[e.jsx(bg,{size:10})," Restore All"]}),e.jsx("button",{onClick:h,className:"p-1 rounded hover:bg-[#f0ede8]","data-testid":"btn-close-data-table",children:e.jsx(ur,{size:14,style:{color:Es}})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto","data-testid":"properties-table",children:e.jsxs("table",{className:"w-full text-[11px]",style:{fontVariantNumeric:"tabular-nums"},children:[e.jsx("thead",{className:"sticky top-0 z-10",style:{backgroundColor:wr},children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-2 py-1.5 text-left w-8 text-[11px] font-medium text-white/80 uppercase",children:"Excl."}),[{key:"address",label:"Address"},{key:"status",label:"Status"},{key:"listPrice",label:"List Price"},{key:"salePrice",label:"Sale Price"},{key:"ppsf",label:"$/SqFt"},{key:"dom",label:"DOM"},{key:"gla",label:"GLA"},{key:"beds",label:"Bd"},{key:"baths",label:"Ba"},{key:"yearBuilt",label:"Yr Built"}].map(v=>e.jsx("th",{className:"px-2 py-1.5 text-left font-medium text-white/80 cursor-pointer hover:text-white whitespace-nowrap text-[12px] uppercase tracking-wider",onClick:()=>d(v.key),children:e.jsxs("span",{className:"flex items-center gap-0.5",children:[v.label,p===v.key&&e.jsx(hN,{className:"w-2.5 h-2.5"})]})},v.key))]})}),e.jsxs("tbody",{children:[t.map((v,S)=>{const N=a.has(v.id),x=s.has(v.id);return e.jsxs("tr",{className:`border-t transition-colors ${N?"opacity-40":"hover:bg-[#F0EDE8]"}`,style:{borderColor:"#E8E4DF",backgroundColor:N?"#f8f7f5":S%2===0?"#fff":ef},"data-testid":`row-property-${v.id}`,children:[e.jsx("td",{className:"px-2 py-1",children:e.jsx("button",{onClick:()=>r(v.id),className:"w-5 h-5 rounded-full flex items-center justify-center transition-colors",style:{backgroundColor:N?"#f0ede8":`${kv}15`,color:N?Es:kv},"data-testid":`btn-exclude-${v.id}`,children:N?e.jsx(un,{size:10}):e.jsx(nf,{size:10})})}),e.jsx("td",{className:"px-2 py-1 max-w-[160px] truncate font-medium",style:{color:wr},children:v.address}),e.jsx("td",{className:"px-2 py-1",children:e.jsx(Uz,{status:v.status})}),e.jsx("td",{className:"px-2 py-1",style:{color:"#4A4540"},children:dl(v.listPrice)}),e.jsx("td",{className:"px-2 py-1",children:e.jsxs("span",{className:"flex items-center gap-1",style:{color:"#4A4540"},children:[dl(v.salePrice),x&&!N&&e.jsx(Ns,{className:"w-3 h-3",style:{color:Ws}})]})}),e.jsx("td",{className:"px-2 py-1",style:{color:"#4A4540"},children:v.ppsf?dl(v.ppsf):"—"}),e.jsx("td",{className:"px-2 py-1",style:{color:"#4A4540"},children:v.dom??"—"}),e.jsx("td",{className:"px-2 py-1",style:{color:"#4A4540"},children:v.gla?Gx(v.gla):"—"}),e.jsx("td",{className:"px-2 py-1",style:{color:"#4A4540"},children:v.beds??"—"}),e.jsx("td",{className:"px-2 py-1",style:{color:"#4A4540"},children:yg(v.fullBathrooms,v.halfBathrooms,v.baths)}),e.jsx("td",{className:"px-2 py-1",style:{color:"#4A4540"},children:v.yearBuilt??"—"})]},v.id)}),t.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:12,className:"text-center py-8 text-[12px]",style:{color:Es},children:"No properties available. Lock a market area to populate data."})})]})]})})]})}function Oz({localBoundaries:t,localDescription:a,localConditions:s,handleNbhdFieldChange:r,handleGenerateNbhd:n,isGeneratingNbhd:i,neighborhoodAiGenerated:l,subjectAddress:c}){return e.jsxs("div",{className:"rounded-lg bg-white p-4 space-y-3",style:{border:`1px solid ${en}`},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gn,{className:"w-3.5 h-3.5",style:{color:wr}}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wider",style:{color:wr},children:"Neighborhood Boundaries"}),(t||a||s)&&e.jsx(kt,{variant:"outline",className:"text-[11px] h-5 ml-1",style:{borderColor:Ws,color:Ws},children:"1004 Report"})]}),(t||a||s)&&e.jsxs("button",{onClick:n,disabled:i||!c,className:"flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] font-medium transition-all disabled:opacity-50",style:{color:Es,border:`1px solid ${en}`},"data-testid":"btn-regenerate-neighborhood",children:[e.jsx(bg,{className:`w-2.5 h-2.5 ${i?"animate-spin":""}`}),i?"Regenerating...":"Regenerate"]})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5 rounded text-[12px]",style:{backgroundColor:"#F0EDE8",color:Es},children:[e.jsx(bg,{className:"w-3 h-3 animate-spin"})," Generating neighborhood content with AI..."]}),l&&(t||a||s)&&!i&&e.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded text-[12px]",style:{backgroundColor:`${Ws}08`,color:Es},"data-testid":"ai-disclaimer",children:[e.jsx(W0,{className:"w-3 h-3 flex-shrink-0",style:{color:Ws}})," Generated by AI — review and edit as needed"]}),!t&&!a&&!s&&!i&&e.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded text-[12px]",style:{backgroundColor:"#F0EDE8",color:Es},children:[e.jsx(W0,{className:"w-3 h-3 flex-shrink-0"})," Content will auto-generate when the sub-market is locked"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] font-medium uppercase tracking-wider mb-1 block",style:{color:Es},children:"Boundaries (N/S/E/W)"}),e.jsx("textarea",{className:"w-full text-[12px] px-2.5 py-1.5 border rounded resize-none focus:outline-none focus:ring-1",style:{borderColor:en,color:wr,minHeight:36},rows:2,placeholder:"North: Oak Creek Road; South: Highway 101; East: Maple Ridge Drive; West: Pacific Coast Highway",value:t,onChange:d=>r("boundaries",d.target.value),"data-testid":"textarea-neighborhood-boundaries"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] font-medium uppercase tracking-wider mb-1 block",style:{color:Es},children:"Neighborhood Description"}),e.jsx("textarea",{className:"w-full text-[12px] px-2.5 py-1.5 border rounded resize-none focus:outline-none focus:ring-1",style:{borderColor:en,color:wr,minHeight:48},rows:3,placeholder:"Factual description of the neighborhood character, land use, and housing types...",value:a,onChange:d=>r("description",d.target.value),"data-testid":"textarea-neighborhood-description"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[12px] font-medium uppercase tracking-wider mb-1 block",style:{color:Es},children:"Market Conditions"}),e.jsx("textarea",{className:"w-full text-[12px] px-2.5 py-1.5 border rounded resize-none focus:outline-none focus:ring-1",style:{borderColor:en,color:wr,minHeight:48},rows:3,placeholder:"Supply/demand conditions, marketing time expectations, and market trends...",value:s,onChange:d=>r("marketConditions",d.target.value),"data-testid":"textarea-market-conditions"})]})]})]})}const Lz={InBalance:"In Balance",OverSupply:"Over Supply",Shortage:"Shortage"},Dz={UnderThreeMonths:"Under 3 months",ThreeToSixMonths:"3–6 months",OverSixMonths:"Over 6 months"},kz={Under3Months:"UnderThreeMonths","3to6Months":"ThreeToSixMonths",Over6Months:"OverSix
4Months"},Mz=[{key:Il.ActiveListingsCount,label:"Active Listings",kind:"count",auto:t=>t.activeCount},{key:Il.PendingSalesCount,label:"Pending Sales",kind:"count",auto:t=>t.pendingCount},{key:Il.TotalSalesCount,label:"Total Sales",kind:"count",auto:t=>t.soldCount},{key:Il.ActiveMedianDaysOnMarketCount,label:"Active Median DOM",kind:"count",suffix:" days",auto:t=>t.activeCount>0?t.activeMedDOM:null},{key:Il.MarketSupplyTrendType,label:"Supply Trend",kind:"enum",options:N_,optionLabels:Lz,auto:(t,a)=>a.demandSupply??null},{key:Il.MarketingTimeType,label:"Marketing Time",kind:"enum",options:A_,optionLabels:Dz,auto:(t,a)=>kz[a.marketingTime]??null},{key:Il.ActiveLowestPriceAmount,label:"Active List Low",kind:"currency",auto:t=>t.activeCount>0?t.activeListLow:null},{key:Il.ActiveMedianPriceAmount,label:"Active List Median",kind:"currency",auto:t=>t.activeCount>0?t.activeListMed:null},{key:Il.ActiveHighestPriceAmount,label:"Active List High",kind:"currency",auto:t=>t.activeCount>0?t.activeListHigh:null},{key:Il.SalesLowestPriceAmount,label:"Sales Low",kind:"currency",auto:t=>t.soldCount>0?t.priceLow:null},{key:Il.SalesMedianPriceAmount,label:"Sales Median",kind:"currency",auto:t=>t.soldCount>0?t.priceMed:null},{key:Il.SalesHighestPriceAmount,label:"Sales High",kind:"currency",auto:t=>t.soldCount>0?t.priceHigh:null},{key:Il.MarketTrendsForeclosureActivityIndicator,label:"Distressed Market",kind:"boolean",auto:()=>null},{key:Il.PriceTrendDataSourceNames,label:"Price Trend Sources",kind:"text",placeholder:"e.g. MLS; Public records",auto:()=>null},{key:Il.PriceTrendsAnalysisDescription,label:"Price Trend Analysis",kind:"text",placeholder:"Analysis commentary…",auto:()=>null},{key:Il.MarketInventorySearchParameterDescription,label:"Search Criteria",kind:"text",placeholder:"Search parameters…",auto:()=>null}];function Fz({derivedFormFields:t,computedStats:a,demandLabel:s,marketTimeLabel:r,formType:n,uad36Editable:i,uad36Overrides:l,onUad36OverrideChange:c}){return e.jsxs(e.Fragment,{children:[n==="3.6"&&e.jsxs("div",{className:"rounded-lg p-3",style:{border:`1px solid ${Ws}`,backgroundColor:`${Ws}06`},"data-testid":"uad36-market-fields",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(gn,{className:"w-3.5 h-3.5",style:{color:Ws}}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wider",style:{color:wr},children:"UAD 3.6 Market Section Fields (§17)"}),e.jsx(kt,{variant:"outline",className:"text-[11px] h-5 ml-1",style:{borderColor:Ws,color:Ws},children:i?"Click a value to override":"Auto-derived on lock"})]}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2","data-testid":"uad36-fields-strip",children:Mz.map(d=>e.jsx(_z,{def:d,autoValue:d.auto(a,t),override:l?l[d.key]:void 0,editable:!!i&&!!c,onChange:c},d.key))}),e.jsx("p",{className:"text-[11px] mt-2",style:{color:Es},children:i?"These values fill the URAR Market section when the market area is locked. Click any value to type your own — overridden cards show a Manual badge and keep your number even if you re-lock; the circular arrow resets a card back to the auto-derived value.":`These values fill the URAR Market section automatically when the market area is locked. Marketing Time: ${r}. Distressed-market indicator, price-trend sources, and analysis commentary remain manual entries in the report.`})]}),e.jsxs("div",{className:"rounded-lg p-3",style:{border:`1px solid ${Ws}`,backgroundColor:`${Ws}06`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(gn,{className:"w-3.5 h-3.5",style:{color:Ws}}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wider",style:{color:wr},children:"Auto-Filled Report Fields"}),e.jsx(kt,{variant:"outline",className:"text-[11px] h-5 ml-1",style:{borderColor:Ws,color:Ws},children:"Derived from data"})]}),e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-6 gap-2","data-testid":"form-fields-strip",children:[e.jsx(mx,{label:"Values",value:t.propertyValues}),e.jsx(mx,{label:"Demand",value:s}),e.jsx(mx,{label:"Mkt Time",value:r}),e.jsx(mx,{label:"Price Range",value:`${dl(t.priceLow)} – ${dl(t.priceHigh)}`}),e.jsx(mx,{label:"Predominant",value:dl(t.pricePredominant)}),e.jsx(mx,{label:"Age",value:`${t.ageLow} – ${t.ageHigh} yrs`})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(tj,{title:"Active",count:a.activeCount,items:[{label:"Listings",value:String(a.activeCount)}
4],color:"slate"}),e.jsx(tj,{title:"Pending",count:a.pendingCount,items:[{label:"Under Contract",value:String(a.pendingCount)}],color:"warm"}),e.jsx(tj,{title:"Recent Sales",count:a.soldCount,items:[{label:"Low",value:dl(a.priceLow)},{label:"Median",value:dl(a.priceMed)},{label:"High",value:dl(a.priceHigh)}],color:"emerald"})]})]})}function _z({def:t,autoValue:a,override:s,editable:r,onChange:n}){const[i,l]=o.useState(!1),[c,d]=o.useState(""),p=s!=null,h=(N=>N==null||N===""?"—":t.kind==="currency"?dl(Number(N)):t.kind==="enum"?t.optionLabels?.[String(N)]??String(N):t.kind==="boolean"?N===!0||N==="true"?"Yes":"No":Array.isArray(N)?N.join("; "):`${N}${t.suffix??""}`)(p?s:a),f=N=>{if(l(!1),!n)return;const x=N.trim();if(x===""){n(t.key,null);return}if(t.kind==="count"||t.kind==="currency"){const y=parseFloat(x.replace(/[^0-9.]/g,""));if(!Number.isFinite(y))return;const b=Math.round(y);if(a!==null&&b===Math.round(Number(a))){n(t.key,null);return}n(t.key,b);return}n(t.key,x)},v=()=>{if(!r||t.kind==="enum"||t.kind==="boolean")return;const N=p?Array.isArray(s)?s.join("; "):String(s):a!=null?String(a):"";d(N),l(!0)},S=p?e.jsxs("span",{className:"inline-flex items-center gap-1 ml-1 shrink-0",children:[e.jsx("span",{className:"text-[9px] font-semibold uppercase px-1 rounded",style:{backgroundColor:"#FEF3C7",color:"#92400E",border:"1px solid #FDE68A"},"data-testid":`badge-manual-${t.key}`,children:"Manual"}),e.jsx("button",{type:"button",title:"Reset to auto-derived value",onClick:N=>{N.stopPropagation(),n?.(t.key,null)},className:"p-0.5 rounded hover:bg-amber-100","data-testid":`btn-reset-uad36-${t.key}`,children:e.jsx(bg,{size:10,style:{color:"#92400E"}})})]}):null;return e.jsxs("div",{className:"bg-white rounded-md px-2 py-1",style:{border:`1px solid ${p?"#F59E0B":Ws}`,backgroundColor:p?"#FFFBEB":"#fff"},"data-testid":`uad36-pill-${t.key}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[11px] font-medium truncate",style:{color:p?"#B45309":Ws},children:t.label}),S]}),i?e.jsx("input",{autoFocus:!0,className:"w-full text-[13px] font-semibold border rounded px-1 py-0 focus:outline-none focus:ring-1",style:{borderColor:Ws,color:wr},value:c,placeholder:t.placeholder,inputMode:t.kind==="count"||t.kind==="currency"?"numeric":void 0,onChange:N=>d(N.target.value),onBlur:()=>f(c),onKeyDown:N=>{N.key==="Enter"&&f(c),N.key==="Escape"&&l(!1)},"data-testid":`input-uad36-${t.key}`}):t.kind==="enum"&&r?e.jsxs("select",{className:"w-full text-[13px] font-semibold bg-transparent focus:outline-none cursor-pointer",style:{color:wr},value:p?String(s):"",onChange:N=>n?.(t.key,N.target.value===""?null:N.target.value),"data-testid":`select-uad36-${t.key}`,children:[e.jsx("option",{value:"",children:a?`Auto: ${t.optionLabels?.[String(a)]??String(a)}`:"—"}),(t.options??[]).map(N=>e.jsx("option",{value:N,children:t.optionLabels?.[N]??N},N))]}):t.kind==="boolean"&&r?e.jsxs("select",{className:"w-full text-[13px] font-semibold bg-transparent focus:outline-none cursor-pointer",style:{color:wr},value:p?String(s):"",onChange:N=>n?.(t.key,N.target.value===""?null:N.target.value==="true"),"data-testid":`select-uad36-${t.key}`,children:[e.jsx("option",{value:"",children:"—"}),e.jsx("option",{value:"true",children:"Yes"}),e.jsx("option",{value:"false",children:"No"})]}):e.jsx("div",{className:`text-[13px] font-semibold truncate ${r?"cursor-pointer hover:underline decoration-dotted":""}`,style:{color:wr},onClick:v,title:r?"Click to override":void 0,"data-testid":`field-${t.label.toLowerCase().replace(/\s+/g,"-")}`,children:h})]})}function mx({label:t,value:a}){return e.jsxs("div",{className:"bg-white rounded-md px-2 py-1",style:{border:`1px solid ${Ws}`},children:[e.jsx("div",{className:"text-[11px] font-medium",style:{color:Ws},children:t}),e.jsx("div",{className:"text-[13px] font-semibold truncate",style:{color:wr},"data-testid":`field-${t.toLowerCase().replace(/\s+/g,"-")}`,children:a})]})}function tj({title:t,count:a,items:s,color:r}){const n={slate:{bg:"#f8fafc",text:Oo,border:"#e2e8f0",label:"#64748b"},warm:{bg:"#fefbf5",text:"#92400e",border:"#f5e6c8",label:"#b45309"},emerald:{bg:"#f0fdf4",text:"#166534",border:"#bbf7d0",label:"#15803d"}},i=n[r]||n.slate;return e.jsxs("div",{className:"rounded-lg p-2.5",style:{backgroundColor:i.bg,border:`1px solid ${i.border}`},"data-testid":`inventory-${t.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider mb-1",style:{color:i.label},children:t}),e.jsx("div",{className:"text-xl font-bold mb-1 tabular-nums",style:{color:i.text},children:a}),s.map((l,c)=>e.jsxs("div",{className:"flex justify-between text-[12px] py-0.5",children:[e.jsx("span",{style:{color:i.label,opacity:.8},children:l.label}),e.jsx("span",{className:"font-medium tabular-nums",style:{color:i.text},children:l.value})]},c))]})}function Uz({status:t}){const a=t.toLowerCase();return a.includes("sold")||a.includes("closed")||a==="clsd"?e.jsx(kt,{variant:"outline",className:"text-[11px] h-5 bg-emerald-50 text-emerald-700 border-emerald-200",children:"Sold"}):a.includes("active")||a==="actv"?e.jsx(kt,{variant:"outline",className:"text-[11px] h-5 bg-slate-50 text-slate-600 border-slate-200",children:"Active"}):a.includes("pending")||a.includes("contract")||a==="pend"?e.jsx(kt,{variant:"outline",className:"text-[11px] h-5",style:{backgroundColor:"#fefbf5",color:"#92400e",borderColor:"#f5e6c8"},children:"Pending"}):e.jsx(kt,{variant:"outline",className:"text-[11px] h-5",children:t})}function Vz({open:t,onClose:a,marketStats:s,subMarketStats:r,properties:n,subMarketProperties:i,subjectPrice:l,subjectYearBuilt:c,subjectGla:d,subjectBeds:p,subjectBaths:u,subjectLotSize:m,subjectListing:h,onFormFieldsUpdate:f,reportFormType:v,assignmentId:S,analyticsState:N,onAnalyticsStateChange:x,neighborhoodInfo:y,onNeighborhoodInfoChange:b,neighborhoodAiGenerated:j,onNeighborhoodAiGeneratedChange:T,subjectAddress:O,subjectCity:E,subjectCounty:R,subjectState:G,subMarketGeometry:U,onApplyChartsToReport:C,onAutoCaptureSave:F,marketDataSignature:A}){return e.jsx(xi,{open:t,onOpenChange:M=>!M&&a(),children:e.jsxs(bi,{className:"w-[90vw] max-w-[1400px] h-[90vh] p-0 flex flex-col overflow-hidden","data-testid":"market-modal",hideClose:!0,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200 shrink-0",style:{backgroundColor:"#FAF9F7"},children:[e.jsx(si,{className:"text-sm font-semibold text-gray-700",children:"Market Analysis"}),e.jsx(lL,{asChild:!0,children:e.jsxs("button",{className:"rounded-full p-1.5 hover:bg-gray-100 transition-colors","data-testid":"btn-close-market-modal",children:[e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",style:{backgroundColor:"#FAF9F7"},children:e.jsx(Ez,{marketStats:s,subMarketStats:r,properties:n,subMarketProperties:i,subjectPrice:l,subjectYearBuilt:c,subjectGla:d,subjectBeds:p,subjectBaths:u,subjectLotSize:m,subjectListing:h,onFormFieldsUpdate:f,reportFormType:v,assignmentId:S,analyticsState:N,onAnalyticsStateChange:x,neighborhoodInfo:y,onNeighborhoodInfoChange:b,neighborhoodAiGenerated:j,onNeighborhoodAiGeneratedChange:T,subjectAddress:O,subjectCity:E,subjectCounty:R,subjectState:G,subMarketGeometry:U,onApplyChartsToReport:C,onAutoCaptureSave:F,marketDataSignature:A})})]})})}const TT="eval_chart_images";function Iw(t){const a=s=>Array.isArray(s)?s.map(a):s&&typeof s=="object"?Object.fromEntries(Object.entries(s).filter(([r])=>!/^(updatedAt|createdAt|loading|error)$/i.test(r)).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,a(n)])):s;return JSON.stringify(a(t))}function $z(t){const a={};return t.forEach((s,r)=>{const n=s.chartId||s.imageType||`chart_${r}`;a[n]=s.src}),a}function Bz(t,a){const s=t[TT];if(a&&s?.signature!==a)return null;if(s?.images&&typeof s.images=="object"){const r=s.images;if(Object.values(r).every(n=>typeof n=="string"))return r}return null}const py=t=>{if(t==null||typeof t!="string"&&typeof t!="number")return null;let a=t;if(typeof t=="string"){const r=t.trim();if(r===""||(a=r.replace(/^\$\s*/,"").replace(/,/g,"").replace(/\s*(?:sf|sq\.?\s*ft\.?|square\s+feet)$/i,"").trim(),a===""))return null}const s=Number(a);return Number.isFinite(s)&&s>=0?s:null},IT=t=>{const a=py(t);return a!==null&&a>0?a:null},ik=t=>py(t);function zz(t){const a=GI(t),s=IT(t.nonstandardFinishedAboveGrade);return a===null&&s===null?null:(a??0)+(s??0)}function GI(t){return Object.prototype.hasOwnProperty.call(t,"finishedAboveGrade")?IT(t.finishedAboveGrade):IT(t.gla)}function ok(t,a){const s=ik(t),r=zz(a);return s!==null&&r!==null?s/r:null}function ob(t,a){const s=ok(t,a);return s===null?null:Math.round(s)}function hb(t){const a=ik(t.salePrice),s=Number(t.totalAdj),r=a!==null?a+(Number.isFinite(s)?s:0):null;return{...t,gla:GI(t),salePricePerSf:ob(a,t),adjustedPrice:r,adjustedPricePerSf:ob(r,t)}}function qz(t){const a={gla:"finishedAboveGrade",bedrooms:"beds",bathrooms:"baths",fullBaths:"fullBathrooms",halfBaths:"halfBathrooms",fullBathrooms:"fullBathrooms",halfBathrooms:"halfBathrooms",lotSize:"lotSize",yearBuilt:"yearBuilt",view:"view",ViewType:"view",quality:"quality",condition:"condition",stories:"stories",heatingType:"heatingCooling",designStyle:"designStyle",neighborhoodName:"neighborhoodName",NeighborhoodName:"neighborhoodName",location:"siteInfluence",locationComparison:"location",locationType:"locationType",siteLocationType:"locationType",neighborhoodClassification:"locationType",attachmentType:"attachmentType",attachedDetached:"attachmentType",siteInfluence:"siteInfluence",SiteInfluenceType:"siteInfluence",totalRooms:"totalRooms",aboveGradeTotal:"totalRooms",garageType:"garageParking",listPrice:"listPrice",listDate:"subjectListDate",listingStatus:"listingStatus",unfinishedAboveGrade:"unfinishedAboveGrade",finishedBelowGrade:"finishedBelowGrade",unfinishedBelowGrade:"unfinishedBelowGrade",nonstandardFinishedAboveGrade:"nonstandardFinishedAboveGrade",nonstandardFinishedBelowGrade:"nonstandardFinishedBelowGrade",belowGradeExteriorAccess:"belowGradeExteriorAccess",porchPatioDeck:"porchPatioDeck"},s={mls:"MLS",MLS:"MLS",public_record:"Public Record",PublicRecord:"Public Record",echo:"Echo",Echo:"Echo",user:"Manual",User:"Manual"},r={};for(const[l,c]of Object.entries(a)){const d=t[l],p=Cw(c,d?.value);if(!d||!ai(p)&&!d.isEdited||r[c]?.selected&&!d.isEdited)continue;const u=Object.entries(d.alternatives||{}).map(([m,h])=>({source:s[m]||m,value:Cw(c,h)})).filter(m=>ai(m.value));r[c]={value:ai(p)?p:null,source:s[d.source||""]||d.source||"Property Lab",alternatives:u,...d.isEdited?{selected:!0}:{}}}const n=t.heatingType,i=t.coolingType;if(n&&i&&ai(n.value)&&ai(i.value)){const l=new Set([...Object.keys(n.alternatives||{}),...Object.keys(i.alternatives||{})]);r.heatingCooling={value:`${String(n.value)} / ${String(i.value)}`,source:n.source===i.source&&(s[n.source||""]||n.source)||"Property Lab",alternatives:Array.from(l).flatMap(c=>{const d=n.alternatives?.[c],p=i.alternatives?.[c];return ai(d)&&ai(p)?[{source:s[c]||c,value:`${String(d)} / ${String(p)}`}]:[]})}}else i&&ai(i.value)&&(r.heatingCooling={value:i.value,source:s[i.source||""]||i.source||"Property Lab",alternatives:Object.entries(i.alternatives||{}).filter(([,l])=>ai(l)).map(([l,c])=>({source:s[l]||l,value:c}))});return r}function df(t){return t?t.manual||!!t.editedAt||ai(t.value):!1}function Hl(t){return!!(t&&(t.manual||t.editedAt))}function Yz(t,a){return df(t)?t.value:a}const tf=t=>`subject.${t}`,kc=(t,a)=>`comp.${t}.${a}`;function F0(t,a){return ai(t)&&ai(a)&&String(t).trim().toLowerCase()===String(a).trim().toLowerCase()}const HI={saleDate:{type:"date"},salePrice:{type:"number"},gla:{type:"number"},finishedAboveGrade:{type:"number"},unfinishedAboveGrade:{type:"number"},finishedBelowGrade:{type:"number"},unfinishedBelowGrade:{type:"number"},nonstandardFinishedAboveGrade:{type:"number"},nonstandardFinishedBelowGrade:{type:"number"},belowGradeExteriorAccess:{type:"enum",options:["Walk Out","Walk Up","Cellar Door","Other"]},beds:{type:"number"},baths:{type:"number"},fullBathrooms:{type:"number"},halfBathrooms:{type:"number"},lotSize:{type:"number"},yearBuilt:{type:"number"},listDate:{type:"date"},subjectListDate:{type:"date"},listPrice:{type:"number"},listingStatus:{type:"enum",options:["Active","Pending","Closed","Expired","Withdrawn","Not Listed"]},heatingCooling:{type:"text"},marketConditionsDesc:{type:"text"},view:{type:"text"}
4,quality:{type:"enum",options:["Q1","Q2","Q3","Q4","Q5","Q6"]},condition:{type:"enum",options:["C1","C2","C3","C4","C5","C6"]},designStyle:{type:"text"},neighborhoodName:{type:"text"},location:{type:"text"},locationType:{type:"text"},attachmentType:{type:"enum",options:["Attached","Detached"]},siteInfluence:{type:"text"},totalRooms:{type:"number"},stories:{type:"number"},rightsConveyed:{type:"text"},financingConcessions:{type:"text"},garageParking:{type:"text"},basementFinished:{type:"text"},porchPatioDeck:{type:"text"}};function ai(t){return t!=null&&!(typeof t=="string"&&t.trim()==="")}function Cw(t,a){if(t!=="lotSize")return a;if(typeof a=="number")return Number.isFinite(a)&&a>=0?a:void 0;if(typeof a!="string"||a.trim()==="")return;const s=a.trim().replace(/,/g,""),r=parseFloat(s);if(!(!Number.isFinite(r)||r<0))return/\b(?:ac|acre|acres)\b/i.test(s)?Math.round(r*43560):r}function aj(t){return{mls:"MLS",publicRecord:"Public Record",vault:"Property Lab",ai:"AI",aiSuggestion:"AI",manual:"Manual",user:"Manual"}[t]||t}function Lu(t,a){if(a==null)return null;if(HI[t]?.type!=="number")return a;
4if(typeof a=="number")return Number.isFinite(a)&&a>=0?a:null;if(typeof a!="string"||a.trim()==="")return null;const s=a.trim().replace(/[$,]/g,""),r=parseFloat(s);return!Number.isFinite(r)||r<0?null:t==="lotSize"&&/\b(?:ac|acre|acres)\b/i.test(s)?Math.round(r*43560):r}function b0(t,a){if(!t)return[];const s=[];for(const[n,i]of Object.entries(t.options||{})){const l=a?Lu(a,i):i;ai(l)&&s.push({source:aj(n),value:l})}const r=a?Lu(a,t.finalValue):t.finalValue;return ai(r)&&!s.some(n=>n.source===aj(t.source))&&s.push({source:aj(t.source),value:r}),s}function lk(t){let a=t;for(const[s,r]of Object.entries(t)){const n=s.slice(s.lastIndexOf(".")+1);if(HI[n]?.type!=="number")continue;const i=Lu(n,r.value),l=r.alternatives.map(c=>({...c,value:Lu(n,c.value)}));i===r.value&&l.every((c,d)=>c.value===r.alternatives[d]?.value)||(a===t&&(a={...t}),a[s]={...r,value:i,alternatives:l})}return a}function ck(t){const a=t[tf("location")];if(!a||!ai(a.value)||Hl(a))return t;const s=a.source.trim().toLowerCase();if(!(["property lab","legacy draft"].includes(s)&&a.alternatives.length===0&&!["inferior","similar","superior"].includes(String(a.value).trim().toLowerCase())))return t;const n=tf("siteInfluence"),i=t[n];if(i&&Hl(i)&&ai(i.value)&&!F0(i.value,a.value)||i&&!Hl(i)&&ai(i.value)&&!F0(i.value,a.value))return t;const l={...t};return(!i||!df(i))&&(l[n]=a),delete l[tf("location")],l}function y0(t,a,s,r=[]){const n=[...t?.alternatives||[]];for(const i of r){const l=n.findIndex(c=>c.source===i.source);l>=0?n[l]=i:n.push(i)}return t&&(t.manual||t.editedAt||ai(t.value)&&t.source!==s)?{...t,alternatives:n}:{value:ai(a)?a:t?.value??null,source:ai(a)?s:t?.source||s,alternatives:n,manual:!1,editedAt:t?.editedAt||""}}function tte(t,a){let s=lk(ck(t));if(!a)return s;for(const[r,n]of Object.entries(a)){const i=tf(r),l=y0(s[i],Lu(r,n.value),n.source,n.alternatives.map(d=>({...d,value:Lu(r,d.value)}))),c=n.selected&&(!Hl(s[i])||s[i]?.editedAt==="property-lab-selection")?{...l,value:Lu(r,n.value),source:n.source,manual:!1,editedAt:"property-lab-selection"}:l;c!==t[i]&&(s===t&&(s={...t}),s[i]=c)}return s}function Mv(t,a=new Date().toISOString(),s){return{value:t,source:"Manual",alternatives:s?.alternatives||[],manual:!0,editedAt:a}}function ate(t,a,s=new Date().toISOString()){return{...t,value:a.value,source:a.source,manual:!1,editedAt:s}}const hx={unfinishedAboveGrade:["unfinishedAboveGrade","aboveGradeUnfinishedArea","UnfinishedAboveGradeArea"],finishedBelowGrade:["basementFinishedSf","belowGradeFinishedArea","BasementFinishedArea"],unfinishedBelowGrade:["unfinishedBelowGrade","belowGradeUnfinishedArea","BasementUnfinishedArea"],nonstandardFinishedAboveGrade:["nonstandardFinishedAboveGrade","aboveGradeNonstandardFinishedArea"],nonstandardFinishedBelowGrade:["nonstandardFinishedBelowGrade","belowGradeNonstandardFinishedArea"],belowGradeExteriorAccess:["belowGradeExteriorAccess","basementExitType","walkoutBasement"]},Gz=["basementTotalArea","basementSqft","BelowGradeTotalArea","BasementArea"];function Tm(t,a){return a.map(s=>t.cleanedFields?.find(r=>r.fieldKey===s)).find(Boolean)}function ap(t){return ai(t)?py(t):null}function WI(t){const a=Tm(t,hx.finishedBelowGrade),s=Tm(t,["belowGradeSummary"]),r=Tm(t,["basement","basementType"]),n=String(s?.finalValue??""),i=n.match(/([\d,]+)\s*sf\s*fin/i),l=n.match(/([\d,]+)\s*sf\s*total/i),c=Tm(t,Gz)||s,d=Tm(t,hx.unfinishedBelowGrade),p=i?ap(i[1]):l&&!i?null:ap(a?.finalValue),u=ap(l?l[1]:c?.finalValue),m=ap(d?.finalValue),f=!((p??0)>0||(u??0)>0||(m??0)>0)&&[n,r?.finalValue].some(N=>{const x=String(N??"").trim();return/^(?:no basement|none|slab(?: foundation)?)$/i.test(x)||/\bbasement\s*[:=-]\s*(?:none|no)\b/i.test(x)}),v=m??(u!==null&&p!==null&&u>=p?u-p:null),S={unfinishedAboveGrade:Tm(t,hx.unfinishedAboveGrade),finishedBelowGrade:a,unfinishedBelowGrade:d??c,nonstandardFinishedAboveGrade:Tm(t,hx.nonstandardFinishedAboveGrade),nonstandardFinishedBelowGrade:Tm(t,hx.nonstandardFinishedBelowGrade),belowGradeExteriorAccess:Tm(t,hx.belowGradeExteriorAccess)};return{values:{finishedAboveGrade:t.gla??null,unfinishedAboveGrade:ap(S.unfinishedAboveGrade?.finalValue),finishedBelowGrade:f?0:p,unfinishedBelowGrade:f?0:v,nonstandardFinishedAboveGrade:ap(S.nonstandardFinishedAboveGrade?.finalValue),nonstandardFinishedBelowGrade:ap(S.nonstandardFinishedBelowGrade?.finalValue),belowGradeExteriorAccess:S.belowGradeExteriorAccess?.finalValue??null},fields:S}}function Hz(t){if(typeof t!="string")return null;const a=t.match(/([\d,]+)\s*(?:sf|sq\.?\s*ft)\s*(?:fin|finished)/i)||t.match(/(?:fin|finished)[^\d]*([\d,]+)/i);return a?ap(a[1]):null}function Wz(t){const a=t,s=ck({...a.evalCellValues||{}});for(const[n,i]of Object.entries(s)){if(!n.startsWith("comp."))continue;const l=[".attachedDetached",".AttachedDetached",".AttachmentType"].find(p=>n.endsWith(p));if(!l)continue;const c=`${n.slice(0,-l.length)}.attachmentType`,d=s[c];(Hl(i)&&!Hl(d)||!df(d)&&df(i))&&(s[c]=i)}const r=(a.compGridRows||[]).map(n=>{const i=String(n.compId||n.address||""),l={...n};if(!ai(l.attachmentType)){for(const h of["attachedDetached","AttachedDetached","AttachmentType"])if(ai(l[h])){l.attachmentType=l[h];break}}if(Object.prototype.hasOwnProperty.call(l,"finishedAboveGrade")||(l.finishedAboveGrade=ap(l.gla)),!Object.prototype.hasOwnProperty.call(l,"nonstandardFinishedAboveGrade")&&Object.prototype.hasOwnProperty.call(l,"aboveGradeNonstandardFinishedArea")&&(l.nonstandardFinishedAboveGrade=ap(l.aboveGradeNonstandardFinishedArea)),!ai(l.finishedBelowGrade)){const h=Hz
4(l.basementFinished);h!==null&&(l.finishedBelowGrade=h)}const c=s[kc(i,"siteInfluence")],d=s[kc(i,"location")],p=ai(l.siteInfluence)&&ai(l.location)&&F0(l.siteInfluence,l.location),u=c&&!Hl(c)&&ai(c.value)&&d&&!Hl(d)&&F0(c.value,d.value),m=c&&ai(c.value)&&!F0(c.value,l.siteInfluence);(p||u)&&!Hl(c)&&!m&&(l.siteInfluence="",c&&delete s[kc(i,"siteInfluence")]);for(const h of Object.keys(HI)){const f=l[h],v=kc(i,h);!s[v]&&ai(f)&&(s[v]={value:f,source:String(l.dataSource||"Legacy draft"),alternatives:[],manual:!1,editedAt:""})}return l});return{...a,compGridRows:r,evalCellValues:s}}function Kz(t,a,s){if(s)return"overridden";if(!t||typeof t!="object")return"none";const r=Object.values(t).filter(i=>i!=null&&i!==void 0&&i!=="").map(i=>String(i).trim().toLowerCase());return r.length<=1?"none":r.every(i=>i===r[0])?"matched":"mismatch"}const Qz={location:"Suburban",builtUp:"Over75",growth:"Stable",propertyValues:"Stable",demandSupply:"InBalance",marketingTime:"3to6Months",priceLow:0,priceHigh:0,pricePredominant:0,ageLow:0,ageHigh:0,agePredominant:0,landUseOneUnit:0,landUseTwoToFour:0,landUseMultiFamily:0,landUseCommercial:0,landUseOther:0,neighborhoodBoundaries:"",neighborhoodDescription:"",marketConditions:""},Zz={marketPolygon:null,marketDescriptionInput:"",marketStats:null,subMarketFilters:null,subMarketStats:null,neighborhoodGrid:null,isAnalyzing:!1,lastAnalyzedAt:null,useRadius:!0,radius:1},sj=60;function Jz({subjectAddress:t,subjectLat:a,subjectLng:s,enabled:r=!0}){const[n,i]=o.useState({status:"idle"}),[l,c]=o.useState(null),d=o.useRef(!1),p=o.useRef(null),u=o.useRef(null),m=o.useRef(0),h=9e4;o.useEffect(()=>{if(!r||!t||a===null||s===null||p.current===t)return;p.current=t,d.current=!1,u.current=null,(async()=>{try{const S=await Ho(`/api/preload/status/${encodeURIComponent(t)}`,{throwOnSuccessFalse:!1});if(S?.status==="completed"){console.log("[Preload] Already completed for",t),d.current=!0,i({status:"completed",propertiesFound:S.propertiesFound,propertiesProcessed:S.propertiesProcessed,elsProcessed:S.elsProcessed,aiAnalyzed:S.aiAnalyzed,closestNScored:S.closestNScored,currentStage:S.currentStage,readyAt:S.readyAt,completedAt:S.completedAt,isReady:!0});return}if(S?.status==="in_progress"){console.log("[Preload] Already in progress for",t),c(S.id),u.current={processed:S.propertiesProcessed||0,timestamp:Date.now()},i({status:"in_progress",propertiesFound:S.propertiesFound,propertiesProcessed:S.propertiesProcessed,elsProcessed:S.elsProcessed,aiAnalyzed:S.aiAnalyzed,closestNScored:S.closestNScored,currentStage:S.currentStage,startedAt:S.startedAt,readyAt:S.readyAt,isReady:!!S.readyAt});return}console.log("[Preload] Starting for",t);const N=await dn("/api/preload/start",{subjectAddress:t,subjectLat:a,subjectLng:s},{throwOnSuccessFalse:!1});if(N?.statusId){if(d.current)return;c(N.statusId),N.message==="Pre-load already completed"?i({status:"completed",isReady:!0}):(u.current={processed:0,timestamp:Date.now()},i({status:"in_progress",startedAt:new Date().toISOString(),currentStage:N.message==="Pre-load queued"?"queued":"searching"}))}}catch(S){console.error("[Preload] Failed to trigger:",S),i({status:"failed",errorMessage:String(S)})}})()},[r,t,a,s]),o.useEffect(()=>{if(n.status!=="in_progress"||!t)return;m.current=0;const v=setInterval(async()=>{if(m.current+=1,m.current>=sj){console.warn(`[Preload] Max poll count (${sj}) reached for ${t} — exiting polling`),clearInterval(v),i(S=>({...S,status:"failed",isStalled:!0,errorMessage:`Client-side poll timeout: no completion after ${sj}s`}));return}try{const S=await Ho(`/api/preload/status/${encodeURIComponent(t)}`,{throwOnSuccessFalse:!1});if(S){S.currentStage==="queued"&&(m.current=0);const N=S.propertiesProcessed||0;let x=!1;if(u.current?N>u.current.processed?u.current={processed:N,timestamp:Date.now()}:Date.now()-u.current.timestamp>h&&N<(S.propertiesFound||1/0)&&S.currentStage!=="queued"&&(x=!0):u.current={processed:N,timestamp:Date.now()},S.status==="failed"||S.status==="error"){i({status:S.status,propertiesFound:S.propertiesFound,propertiesProcessed:S.propertiesProcessed,errorMessage:S.errorMessage,startedAt:S.startedAt}),clearInterval(v);return}i({status:S.status,propertiesFound:S.propertiesFound,propertiesProcessed:S.propertiesProcessed,elsProcessed:S.elsProcessed,aiAnalyzed:S.aiAnalyzed,closestNScored:S.closestNScored,currentStage:S.currentStage,errorMessage:S.errorMessage,startedAt:S.startedAt,readyAt:S.readyAt,completedAt:S.completedAt,isReady:!!S.readyAt||S.status==="completed",isStalled:x}),(S.status==="completed"||S.readyAt)&&(S.readyAt&&S.status!=="completed"&&i(y=>({...y,isReady:!0})),clearInterval(v))}}catch(S){console.error("[Preload] Status poll failed:",S)}},1e3);return()=>clearInterval(v)},[n.status,t]),o.useEffect(()=>{if(n.status!=="failed"&&n.status!=="error")return;const v=setTimeout(()=>{i(S=>({...S,status:"idle"}))},8e3);return()=>clearTimeout(v)},[n.status]);const f=o.useCallback(async()=>
4{if(t)try{const v=await Ho(`/api/preload/status/${encodeURIComponent(t)}`,{throwOnSuccessFalse:!1});v&&i({status:v.status,propertiesFound:v.propertiesFound,propertiesProcessed:v.propertiesProcessed,elsProcessed:v.elsProcessed,aiAnalyzed:v.aiAnalyzed,closestNScored:v.closestNScored,currentStage:v.currentStage,errorMessage:v.errorMessage,startedAt:v.startedAt,readyAt:v.readyAt,completedAt:v.completedAt,isReady:!!v.readyAt||v.status==="completed"})}catch(v){console.error("[Preload] Refresh failed:",v)}},[t]);return{status:n,statusId:l,isLoading:n.status==="in_progress",isGated:n.status==="in_progress"&&!n.isReady,isBackgroundLoading:n.status==="in_progress"&&!!n.isReady,isReady:!!n.isReady,isComplete:n.status==="completed",refresh:f}}function Ec(t,a){const s={};return t!=null&&(s.mls=t),a!=null&&(s.publicRecord=a),s}function Sh(t,a,s=0){return t==null||a==null?!1:typeof t=="number"&&typeof a=="number"?s>0?Math.abs(t-a)>s:t!==a:typeof t=="string"&&typeof a=="string"?t.toLowerCase()!==a.toLowerCase():t!==a}function Lp(t,a){return t!=null?{value:t,source:"mls"}:a!=null?{value:a,source:"publicRecord"}:{value:null,source:"mls"}}function Xz(t){if(t==null||t==="")return null;const a=String(t).trim().replace(/,/g,""),s=typeof t=="number"?t:parseFloat(a);return!Number.isFinite(s)||s<0?null:/\b(?:ac|acre|acres)\b/i.test(a)?Math.round(s*43560):s}function Eh(t){if(t==null||t==="")return null;const a=String(t).trim().toLowerCase();return a==="attached"||a==="attach"?"Attached":a==="detached"||a==="detach"?"Detached":null}function Rw(t,a){const s=Eh(t.attachmentType??t.AttachmentType??t.attachedDetached??t.AttachedDetached);return s||Q0(typeof(t.propertyType??t.PropertySubType??t.PropertyType??a)=="string"?String(t.propertyType??t.PropertySubType??t.PropertyType??a):null,t.PropertyAttachedYN??t.propertyAttachedYN??t.propertyAttachedYn??t.PropertyAttachedYn??t.PROPERTY_ATTACHED_YN)}function CT(t){const a=t.mlsData||{},s=t.publicRecordData||{},r=t.mlsData||{},n=t.publicRecordData||{},i=Ec(a.squareFeet??t.gla,s.squareFeet),l=Lp(a.squareFeet??t.gla,s.squareFeet),c=Sh(a.squareFeet??t.gla,s.squareFeet,50),d=Ec(a.bedrooms??t.beds,s.bedrooms),p=Lp(a.bedrooms??t.beds,s.bedrooms),u=Sh(a.bedrooms??t.beds,s.bedrooms),m=Ec(a.bathrooms??t.baths,s.bathrooms),h=Lp(a.bathrooms??t.baths,s.bathrooms),f=Sh(a.bathrooms??t.baths,s.bathrooms),v=Ec(a.yearBuilt??t.yearBuilt,s.yearBuilt),S=Lp(a.yearBuilt??t.yearBuilt,s.yearBuilt),N=Sh(a.yearBuilt??t.yearBuilt,s.yearBuilt,1),x=a.lotSize??r.lotSizeSquareFeet??r.LotSizeSquareFeet??r.LotSizeAreaMeasure??t.lotSize,y=s.lotSize??n.lotSizeSquareFeet??n.LotSizeSquareFeet??n.LotSizeAreaMeasure,b=Ec(x,y),j=Lp(x,y),T=Sh(x,y,100),O=(()=>{const It=t.siteInfluence??r.siteInfluence??r.SiteInfluenceType??n.siteInfluence??n.SiteInfluenceType;return typeof It=="string"&&It.trim()?It:null})(),E=t,R=Rw(r,t.propertyType),G=Rw(n,null),C=Eh(t.attachmentType)??Eh(E.AttachmentType)??Eh(E.attachedDetached)??Q0(t.propertyType??null,E.propertyAttachedYN??E.PropertyAttachedYN??E.PropertyAttachedYn)??R,F=E.gridFieldOverrides&&["attachedDetached","attachmentType","AttachmentType","AttachedDetached"].find(Ze=>Object.prototype.hasOwnProperty.call(E.gridFieldOverrides,Ze)),A=F?E.gridFieldOverrides?.[F]:void 0,M=A&&typeof A=="object"?A:A===void 0?void 0:{value:A},B=M?Eh(M.value):null,oe=(()=>{const Ze=String(M?.source||"").toLowerCase();return Ze==="publicrecord"||Ze==="public_record"||Ze==="public_records"?"publicRecord":Ze==="ai"?"ai":Ze==="user"||Ze==="manual"?"manual":"mls"})(),ae=Eh(M?.mlsValue??M?.mls),D=Eh(M?.prValue??M?.publicRecordValue??M?.publicRecord),_=Eh(M?.aiValue??M?.ai),$=M?{...ae!=null?{mls:ae}:{},...D!=null?{publicRecord:D}:{},..._!=null?{aiSuggestion:_}:{},...!ae&&C!=null?{mls:C}:{},...!D&&G!=null?{publicRecord:G}:{}}:Ec(C,G),z=M?{value:B,source:oe}:Lp(C,G),V=!!M,le=a.basement??t.basement??r.basementType??r.BasementType??r.BasementYN??s.basement,W=r.basementFinishedSf??r.basementFinishedArea??r.belowGradeFinishedArea??r.BasementFinishedArea??a.basementFinishedSf??s.basementFinishedSf,me=r.basementTotalArea??r.basementSqft??r.BasementArea??r.BelowGradeTotalArea??null,Z=(Ze,It,Ne)=>
4{if(!Ze)return null;const Ue=String(Ze).trim(),ct=Ue.toLowerCase();if(ct==="none"||ct==="no"||ct==="n"||ct==="0")return"None";let xt=Ue;(ct==="yes"||ct==="y"||ct==="1"||ct==="true")&&(xt="Full");const Na=typeof It=="number"?It:It?parseInt(String(It)):NaN,qt=typeof Ne=="number"?Ne:Ne?parseInt(String(Ne)):NaN;let la="";return!isNaN(Na)&&Na>0?!isNaN(qt)&&qt>0&&Na>=qt*.9?la="Finished":!isNaN(qt)&&qt>0?la="Partially Finished":la="Finished":!isNaN(Na)&&Na===0&&(la="Unfinished"),la?`${xt};${la}`:xt},pe=Z(le,W,me),se=Z(s.basement,s.basementFinishedSf,null),fe=Ec(pe,se),ue=Lp(pe,se),be=Sh(pe,se),H=r.basementFinishedSf??r.belowGradeFinishedArea??a.basementFinishedSf??s.basementFinishedSf??null,ye=me,de=Ec(H??ye,s.basementFinishedSf),ge=Lp(H??ye,s.basementFinishedSf),Be=t.basementFullBaths??r.basementFullBaths??null,He=t.basementHalfBaths??r.basementHalfBaths??null,Ie=r.belowGradeRooms??r.BelowGradeRooms??null,ce=r.belowGradeBedrooms??r.BelowGradeBedrooms??r.BedroomsBelowGrade??null,We=(()=>{const Ze=Be!=null&&Be>0||He!=null&&He>0;if(Ie!=null||ce!=null||Ze){const Ne=(Be||0)+(He||0)*.5,Ue=[];return Ie!=null&&Ue.push(`${Ie}rm`),ce!=null&&Ue.push(`${ce}br`),Ze&&Ue.push(`${Ne}ba`),H&&Ue.push(`${H}sf`),Ue.join(" | ")}return H&&ye&&H!==ye?`${H}sf fin / ${ye}sf total`:H?`${H}sf`:ye?`${ye}sf total`:null})(),Re=a.garageSpaces??r.GarageSpaces??r.GarageSpacesCount??t.garageSpaces,ne=s.garageSpaces??n.GarageSpaces??n.GarageSpacesCount,Me=Ec(Re,ne),lt=Lp(Re,ne),Tt=Sh(Re,ne),je=a.garageType??r.garageType??r.GarageType??r.carStorageType??r.parkingFeatures??r.ParkingFeatures??null,Le=Re??ne,st=je&&Le?`${Le} ${je}`:je||(Le?`${Le}-car`:null),Xt=Ec(st,null),ua=je||Re?"mls":ne?"publicRecord":"mls",Oa=t.vehicleStorageItems?.slice(0,12),Xa=[],qa=(Ze,It,Ne,Ue)=>{const ct=Number(It),xt=It!=null&&It!==""&&Number.isFinite(ct)&&ct>0?ct:null;if(!Ze)return;const Na=Xa.findIndex(qt=>qt.CarStorageType===Ze);if(Na>=0){const qt=Xa[Na];Xa[Na]={...qt,...qt.ParkingSpacesCount==null&&xt!==null?{ParkingSpacesCount:xt}:{},...!qt.CarStorageAttachmentType&&Ue?{CarStorageAttachmentType:Ue}:{},fieldSources:{...qt.fieldSources??{},...xt!==null?{ParkingSpacesCount:Ne}:{},...Ue?{CarStorageAttachmentType:Ne}:{}}};return}Xa.push({id:`source-${Ne}-${Ze.toLowerCase()}`,CarStorageType:Ze,ParkingSpacesCount:xt,...Ue?{CarStorageAttachmentType:Ue}:{},fieldSources:{CarStorageType:Ne,...xt!==null?{ParkingSpacesCount:Ne}:{},...Ue?{CarStorageAttachmentType:Ne}:{}}})},os=String(je??""),ya=/^(?:none|no|n|0|no garage|no parking|no vehicle storage)$/i.test(os.trim()),At=dy({compData:t,mlsData:r,prData:n});if(At.kind==="value"){const Ze=String(At.raw.type??"").toLowerCase(),It=Ze.includes("carport")?"Carport":"Garage",Ne=At.source==="PublicRecord"?n:{...t,...r},Ue=It==="Carport"?Ne.CarportSpaces??Ne.carportSpaces??Ne.CarportSpacesCount??Ne.carportSpacesCount??Ne.GarageSpaces??Ne.garageSpaces??Ne.GarageSpacesCount??Ne.garageSpacesCount:Ne.GarageSpaces??Ne.garageSpaces??Ne.GarageSpacesCount??Ne.garageSpacesCount;qa(It,Ue,At.source==="PublicRecord"?"public_records":"mls",Ze.includes("detach")?"Detached":Ze.includes("built")?"BuiltIn":Ze.includes("attach")?"Attached":void 0)}const Fe=(Ze,It,Ne)=>{const Ue=Number(It);!Number.isFinite(Ue)||Ue<=0||qa(Ze,Ue,Ne)};Fe("Carport",r.CarportSpaces??r.carportSpaces??r.CarportSpacesCount??r.carportSpacesCount,"mls"),Fe("Carport",n.CarportSpaces??n.carportSpaces??n.CarportSpacesCount??n.carportSpacesCount,"public_records"),Fe("OpenLot",r.OpenParkingSpaces??r.openParkingSpaces??r.OpenParkingSpacesCount??r.openParkingSpacesCount,"mls"),Fe("OpenLot",n.OpenParkingSpaces??n.openParkingSpaces??n.OpenParkingSpacesCount??n.openParkingSpacesCount,"public_records");const Oe=(Ze,It)=>{if(Xa.length>0)return;const Ne=String(Ze.ParkingFeatures??Ze.parkingFeatures??Ze.ParkingDescription??Ze.parkingDescription??"").toLowerCase(),Ue=Number(Ze.TotalParkingSpaces??Ze.totalParkingSpaces??Ze.ParkingTotal??Ze.parkingTotal??Ze.ParkingSpaces??Ze.parkingSpaces);if(!Number.isFinite(Ue)||Ue<=0)return;const ct=Ne.includes("shared driveway")?"SharedDriveway":Ne.includes("driveway")?"Driveway":Ne.includes("open parking")||Ne.includes("open lot")?"OpenLot":Ne.includes("parking garage")?"ParkingGarage":null;ct&&qa(ct,Ue,It)};Oe({...t,...r},"mls"),Oe(n,"public_records");const rt=Xa.length===0&&(ya||At.kind==="confirmed-none"),$t=Oa??(Xa.length>0||rt?Xa:void 0),na=r.ArchitecturalStyle??r.architecturalStyle??a.style??t.style??r.PropertySubType,zt=n.ArchitecturalStyle??n.architecturalStyle??s.style,Ua=Ec(na,zt),Ce=Lp(na,zt),St=a.heating??r.Heating??s.heating??null,vt=a.cooling??r.Cooling??s.cooling??null,Ve=St!=null||vt!=null,sa=aD(St!=null?String(St):null,vt!=null?String(vt):null),tt=Ec(sa,null),it=a.heating||a.cooling||r.Heating||r.Cooling?"mls":"publicRecord",Je=a.patioFeatures??a.exteriorFeatures??r.PatioAndPorchFeatures??r.PorchFeatures??r.ExteriorFeatures??r.ExteriorAmenities??null,ht=Je!=null&&Je!=="",Kt=wI(ht?String(Je):null),Sa=Ec(Kt,null),Qt=a.pool??r.PoolPrivateYN??r.PoolFeatures??null,ea=s.pool,tr=Ze=>{if(Ze===!0||Ze===1)return!0;
4if(typeof Ze=="string"){const It=Ze.toLowerCase().trim();return It==="yes"||It==="y"||It==="true"||It==="1"||It==="pool"}return!1},zs=tr(Qt)||tr(ea)||t.pool===!0?"Pool":"None",pr=Ec(zs,null),$e=Qt!=null?"mls":ea!=null?"publicRecord":"mls",Ot=[{fieldKey:"gla",fieldLabel:"GLA (Living Area)",category:"basics",finalValue:l.value,source:l.source,confidence:c?.6:.9,options:i,hasConflict:c,isRequired:!0},{fieldKey:"beds",fieldLabel:"Bedrooms",category:"basics",finalValue:p.value,source:p.source,confidence:u?.7:.95,options:d,hasConflict:u,isRequired:!0},{fieldKey:"baths",fieldLabel:"Bathrooms",category:"basics",finalValue:h.value,source:h.source,confidence:f?.7:.95,options:m,hasConflict:f,isRequired:!0},{fieldKey:"yearBuilt",fieldLabel:"Year Built",category:"basics",finalValue:S.value,source:S.source,confidence:N?.6:.9,options:v,hasConflict:N,isRequired:!0},{fieldKey:"lotSize",fieldLabel:"Lot Size (sqft)",category:"basics",finalValue:j.value,source:j.source,confidence:T?.6:.85,options:b,hasConflict:T,isRequired:!0},{fieldKey:"attachmentType",fieldLabel:"Attached / Detached",category:"improvements",finalValue:z.value,source:z.source,confidence:z.value?.9:.5,options:$,hasConflict:Sh($.mls,$.publicRecord),isRequired:!1,...V?{comment:"Property Lab selected source"}:{}},{fieldKey:"basement",fieldLabel:"Basement",category:"basement",finalValue:ue.value,source:ue.source,confidence:be?.6:.8,options:fe,hasConflict:be,isRequired:!1},{fieldKey:"basementFinishedSf",fieldLabel:"Basement Finished SF",category:"basement",finalValue:ge.value,source:ge.source,confidence:.7,options:de,hasConflict:!1,isRequired:!1},...We?[{fieldKey:"belowGradeSummary",fieldLabel:"Below Grade Summary",category:"basement",finalValue:We,source:"mls",confidence:.7,options:Ec(We,null),hasConflict:!1,isRequired:!1}]:[],{fieldKey:"garageSpaces",fieldLabel:"Garage Spaces",category:"basement",finalValue:lt.value,source:lt.source,confidence:Tt?.7:.9,options:Me,hasConflict:Tt,isRequired:!1},{fieldKey:"garage",fieldLabel:"Garage/Carport",category:"improvements",finalValue:st,source:ua,confidence:st?.8:.5,options:Xt,hasConflict:!1,isRequired:!1},{fieldKey:"style",fieldLabel:"Design (Style)",category:"basics",finalValue:Ce.value,source:Ce.source,confidence:.8,options:Ua,hasConflict:!1,isRequired:!1},{fieldKey:"heatingCooling",fieldLabel:"Heating/Cooling",category:"basics",finalValue:Ve?sa:null,source:it,confidence:Ve?.8:.5,options:tt,hasConflict:!1,isRequired:!1},{fieldKey:"porchPatioDeck",fieldLabel:"Porch/Patio/Deck",category:"basics",finalValue:Kt,source:"mls",confidence:ht?.7:.5,options:Sa,hasConflict:!1,isRequired:!1},{fieldKey:"pool",fieldLabel:"Pool",category:"basics",finalValue:zs,source:$e,confidence:.8,options:pr,hasConflict:!1,isRequired:!1}],_e=t,ma=_e.isStrProperty===!0,re=(()=>{const Ze=[],It=Ne=>{typeof Ne=="string"&&Ne.startsWith("http")&&!Ze.includes(Ne)&&Ze.push(Ne)};return It(t.photoUrl),Array.isArray(t.photos)&&t.photos.forEach(Ne=>It(Ne)),_e.mlsData?.photos&&_e.mlsData.photos.forEach(Ne=>It(Ne)),_e.primaryPhoto?.url&&It(_e.primaryPhoto.url),Array.isArray(_e.media)&&_e.media.forEach(Ne=>{typeof Ne=="string"?It(Ne):Ne?.cdnUrl?It(Ne.cdnUrl):Ne?.url&&It(Ne.url)}),_e.listing?.photos&&Array.isArray(_e.listing.photos)&&_e.listing.photos.forEach(Ne=>{typeof Ne=="string"?It(Ne):Ne?.url&&It(Ne.url)}),_e.imageUrl&&It(_e.imageUrl),_e.thumbnail&&It(_e.thumbnail),Ze})(),qe=re[0]||t.photoUrl;return{compId:t.id,address:t.fullAddress||`${t.address}, ${t.city}, ${t.state} ${t.zip}`,mlsNumber:t.mlsNumber,photoUrl:qe,price:t.price,beds:t.beds,baths:t.baths,gla:t.gla,lotSize:Xz(j.value),siteInfluence:O,attachmentType:z.value,attachmentTypeSource:z.source,mlsRemarks:t.mlsRemarks||t.remarks,cleanedFields:Ot,isClean:!1,aiConfidence:0,photos:re.length>0?re:t.photoUrl?[t.photoUrl]:[],isStrProperty:ma,strSource:ma?_e.strSource:void 0,strProviderId:ma?_e.strProviderId:void 0,strListingName:ma?_e.strListingName:void 0,strRentalType:ma?_e.strRentalType:void 0,strAverageDailyRate:ma?_e.strAverageDailyRate:void 0,strOccupancyRate:ma?_e.strOccupancyRate:void 0,strGrossRevenue12mo:ma?_e.strGrossRevenue12mo:void 0,strGrossMonthlyIncome:_e.strGrossMonthlyIncome??void 0,strRating:ma?_e.strRating:void 0,strReviewCount:ma?_e.strReviewCount:void 0,strGuestCapacity:ma?_e.strGuestCapacity:void 0,strMaxGuests:ma?_e.strMaxGuests:void 0,strProvider:ma?_e.strProvider:void 0,strAmenities:ma?_e.strAmenities:void 0,hasPool:_e.hasPool===!0||_e.pool===!0||_e.pool==="Yes",strComparability:_e.strComparability||null,latitude:t.coordinates?.lat??t.lat??(parseFloat(t.latitude||"")||void 0),longitude:t.coordinates?.lng??t.lng??(parseFloat(t.longitude||"")||void 0),distanceMiles:typeof t.distance=="number"&&t.distance>0?t.distance:void 0,listDate:t.listDate,listPrice:t.listPrice,listingStatus:t.status,saleDate:t.saleDate,contractDate:t.contractDate,vehicleStorageItems:$t,vehicleStorageExplicitNone:t.vehicleStorageExplicitNone!==void 0?t.vehicleStorageExplicitNone:rt?!0:$t?!1:void 0,stories:(()=>{const Ze=r.stories??r.Stories??r.StoriesTotal??r.Levels??r.LevelsInUnit??null;if(typeof Ze=="number"&&isFinite(Ze))return Ze;if(typeof Ze=="string"){const It=parseFloat(Ze);return isFinite(It)?It:null}return null})(),view:(()=>{const Ze=r.View??r.view??r.ViewDescription??r.ViewType??r.ViewFeatures??null;return typeof Ze=="string"&&Ze.trim()?Ze.trim():null})()}}const dk={location:["locationComparison"],locationType:["locationType","siteLocationType","neighborhoodClassification"],siteInfluence:["siteInfluence","SiteInfluenceType","location"],attachmentType:["attachmentType","attachedDetached","AttachmentType","AttachedDetached"]};function uk(t,a){const s={};let r=t.cleanedFields;const n=a.gridFieldOverrides??{};for(const[i,l]of Object.entries(dk)){const c=l.find(y=>Object.prototype.hasOwnProperty.call(n,y)),d=c===void 0?void 0:n[c],p=d&&typeof d=="object"&&Object.prototype.hasOwnProperty.call(d,"value"),u=i==="siteInfluence"?["siteInfluence","SiteInfluenceType"]:l,m=[a,a.mlsData,a.publicRecordData].filter(
4Boolean).flatMap(y=>u.filter(b=>Object.prototype.hasOwnProperty.call(y,b)).map(b=>y[b])).find(y=>y!==void 0);if(!p&&m===void 0)continue;const h=p?d.value:m;if(h!=null&&typeof h!="string")continue;const f=i==="location"?"locationComparison":i,v=r.find(y=>y.fieldKey===f);if(!p&&v&&v.finalValue!=null&&v.finalValue!=="")continue;s[i==="location"?"locationComparison":i]=h;const S=String(d?.source||"mls"),N=S==="PublicRecord"?"publicRecord":S==="User"?"manual":S==="MLS"?"mls":S,x={...v,fieldKey:f,fieldLabel:i,category:"basics",finalValue:h??null,source:N,options:{...v?.options??{},...p?{[N]:h??null}:{}},confidence:v?.confidence??0,hasConflict:!1,isRequired:!1,...p?{comment:"Property Lab selected source"}:{}};r=[...r.filter(y=>y.fieldKey!==f),x]}return{...t,...s,cleanedFields:r}}function Ew(t){return t==="location"?"siteInfluence":t}function my(t,a=!1){return t.length===0?a?"None":"":t.map(s=>{const r=s.TenOrMoreParkingSpacesIndicator?"10+":s.ParkingSpacesCount,n=s.CarStorageTypeOtherDescription||s.CarStorageType,i=s.CarStorageAreaMeasure!=null?`${s.CarStorageAreaMeasure} sf`:"";return[r,s.CarStorageAttachmentType,n,i].filter(l=>l!=null&&l!=="").join(" ")}).filter(Boolean).join("; ")}const RT=t=>String(t??"").trim().toLowerCase(),ww=t=>RT(t).replace(/[^a-z0-9]/g,""),Cl=t=>{if(t==null)return!0;const a=String(t).trim();return a===""?!0:a.replace(/[–—\-\s/;]+/g,"")===""};function ty(t,a){const s=i=>{const l=RT(i);if(!l)return null;const c=[];return t.forEach((d,p)=>{RT(d.compId)===l&&c.push(p)}),c.length===0?null:c.length===1?c[0]:-1};for(const i of[a.compId,a.snapshotId,a.mlsNumber]){const l=s(i);if(l!==null)return l}const r=ww(a.address);if(!r)return-1;const n=[];return t.forEach((i,l)=>{ww(i.address)===r&&n.push(l)}),n.length===1?n[0]:-1}function Pw(t,a){return{...t,value:a,source:"AI",hasConflict:t?.hasConflict??!1,isVerified:!1}}function eq(t){const a=t.trim();if(/^(?:s\d{2}\/\d{2})(?:;c\d{2}\/\d{2})?$/i.test(a))return a;const s=Mm(a,null);return s==="–"?a:s}function tq(t,a,s){const r=ty(s,a);if(r<0)return t;const n=s[r],i=n,l=t.fields;let c=null;const d=(y,b)=>{const j=l[y];Cl(b)||!Cl(j?.value)||j?.source==="User"||(c===null&&(c={...l}),c[y]=Pw(j,b))};if(Cl(n.saleDate)||d("dateOfSale",eq(n.saleDate)),d("quality",n.quality),d("condition",n.condition),d("design",n.designStyle||""),n.neighborhoodNameUserEdited){const y=n.neighborhoodNameSource==="MLS"||n.neighborhoodNameSource==="PublicRecord"||n.neighborhoodNameSource==="AI"||n.neighborhoodNameSource==="User"?n.neighborhoodNameSource:"User",b=n.neighborhoodNameAlternatives??[],j={...l.NeighborhoodName?.sourceCandidates??{},...l.neighborhoodName?.sourceCandidates??{},...Object.fromEntries(b.map(O=>[O.source,O.value]))},T={...l.neighborhoodName,value:n.neighborhoodName??"",source:y,hasConflict:!1,isVerified:!0,sourceCandidates:j,mlsValue:b.find(O=>O.source==="MLS")?.value??l.neighborhoodName?.mlsValue??l.NeighborhoodName?.mlsValue,prValue:b.find(O=>O.source==="PublicRecord")?.value??l.neighborhoodName?.prValue??l.NeighborhoodName?.prValue,aiValue:b.find(O=>O.source==="AI")?.value??l.neighborhoodName?.aiValue??l.NeighborhoodName?.aiValue,userValue:b.find(O=>O.source==="User")?.value??l.neighborhoodName?.userValue??l.NeighborhoodName?.userValue};c===null&&(c={...l}),c.neighborhoodName=T,c.NeighborhoodName={...l.NeighborhoodName,...T}}else d("neighborhoodName",n.neighborhoodName||""),d("NeighborhoodName",n.neighborhoodName||"");d("location",n.location||""),d("locationType",n.locationType||""),d("view",n.view||""),d("attachedDetached",n.attachmentType||""),d("attachmentType",n.attachmentType||""),d("SiteInfluenceType",n.siteInfluence||""),d("siteInfluence",n.siteInfluence||""),d("totalRooms",n.totalRooms==null?"":String(n.totalRooms)),d("heatingCooling",n.heatingCooling||""),d("garageCarport",n.garageParking||""),d("garageParking",n.garageParking||""),d("porchPatioDeck",n.porchPatioDeck||"");const p=Object.prototype.hasOwnProperty.call(i,"salePrice")?i.salePrice:i.price??i.closePrice;d("salePrice",p==null?"":String(p));const u=Object.prototype.hasOwnProperty.call(i,"finishedAboveGrade")?i.finishedAboveGrade:i.gla;d("finishedAboveGrade",u==null?"":String(u));const m=Object.prototype.hasOwnProperty.call(i,"nonstandardFinishedAboveGrade")?i.nonstandardFinishedAboveGrade:i.aboveGradeNonstandardFinishedArea;d("nonstandardFinishedAboveGrade",m==null?"":String(m)),d("unfinishedAboveGrade",n.unfinishedAboveGrade==null?"":String(n.unfinishedAboveGrade)),d("finishedBelowGrade",n.finishedBelowGrade==null?"":String(n.finishedBelowGrade)),d("unfinishedBelowGrade",n.unfinishedBelowGrade==null?"":String(n.unfinishedBelowGrade)),d("belowGradeExteriorAccess",n.belowGradeExteriorAccess||"");const h=Cl(l.quality?.value)?n.quality:String(l.quality.value),f=Cl(l.condition?.value)?n.condition:String(l.condition.value);if(Cl(l.qualityCondition?.value)&&l.qualityCondition?.source!=="User"&&(!Cl(h)||!Cl(f))){const y=`${Cl(h)?"–":h} / ${Cl(f)?"–":f}`;c===null&&(c={...l}),c.qualityCondition=Pw(l.qualityCondition,y)}const v=n.vehicleStorageItems!==void 0||n.vehicleStorageExplicitNone!==void 0,S=!v&&n.vehicleStorageUserEdited!==!1&&!Cl(n.garageParking),N=S?[]:v?n.vehicleStorageItems:t.vehicleStorageItems,x=S?!1:v?n.vehicleStorageExplicitNone:t.vehicleStorageExplicitNone;return c===null&&N===t.vehicleStorageItems&&x===t.vehicleStorageExplicitNone?t:{...t,...N!==void 0?{vehicleStorageItems:N}:{},...x!==void 0?{vehicleStorageExplicitNone:x}:{},...S?{vehicleStorageLegacyLabel:n.garageParking}:{},fields:c??l}}function aq(t){const a=t.trim();
4if(Cl(a))return{quality:"",condition:""};const s=a.match(/\bQ[1-6]\b/i)?.[0]?.toUpperCase(),r=a.match(/\bC[1-6]\b/i)?.[0]?.toUpperCase();if(!a.includes("/"))return{quality:s,condition:r};const[n="",i=""]=a.split("/",2);return{quality:s??(Cl(n)?"":void 0),condition:r??(Cl(i)?"":void 0)}}function _x(t){const a=t.replace(/[$,\s]/g,"");if(a==="")return null;const s=Number(a);return Number.isFinite(s)?s:null}function sq(t){if(Cl(t))return{accepted:!0,lotSize:null};const s=t.trim().toLowerCase().replace(/,/g,"").match(/^(\d+(?:\.\d+)?|\.\d+)\s*(?:(ac|acre|acres)|(?:sf|sqft|sq\.?\s*ft\.?|square\s+feet))?$/);if(!s)return{accepted:!1,lotSize:null};const r=Number(s[1]);return!Number.isFinite(r)||r<0?{accepted:!1,lotSize:null}:{accepted:!0,lotSize:s[2]?Math.round(r*43560):r}}function rq(t){if(Cl(t))return{accepted:!0,totalRooms:null,beds:null,baths:null,fullBathrooms:null,halfBathrooms:null};const[a,s,r,...n]=t.split("|");if(n.length>0||r===void 0)return{accepted:!1,totalRooms:null,beds:null,baths:null,fullBathrooms:null,halfBathrooms:null};const i=_x(a),l=_x(s),c=r.trim().split(".");if(i===null||l===null||c.length>2||c[0]==="")return{accepted:!1,totalRooms:null,beds:null,baths:null,fullBathrooms:null,halfBathrooms:null};const d=_x(c[0]),p=c.length===2?_x(c[1]):0;return d===null||p===null||[i,l,d,p].some(u=>u<0)?{accepted:!1,totalRooms:null,beds:null,baths:null,fullBathrooms:null,halfBathrooms:null}:{accepted:!0,totalRooms:i,beds:l,baths:d+p*.5,fullBathrooms:d,halfBathrooms:p}}function nq(t){if(Cl(t))return{accepted:!0,finishedBelowGrade:null,unfinishedBelowGrade:null,basementFinished:""};const a=t.trim();if(/^(?:0(?:\/0(?:\s*(?:sf|sq\.?\s*ft\.?))?)?|none|no\s+basement|no\s+below[-\s]?grade)$/i.test(a))return{accepted:!0,finishedBelowGrade:0,unfinishedBelowGrade:0,basementFinished:a};const[s,r,...n]=a.split("/");if(n.length>0||r===void 0)return{accepted:!1,finishedBelowGrade:null,unfinishedBelowGrade:null,basementFinished:""};const i=_x(s.replace(/\b(?:sf|sq\.?\s*ft\.?)\b/gi,"")),l=_x(r.replace(/\b(?:sf|sq\.?\s*ft\.?|fin(?:ished)?)\b/gi,""));return i===null||l===null||i<0||l<0||l>i?{accepted:!1,finishedBelowGrade:null,unfinishedBelowGrade:null,basementFinished:""}:{accepted:!0,finishedBelowGrade:l,unfinishedBelowGrade:Math.max(0,i-l),basementFinished:a}}function rj(t,a,s){if(a<1||a>12||s<1)return;const r=new Date(Date.UTC(t,a,0)).getUTCDate();if(!(s>r))return`${String(t).padStart(4,"0")}-${String(a).padStart(2,"0")}-${String(s).padStart(2,"0")}`}function iq(t){const a=/^\d{4}-\d{2}-(\d{2})/.exec(t.trim());if(a)return Number(a[1]);const s=/^\d{1,2}\/(\d{1,2})\/\d{4}$/.exec(t.trim());return s?Number(s[1]):null}function oq(t,a){const s=t.trim();if(Cl(s))return"";const r=/^(\d{4})-(\d{2})-(\d{2})/.exec(s);if(r)return rj(Number(r[1]),Number(r[2]),Number(r[3]))??s;const n=/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(s);if(n)return rj(Number(n[3]),Number(n[1]),Number(n[2]))??s;const i=/(?:^|;)s(\d{2})\/(\d{2})(?:;|$)/i.exec(s);if(!i)return/(?:^|;)c\d{2}\/\d{2}(?:;|$)/i.test(s)?void 0:s;const l=Number(i[1]),c=Number(i[2]),d=c>=70?1900+c:2e3+c,p=l>=1&&l<=12?new Date(Date.UTC(d,l,0)).getUTCDate():0;if(p===0)return;const u=iq(a),m=Math.min(Math.max(u??1,1),p);return rj(d,l,m)}function lq(t,a){const s=ty(t,a.identity);if(s<0)return{rows:t,rowIndex:-1,changedFields:[],acceptedFields:[]};const r=String(a.value??"").trim(),n={};let i;if(a.fieldName==="dateOfSale"){const h=oq(r,t[s].saleDate);h!==void 0&&(n.saleDate=h)}else if(a.fieldName==="quality")n.quality=r;else if(a.fieldName==="condition")n.condition=r;else if(a.fieldName==="design"||a.fieldName==="designStyle")n.designStyle=r;else if(a.fieldName==="neighborhoodName"||a.fieldName==="NeighborhoodName")n.neighborhoodName=r,i={neighborhoodNameSource:a.source||"User",neighborhoodNameUserEdited:!0,neighborhoodNameAlternatives:(a.alternatives??[]).map(h=>({source:h.source,value:String(h.value)}))};else if(a.fieldName==="qualityCondition"){const h=aq(r);h.quality!==void 0&&(n.quality=h.quality),h.condition!==void 0&&(n.condition=h.condition)}else if(a.fieldName==="location"||a.fieldName==="locationComparison")n.location=r;else if(a.fieldName==="locationType"||a.fieldName==="siteLocationType"||a.fieldName==="neighborhoodClassification")n.locationType=r;else if(a.fieldName==="view"||a.fieldName==="viewType"||a.fieldName==="ViewType")n.view=r;else if(a.fieldName==="attachmentType"||a.fieldName==="attachedDetached")n.attachmentType=r;else if(a.fieldName==="belowGradeExteriorAccess")n.belowGradeExteriorAccess=r;else if(a.fieldName==="siteInfluence"||a.fieldName==="SiteInfluenceType")n.siteInfluence=r;else if(a.fieldName==="heatingCooling")n.heatingCooling=r;else if(a.fieldName==="garageCarport"||a.fieldName==="garageParking")n.garageParking=r;else if(a.fieldName==="porchPatioDeck")n.porchPatioDeck=r;else if(a.fieldName==="site"){const h=sq(r);
4if(!h.accepted)return{rows:t,rowIndex:s,changedFields:[],acceptedFields:[]};n.lotSize=h.lotSize}else if(a.fieldName==="aboveGrade"){const h=rq(r);if(!h.accepted)return{rows:t,rowIndex:s,changedFields:[],acceptedFields:[]};n.totalRooms=h.totalRooms,n.beds=h.beds,n.baths=h.baths,n.fullBathrooms=h.fullBathrooms,n.halfBathrooms=h.halfBathrooms}else if(a.fieldName==="basementFinished"||a.fieldName==="basement"||a.fieldName==="basementDescription")if(a.fieldName==="basement"){const h=nq(r);if(!h.accepted)return{rows:t,rowIndex:s,changedFields:[],acceptedFields:[]};n.finishedBelowGrade=h.finishedBelowGrade,n.unfinishedBelowGrade=h.unfinishedBelowGrade,n.basementFinished=h.basementFinished}else n.basementFinished=r;else if(a.fieldName==="salePrice"||a.fieldName==="gla"||a.fieldName==="beds"||a.fieldName==="bedrooms"||a.fieldName==="baths"||a.fieldName==="bathrooms"||a.fieldName==="fullBathrooms"||a.fieldName==="halfBathrooms"||a.fieldName==="lotSize"||a.fieldName==="yearBuilt"||a.fieldName==="totalRooms"||a.fieldName==="aboveGradeTotal"||a.fieldName==="finishedAboveGrade"||a.fieldName==="nonstandardFinishedAboveGrade"||a.fieldName==="unfinishedAboveGrade"||a.fieldName==="finishedBelowGrade"||a.fieldName==="unfinishedBelowGrade"){const h=r===""?null:Number(r.replace(/[$,\s]/g,"")),f=a.fieldName==="gla"?"finishedAboveGrade":a.fieldName==="bedrooms"?"beds":a.fieldName==="bathrooms"?"baths":a.fieldName==="aboveGradeTotal"?"totalRooms":a.fieldName;n[f]=h!==null&&Number.isFinite(h)?h:null,(a.fieldName==="gla"||a.fieldName==="finishedAboveGrade")&&(n.gla=n.finishedAboveGrade)}else if(a.fieldName==="VehicleStorageItems")try{const h=JSON.parse(r);if(!Array.isArray(h))return{rows:t,rowIndex:s,changedFields:[],acceptedFields:[]};n.vehicleStorageItems=h.slice(0,12),n.vehicleStorageExplicitNone=h.length===0,n.garageParking=my(h,h.length===0)}catch{return{rows:t,rowIndex:s,changedFields:[],acceptedFields:[]}}else return{rows:t,rowIndex:s,changedFields:[],acceptedFields:[]};const l=t[s],c=Object.keys(n),d=c.filter(h=>l[h]!==n[h]),p=a.fieldName==="VehicleStorageItems"&&l.vehicleStorageUserEdited!==!0,u=i!==void 0&&(l.neighborhoodNameUserEdited!==!0||l.neighborhoodNameSource!==i.neighborhoodNameSource||JSON.stringify(l.neighborhoodNameAlternatives??[])!==JSON.stringify(i.neighborhoodNameAlternatives??[]));if(d.length===0&&!p&&!u)return{rows:t,rowIndex:s,changedFields:[],acceptedFields:c};const m=[...t];return m[s]=hb({...l,...n,...i??{},...p?{vehicleStorageUserEdited:!0}:{}}),{rows:m,rowIndex:s,changedFields:d,acceptedFields:c}}const cq="Property Lab selected source";function Fv(t){return[t?.compId,t?.snapshotId,t?.id,t?.mlsNumber,t?.mlsData?.mlsNumber,t?.mlsData?.MlsListingNumber].filter(a=>a!=null&&String(a).trim()!=="").map(a=>String(a))}function dq(t){return Array.isArray(t?.cleanedFields)?t.cleanedFields.filter(a=>a&&typeof a=="object"&&a.fieldKey).map(a=>[String(a.fieldKey),a]):t?.cleanedFields&&typeof t.cleanedFields=="object"?Object.entries(t.cleanedFields):[]}function uq(t){return Object.prototype.hasOwnProperty.call(t,"finalValue")?{present:!0,value:t.finalValue}:Object.prototype.hasOwnProperty.call(t,"value")?{present:!0,value:t.value}:{present:!1,value:void 0}}function pq(t){return t.map(a=>({...a,options:a.options?{...a.options}:a.options}))}function mq(t,a){if(!a||typeof a!="object")return t;const s=pq(t.cleanedFields||[]),n=s.find(p=>p.fieldKey==="attachmentType"||p.fieldKey==="attachedDetached")?.comment===cq,i=new Map;for(const[p,u]of dq(a)){const m=p==="attachedDetached"||p==="AttachedDetached"||p==="AttachmentType"?"attachmentType":p;i.set(m,u)}const l=[],c=Array.from(new Set([...s.map(p=>p.fieldKey),...Array.from(i.keys())]));for(const p of c){const u=s.find(v=>v.fieldKey===p),m=i.get(p);if(!m||typeof m!="object"){u&&l.push(u);continue}if(p==="attachmentType"&&n){u&&l.push(u);continue}const h={...u||{},...m,fieldKey:p},f=uq(m);f.present&&(h.finalValue=f.value),typeof m.source=="string"&&(h.source=m.source),l.push(h)}const d={...t,...a,compId:t.compId,address:t.address,cleanedFields:l};return n&&(d.attachmentType=t.attachmentType,d.attachmentTypeSource=t.attachmentTypeSource),d}function nj(t,a,s=!1){const r=new Map;for(const n of a)for(const i of Fv(n))r.set(i,n);return t.map(n=>{const i=CT(n),l=Fv(n).map(d=>r.get(d)).find(Boolean),c=mq(i,l);return s?uk(c,n):c})}function hq(t){const a=(s,r)=>{try{const n=s?.value;if(n==null||n==="")return;let i=String(n);r?.stripNonDigits?i=i.replace(/[^0-9]/g,""):r?.stripCommas&&(i=i.replace(/,/g,""));const l=r?.float?parseFloat(i):parseInt(i,10);return Number.isFinite(l)?l:void 0}catch{return}};try{return{beds:a(t?.bedrooms),baths:a(t?.bathrooms,{float:!0}),gla:a(t?.gla,{stripCommas:!0}),yearBuilt:a(t?.yearBuilt),lotSize:a(t?.lotSize,{stripNonDigits:!0}),propertyType:"SFR",basementFinishedSqft:a(t?.basementArea,{stripNonDigits:!0})}}catch(s){return console.error("[Wizard] buildCompIntentSubjectData failed; rendering with empty subject data:",s),{propertyType:"SFR"}}}function fq(t,a){return t??a??void 0}function gq(t){return!!t?.order}function xq(t,a,s){return!t?.order&&(a||s)}function Ow(t,a){return t?"full":a?"slim-loading":"slim-done"}function bq(t,a,s){return`${t}|${a}|${s.map(r=>`${r.stepKey}:${r.id||""}${fb(r)?"!":""}`).join(",")}`}function fb(t){return!!t&&t.stepDataOmitted===!0&&t.stepData==null}function yq(t){return t.filter(a=>fb(a)&&typeof a.stepKey=="string"&&a.stepKey.length>0).map(a=>a.stepKey)}const ay="__seededFromRqCache";function ET(t){if(t==null)return null;const a=t instanceof Date?t.getTime():new Date(String(t)).getTime();return Number.isFinite(a)?a:null}function Sq(t,a){const s=[],r=[],n=[];for(const i of t){if(!fb(i)||typeof i.stepKey!="string"||i.stepKey.length===0)continue;const l=a.get(i.stepKey);if(l){if(l[ay]===!0){if(i.updatedAt!=null&&l.updatedAt!=null&&String(i.updatedAt)===String(l.updatedAt)){s.push(l);continue}n.push(i.stepKey),r.push(i.stepKey);continue}const c=ET(i.updatedAt),d=ET(l.updatedAt);if(!(c!=null&&d!=null&&c>d)){s.push(l);continue}}r.push(i.stepKey)}return{mergeableRows:s,fetchStepKeys:r,staleSeedKeys:n}}function vq(t,a,s){const r=new Set(s),n=a.filter(i=>typeof i.stepKey=="string"&&r.has(i.stepKey)).map(i=>`${i.stepKey}@${ET(i.updatedAt)??""}`).sort();return`${t}|${n.join(",")}`}function Nq(t,a,s,r){return t.length===0?!1:!((a==="done"||a==="failed")&&s===r)}function ij(t,a){const s=new Map;for(const r of a)typeof r?.stepKey=="string"&&r.stepKey.length>0&&s.set(r.stepKey,r);return t.map(r=>{if(!fb(r)||!r.stepKey)return r;const n=s.get(r.stepKey);return n?{...r,...n,stepDataOmitted:!1}:r})}function Aq(t,a){return t&&(a==="idle"||a==="pending")}function jq(t,a=!1){return t||a}function Tq(t,a=!1){return t==="slim-loading"||a}const Iq=new Set(["comp_intent","property_lab","leasehold","str","eval","review"]);function Cq(t){return Iq.has(t)}function sy(t){return t==="property_lab"||t.startsWith("cachedLabState")}function Rq(t){return t.startsWith("cachedLabStateCache")}function Eq(t){if(t.size===0)return!1;for(const a of t)if(!Rq(a)&&(sy(a)||!ry(a)))return!0;return!1}function ry(t){return t==="sales_grid"}function wq(t){const a=[],s=[],r=[];for(const n of t)sy(n)?a.push(n):ry(n)?s.push(n):r.push(n);return[a,s,r].filter(n=>n.length>0)}function Lw(t,a,s){if(s.size===0)return!1;if(t!=="property_lab")return!0;let r=!1;
4return s.forEach(n=>{(a?ry(n):sy(n))&&(r=!0),!ry(n)&&!sy(n)&&(r=!0)}),r}function Dw(t,a,s,r){return a&&Cq(t)&&(s||t==="property_lab"&&!r)}function Pq(t,a){return t||a}function pk(t){return t.hydrationPending?"loading":t.pendingSaveCount>0?"saving":t.lastSaveFailed?"error":t.recentlySaved?"saved":"idle"}const KI={loading:"Loading saved work…",saving:"Saving…",error:"Save failed — check your connection",saved:"Saved"};function mk(t){return t===403?"Save failed — you don't have permission to edit this order":t===401?"Save failed — your session expired, please sign in again":KI.error}function Oq({orderId:t,hydrationPending:a,recentlySaved:s}){const{pendingCount:r,lastSaveFailed:n,lastFailureStatus:i}=cL(t),l=pk({hydrationPending:a,pendingSaveCount:r,lastSaveFailed:t&&!Xf(t)?!1:n,recentlySaved:s});if(l==="idle")return null;const c=l==="error"?mk(i):KI[l];return e.jsxs("span",{className:l==="error"?"flex items-center gap-1 text-[11px] text-red-600":l==="saved"?"flex items-center gap-1 text-[11px] text-emerald-600 animate-in fade-in duration-300":"flex items-center gap-1 text-[11px] text-slate-400","data-testid":`wizard-sync-indicator-${l}`,children:[l==="saved"?e.jsx(Bs,{className:"w-3 h-3"}):l==="error"?e.jsx(Ns,{className:"w-3 h-3"}):e.jsx(za,{className:"w-3 h-3 animate-spin"}),c]})}const Lq="insight-wizard-snapshots",Dq=1,Bh="heavy-rows",Ux="order-access",kw=5,Mw=10*1024*1024,Hx=new Map,_v=new Set;let Bf=null,hk;function fk(){return hk()}function kq(){return Bf||(Bf=new Promise((t,a)=>{try{const s=indexedDB.open(Lq,Dq);s.onupgradeneeded=r=>{const n=r.target.result;n.objectStoreNames.contains(Bh)||n.createObjectStore(Bh,{keyPath:["orderId","stepKey"]}).createIndex("by-order","orderId",{unique:!1}),n.objectStoreNames.contains(Ux)||n.createObjectStore(Ux,{keyPath:"orderId"})},s.onsuccess=()=>t(s.result),s.onerror=()=>{Bf=null,a(s.error)},s.onblocked=()=>{Bf=null,a(new Error("IDB open blocked"))}}catch(s){Bf=null,a(s)}}),Bf)}hk=kq;function Mq(t,a){return new Promise((s,r)=>{const n=t.getAll();n.onsuccess=()=>s(n.result),n.onerror=()=>r(n.error)})}function Fq(t,a,s){return new Promise((r,n)=>{const l=t.index(a).getAll(s);l.onsuccess=()=>r(l.result),l.onerror=()=>n(l.error)})}function Fw(t,a){return new Promise((s,r)=>{const n=t.put(a);n.onsuccess=()=>s(),n.onerror=()=>r(n.error)})}function _q(t,a){return new Promise((s,r)=>{const n=t.delete(a);n.onsuccess=()=>s(),n.onerror=()=>r(n.error)})}function Uq(t,a,s){return new Promise((r,n)=>{const l=t.index(a).openKeyCursor(s),c=[];l.onsuccess=()=>{const d=l.result;if(d)c.push(d.primaryKey),d.continue();else{let p=c.length;if(p===0){r();return}for(const u of c){const m=t.delete(u);m.onsuccess=()=>{p-=1,p===0&&r()},m.onerror=()=>n(m.error)}}},l.onerror=()=>n(l.error)})}async function _w(t){if(_v.has(t))return(Hx.get(t)?.size??0)>0;_v.add(t);try{const r=(await fk()).transaction([Bh],"readonly").objectStore(Bh),n=await Fq(r,"by-order",t);if(n.length>0){const i=new Map;for(const l of n){const{orderId:c,...d}=l;i.set(l.stepKey,{...d,[ay]:!0})}return Hx.set(t,i),!0}return!1}catch(a){return console.warn("[Wizard] IDB preload failed (ignoring):",a),!1}}function wT(t){const a=Hx.get(t);return a?Array.from(a.values()):[]}async function Uw(t,a){if(a.length===0)return;let s=Hx.get(t);s||(s=new Map,Hx.set(t,s)),_v.add(t);for(const r of a)typeof r.stepKey=="string"&&r.stepKey.length>0&&s.set(r.stepKey,{...r,[ay]:!0});if(typeof navigator<"u"&&navigator.storage?.estimate)try{const{quota:r,usage:n}=await navigator.storage.estimate();if(typeof r=="number"&&isFinite(r)&&typeof n=="number"&&isFinite(n)){const i=r-n;if(i<Mw){console.warn("[Wizard] IDB write skipped: storage quota low",{quota:r,usage:n,remaining:i,thresholdBytes:Mw});return}}}catch{}try{const r=await fk(),n=Date.now(),i=r.transaction([Bh,Ux],"readwrite"),l=i.objectStore(Bh),c=i.objectStore(Ux);for(const m of a){if(typeof m.stepKey!="string"||m.stepKey.length===0)continue;const{[ay]:h,...f}=m;await Fw(l,{...f,orderId:t})}await Fw(c,{orderId:t,lastAccessedAt:n}),await new Promise((m,h)=>{i.oncomplete=()=>m(),i.onerror=()=>h(i.error),i.onabort=()=>h(i.error)});const d=r.transaction([Bh,Ux],"readwrite"),p=d.objectStore(Ux),u=await Mq(p);if(u.length>kw){u.sort((f,v)=>f.lastAccessedAt-v.lastAccessedAt);const m=u.slice(0,u.length-kw),h=d.objectStore(Bh);for(const f of m)await Uq(h,"by-order",f.orderId),await _q(p,f.orderId),Hx.delete(f.orderId),_v.delete(f.orderId)}await new Promise((m,h)=>{d.oncomplete=()=>m(),d.onerror=()=>h(d.error),d.onabort=()=>h(d.error)})}catch(r){const n=r instanceof DOMException&&r.name==="QuotaExceededError";console.warn(n?"[Wizard] IDB write skipped: QuotaExceededError":"[Wizard] IDB write failed (ignoring):",r)}}const Vw=42e4;function $w(t){const a=[fi.getQueryData(ZS(t)),fi.getQueryData(kx(t))],s=wT(t);return s.length>0&&a.push({progress:s}),a}function Bw(t){return sy(t)||ry(t)}function Vq(t){const{orderId:a,progressEntries:s,mergeRowsIntoCaches:r}=t,n=o.useRef(t.retryDelayMs??2e3);n.current=t.retryDelayMs??2e3;const i=o.useRef(t.watchdogCeilingMs??Vw);
4i.current=t.watchdogCeilingMs??Vw;const l=t.fetchProgressRows??((_,$)=>I2(_,{stepKeys:$})),c=o.useRef(l);c.current=l;const d=o.useRef(r);d.current=r;const p=o.useRef(t.readCachedOrderPayloads??$w);p.current=t.readCachedOrderPayloads??$w;const u=o.useRef(t.preloadIdbOrder??_w);u.current=t.preloadIdbOrder??_w;const m=o.useRef(t.getIdbMemCacheRows??wT);m.current=t.getIdbMemCacheRows??wT;const h=o.useRef(t.writeIdbRows??Uw);h.current=t.writeIdbRows??Uw;const[f,v]=o.useState("idle"),[S,N]=o.useState(null),[x,y]=o.useState(0),[b,j]=o.useState(!1),T=o.useRef(new Map),O=o.useRef(f);O.current=f;const E=o.useRef(null),R=o.useRef(null),G=s||[],U=o.useRef(void 0);if(U.current!==(a??null)&&(U.current=a??null,T.current=new Map,a))try{const _=[];for(const $ of p.current(a)){const z=Array.isArray($?.progress)?$.progress:[];for(const V of z)!V||typeof V.stepKey!="string"||V.stepKey.length===0||Bw(V.stepKey)&&(fb(V)||V.stepData==null||V.updatedAt==null||T.current.has(V.stepKey)||(T.current.set(V.stepKey,{...V,[ay]:!0}),_.push(V.stepKey)))}_.length>0&&console.log("[Wizard] omitted-recovery CACHE-HIT:",_)}catch(_){console.warn("[Wizard] omitted-recovery cache seed failed (falling back to fetch):",_)}const C=o.useMemo(()=>yq(G),[s]),F=o.useMemo(()=>Sq(G,T.current),[s,x]),A=a?vq(a,G,F.fetchStepKeys):"",M=!b&&Nq(F.fetchStepKeys,f,S,A),B=M?F.fetchStepKeys.slice().sort().join("\0"):"",oe=o.useMemo(()=>new Set(B.length>0?B.split("\0"):[]),[B]),ae=o.useRef({signature:A,state:f,attemptSignature:S});ae.current={signature:A,state:f,attemptSignature:S},o.useEffect(()=>{v("idle"),N(null),y(0),j(!1),E.current=null,R.current=null},[a]),o.useEffect(()=>{if(!a)return;const _=a;u.current(a).then($=>{if(!$||U.current!==_)return;const z=m.current(_);let V=0;for(const le of z)typeof le.stepKey=="string"&&le.stepKey.length>0&&!T.current.has(le.stepKey)&&(T.current.set(le.stepKey,le),V+=1);V>0&&(console.log("[Wizard] omitted-recovery IDB-HIT:",z.map(le=>le.stepKey)),y(le=>le+1))}).catch(()=>{})},[a]);const D=o.useRef("");return o.useEffect(()=>{const _=F.staleSeedKeys;if(_.length===0)return;const $=_.slice().sort().join(",");D.current!==$&&(D.current=$,console.log("[Wizard] omitted-recovery CACHE-MISS (stale):",_))},[F.staleSeedKeys]),o.useEffect(()=>{!a||F.mergeableRows.length===0||(console.log("[Wizard] omitted-recovery MERGE (local, no refetch):",F.mergeableRows.map(_=>_.stepKey),F.fetchStepKeys.length>0?`still needs refetch: ${F.fetchStepKeys.join(",")}`:"nothing left to fetch"),d.current(F.mergeableRows))},[a,F.mergeableRows]),o.useEffect(()=>{if(!a||F.fetchStepKeys.length===0||b||S===A&&f!=="idle")return;if(f==="pending"&&E.current){R.current!==A&&(R.current=A,console.log("[Wizard] omitted-recovery ABSORB: superseding signature while attempt in flight (no re-arm)",{inFlight:E.current.signature,superseding:A}));return}const _=F.fetchStepKeys,$={signature:A};E.current=$,N(A),v("pending"),console.log("[Wizard] omitted-recovery ARM:",{stepKeys:_,signature:A,previousState:f});const z=wq(_);let V=z.length,le=!1;const W=()=>{V-=1,!(V>0)&&(v(le?"failed":"done"),console.log(`[Wizard] omitted-recovery SETTLE ${le?"failed":"done"}:`,{stepKeys:_,signature:$.signature}))},me=(Z,pe)=>{c.current(a,Z).then(se=>{if(E.current!==$)return;const fe=Array.isArray(se?.progress)?se.progress:[],ue=[];for(const be of fe)be&&typeof be.stepKey=="string"&&be.stepKey.length>0&&(T.current.set(be.stepKey,be),Bw(be.stepKey)&&ue.push(be));ue.length>0&&h.current(a,ue),y(be=>be+1),console.log("[Wizard] omitted-recovery GROUP done:",{stepKeys:Z,signature:$.signature}),W()}).catch(se=>{if(E.current===$){if(pe>0){console.warn("[Wizard] Omitted heavy snapshot fetch failed — retrying once:",Z,se),setTimeout(()=>{E.current===$&&me(Z,pe-1)},n.current);return}le=!0,console.error("[Wizard] omitted-recovery GROUP failed:",{stepKeys:Z,signature:$.signature,err:se}),W()}})};z.forEach(Z=>me(Z,1))},[a,F.fetchStepKeys,A,S,f,b]),o.useEffect(()=>{if(!a||!M)return;const _=setTimeout(()=>{const $=ae.current,z=$.state==="pending"?"in-flight attempt never settled":$.attemptSignature!==$.signature?`signature re-arm gap (state ${$.state}, attempted signature never caught up to current)`:`unexpected gate (state ${$.state})`;console.error(`[Wizard] omitted-recovery WATCHDOG TRIPPED after ${i.current}ms — forcing 'failed'. Gate: ${z}`,{state:$.state,attemptSignature:$.attemptSignature,currentSignature:$.signature}),E.current=null,j(!0),v("failed")},i.current);return()=>clearTimeout(_)}
4,[a,M]),{omittedFetchState:f,omittedFetchStateRef:O,omittedFetchPending:M,omittedStepKeys:C,fetchedOmittedRowsRef:T,omittedFetchPendingKeys:oe}}const gk="wizardSidebarCollapsed";function $q(){try{return localStorage.getItem(gk)==="true"}catch{return!1}}function Bq(t){try{localStorage.setItem(gk,String(t))}catch{}}const zq=["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"],qq=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const a=Math.random()*16|0;return(t==="x"?a:a&3|8).toString(16)});function Yq({onPropertyLoaded:t,onReset:a,onAdvanceToNextStep:s,isLoading:r,setIsLoading:n,hasPropertyData:i}){const[l,c]=o.useState({streetAddress:"",city:"",state:"IL",zipCode:"",coordinates:null}),[d,p]=o.useState(""),[u,m]=o.useState(!1),[h,f]=o.useState(""),[v,S]=o.useState([]),[N,x]=o.useState(!1),[y,b]=o.useState(!1),[j,T]=o.useState(null),[O]=o.useState(()=>qq()),E=o.useRef(null),R=o.useRef(null),G=o.useRef(null);o.useEffect(()=>{const ae=D=>{G.current&&!G.current.contains(D.target)&&R.current&&!R.current.contains(D.target)&&x(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[]);const U=o.useCallback(async ae=>{if(ae.length<3){S([]);return}b(!0);try{const _=await(await fetch(`/api/places/autocomplete?input=${encodeURIComponent(ae)}&sessionToken=${O}`)).json();_.success&&_.predictions&&(S(_.predictions),x(!0))}catch(D){console.error("Places search error:",D)}finally{b(!1)}},[O]),C=ae=>{f(ae),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{U(ae)},300)},F=ae=>{const D=[/\b(?:unit|apt|apartment|suite|ste|#)\s*([a-z0-9-]+)/i,/,\s*#?\s*([a-z0-9-]+)\s*,/i];for(const z of D){const V=ae.match(z);if(V)return V[1].toUpperCase()}const _=ae.match(/^\s*\d+\s+[a-z0-9\s.]+(?:street|st|avenue|ave|boulevard|blvd|drive|dr|road|rd|lane|ln|way|place|pl|court|ct|circle|cir|terrace|ter|parkway|pkwy)\s+([a-z]?\d+[a-z]?|ph\d*|penthouse|\d{1,4}[nsew])\b/i);if(_)return _[1].toUpperCase();const $=ae.match(/^\s*\d+\s+\S+(?:\s+\S+)*?\s+(\d{1,4}[nsew]|[nsew]\d{1,4}|ph\d*)\s*(?:,|$)/i);return $?$[1].toUpperCase():null},A=async ae=>{x(!1);const D=h;f(ae.description),b(!0);const _=F(D);_&&(p(_f(_)),m(!0));try{const z=await(await fetch(`/api/places/details?placeId=${ae.place_id}&sessionToken=${O}`)).json();if(z.success&&z.address){const V=z.address.streetNumber?`${z.address.streetNumber} ${z.address.streetName}`:z.address.streetName;if(z.address.unit)p(_f(z.address.unit)),m(!0);else if(!_){const le=F(D);le&&(p(_f(le)),m(!0))}c({streetAddress:V||"",city:z.address.city||"",state:z.address.state||"IL",zipCode:z.address.zipCode||"",coordinates:z.address.coordinates||null})}}catch($){console.error("Place details error:",$)}finally{b(!1)}},M=async()=>{if(!l.streetAddress||!l.city||!l.state||!l.zipCode){T("Please fill in all address fields");return}n(!0),T(null);try{let ae=l.streetAddress;if(d){const V=l$(l.streetAddress);(!V||_f(V).toUpperCase()!==_f(d).toUpperCase())&&(ae=`${l.streetAddress} ${_f(d)}`)}const D=new URLSearchParams({street:ae,city:l.city,state:l.state,zip:l.zipCode}),_=await fetch(`/api/property?${D.toString()}`);if(!_.ok)throw new Error("Failed to fetch property data");const $=await _.json();if(!$.success)throw new Error($.error||"Property lookup failed");const z=`${ae}, ${l.city}, ${l.state} ${l.zipCode}`;t({propertyDetails:$.propertyDetails||$.data,listingDetails:$.listingDetails},{fullAddress:z,streetAddress:l.streetAddress,city:l.city,state:l.state,zipCode:l.zipCode,lat:l.coordinates?.lat,lng:l.coordinates?.lng}),s()}catch(ae){console.error("Property lookup error:",ae),T("Property not found. You can enter the address manually and continue, but data won't be auto-filled.")}finally{n(!1)}},B=ae=>{ae.key==="Enter"&&!r&&M()},oe=()=>{c({streetAddress:"",city:"",state:"IL",zipCode:"",coordinates:null}),p(""),m(!1),f(""),S([]),x(!1),T(null),a()};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-serif font-bold text-accent mb-1",children:"Property Address"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Enter the subject property address to automatically pull in property data."})]}),e.jsxs(ja,{className:"border-border shadow-sm",children:[e.jsx(Do,{
4className:"pb-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Wl,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(ko,{className:"text-lg",children:"Subject Property"}),e.jsx(C2,{children:"Start typing to search for an address"})]})]}),e.jsxs(De,{variant:"outline",size:"sm",onClick:oe,className:"text-red-600 border-red-200 hover:bg-red-50 hover:text-red-700","data-testid":"button-reset-address",children:[e.jsx(bg,{className:"w-4 h-4 mr-1"}),"Start Over"]})]})}),e.jsxs(Ta,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2 relative",children:[e.jsx(Ja,{htmlFor:"addressSearch",children:"Search Address"}),e.jsxs("div",{className:"relative",children:[e.jsx(ze,{ref:R,id:"addressSearch",placeholder:"Start typing an address...",value:h,onChange:ae=>C(ae.target.value),onFocus:()=>v.length>0&&x(!0),disabled:r,className:"pr-10","data-testid":"input-address-search"}),y&&e.jsx(za,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 animate-spin text-muted-foreground"})]}),N&&v.length>0&&e.jsx("div",{ref:G,className:"absolute z-50 w-full mt-1 bg-white border border-border rounded-lg shadow-lg max-h-60 overflow-auto",children:v.map(ae=>e.jsxs("button",{onClick:()=>A(ae),className:"w-full text-left px-4 py-3 hover:bg-slate-50 focus:bg-slate-50 focus:outline-none border-b last:border-b-0 border-slate-100","data-testid":`prediction-${ae.place_id}`,children:[e.jsx("div",{className:"font-medium text-sm text-slate-800",children:ae.structured_formatting.main_text}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ae.structured_formatting.secondary_text})]},ae.place_id))})]}),e.jsxs("div",{className:"border-t border-slate-100 pt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Or enter manually:"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{htmlFor:"streetAddress",children:"Street Address"}),e.jsx(ze,{id:"streetAddress",placeholder:"123 Main Street",value:l.streetAddress,onChange:ae=>c({...l,streetAddress:ae.target.value}),onKeyDown:B,disabled:r,"data-testid":"input-street-address"})]}),u?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{htmlFor:"unitNumber",children:"Unit / Apt Number"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ze,{id:"unitNumber",placeholder:"Unit 2B, Apt 101, #3",value:d,onChange:ae=>p(_f(ae.target.value)),onKeyDown:B,disabled:r,className:"flex-1","data-testid":"input-unit-number"}),e.jsx("button",{type:"button",onClick:()=>{p(""),m(!1)},className:"text-xs text-slate-400 hover:text-slate-600 px-2","data-testid":"button-remove-unit",children:"Remove"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Required for condos and multi-unit properties to find the correct unit."})]}):e.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-blue-600 hover:text-blue-700 hover:underline flex items-center gap-1","data-testid":"button-add-unit",children:"+ Add Unit/Apt Number (for condos, townhouses, multi-family)"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{htmlFor:"city",children:"City"}),e.jsx(ze,{id:"city",placeholder:"Chicago",value:l.city,onChange:ae=>c({...l,city:ae.target.value}),onKeyDown:B,disabled:r,"data-testid":"input-city"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{htmlFor:"state",children:"State"}),e.jsxs(sr,{value:l.state,onValueChange:ae=>c({...l,state:ae}),disabled:r,children:[e.jsx(rr,{id:"state","data-testid":"select-state",children:e.jsx(or,{placeholder:"State"})}),e.jsx(nr,{children:zq.map(ae=>e.jsx(vs,{value:ae,children:ae},ae))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{htmlFor:"zipCode",children:"ZIP Code"}),e.jsx(ze,{id:"zipCode",placeholder:"60601",value:l.zipCode,onChange:ae=>c({...l,zipCode:ae.target.value}),onKeyDown:B,disabled:r,maxLength:5,"data-testid":"input-zip-code"})]})]})]})]}),j&&e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-red-50 text-red-700 text-sm",children:[e.jsx(Di,{className:"w-4 h-4 shrink-0"}),j]}),e.jsx(De,{onClick:M,disabled:r||!l.streetAddress||!l.city||!l.zipCode,className:"w-full",size:"lg","data-testid":"button-lookup-property",children:r?e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"w-4 h-4 mr-2 animate-spin"}),"Looking up property..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Eu,{className:"w-4 h-4 mr-2"}),"Look Up Property"]})})]})]})]})}function Uv({className:t,classNames:a,showOutsideDays:s=!0,captionLayout:r="label",buttonVariant:n="ghost",formatters:i,components:l,...c}){const d=HO();return e.jsx(N5,{showOutsideDays:s,className:Q("bg-background group/calendar p-3 [--cell-size:2rem] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,t),captionLayout:r,formatters:{formatMonthDropdown:p=>
4p.toLocaleString("default",{month:"short"}),...i},classNames:{root:Q("w-fit",d.root),months:Q("relative flex flex-col gap-4 md:flex-row",d.months),month:Q("flex w-full flex-col gap-4",d.month),nav:Q("absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",d.nav),button_previous:Q(tE({variant:n}),"h-[--cell-size] w-[--cell-size] select-none p-0 aria-disabled:opacity-50",d.button_previous),button_next:Q(tE({variant:n}),"h-[--cell-size] w-[--cell-size] select-none p-0 aria-disabled:opacity-50",d.button_next),month_caption:Q("flex h-[--cell-size] w-full items-center justify-center px-[--cell-size]",d.month_caption),dropdowns:Q("flex h-[--cell-size] w-full items-center justify-center gap-1.5 text-sm font-medium",d.dropdowns),dropdown_root:Q("has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative rounded-md border",d.dropdown_root),dropdown:Q("bg-popover absolute inset-0 opacity-0",d.dropdown),caption_label:Q("select-none font-medium",r==="label"?"text-sm":"[&>svg]:text-muted-foreground flex h-8 items-center gap-1 rounded-md pl-2 pr-1 text-sm [&>svg]:size-3.5",d.caption_label),table:"w-full border-collapse",weekdays:Q("flex",d.weekdays),weekday:Q("text-muted-foreground flex-1 select-none rounded-md text-[0.8rem] font-normal",d.weekday),week:Q("mt-2 flex w-full",d.week),week_number_header:Q("w-[--cell-size] select-none",d.week_number_header),week_number:Q("text-muted-foreground select-none text-[0.8rem]",d.week_number),day:Q("group/day relative aspect-square h-full w-full select-none p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md",d.day),range_start:Q("bg-accent rounded-l-md",d.range_start),range_middle:Q("rounded-none",d.range_middle),range_end:Q("bg-accent rounded-r-md",d.range_end),today:Q("bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",d.today),outside:Q("text-muted-foreground aria-selected:text-muted-foreground",d.outside),disabled:Q("text-muted-foreground opacity-50",d.disabled),hidden:Q("invisible",d.hidden),...a},components:{Root:({className:p,rootRef:u,...m})=>e.jsx("div",{"data-slot":"calendar",ref:u,className:Q(p),...m}),Chevron:({className:p,orientation:u,...m})=>u==="left"?e.jsx(oy,{className:Q("size-4",p),...m}):u==="right"?e.jsx(fo,{className:Q("size-4",p),...m}):e.jsx(Rr,{className:Q("size-4",p),...m}),DayButton:Gq,WeekNumber:({children:p,...u})=>e.jsx("td",{...u,children:e.jsx("div",{className:"flex size-[--cell-size] items-center justify-center text-center",children:p})}),...l},...c})}function Gq({className:t,day:a,modifiers:s,...r}){const n=HO(),i=o.useRef(null);return o.useEffect(()=>{s.focused&&i.current?.focus()},[s.focused]),e.jsx(De,{ref:i,variant:"ghost",size:"icon","data-day":a.date.toLocaleDateString(),"data-selected-single":s.selected&&!s.range_start&&!s.range_end&&!s.range_middle,"data-range-start":s.range_start,"data-range-end":s.range_end,"data-range-middle":s.range_middle,className:Q("data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 flex aspect-square h-auto w-full min-w-[--cell-size] flex-col gap-1 font-normal leading-none data-[range-end=true]:rounded-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] [&>span]:text-xs [&>span]:opacity-70",n.day,t),...r})}function Hq({state:t}){if(t==="none")return null;const a={matched:"bg-slate-100 text-slate-500",mismatch:"bg-amber-100 text-amber-700",overridden:"bg-sky-100 text-sky-700"},s={matched:"Matched",mismatch:"Mismatch",overridden:"Overridden"};return e.jsx(kt,{variant:"outline",className:Q("text-[11px] px-1.5 py-0 rounded-full border-0 font-medium",a[t]),children:s[t]})}function Wq({fieldId:t,currentValue:a,sources:s,onSelectSource:r,onClose:n,onManualEdit:i,preferredSource:l,onSetPreference:c,onClearPreference:d}){const p=o.useRef(null),[u,m]=o.useState(!1),[h,f]=o.useState(String(a||"")),v=o.useRef(null);o.useEffect(()=>{function x(y){if(p.current&&!p.current.contains(y.target)){const b=y.target.closest("[data-field-row
4]");(!b||b.getAttribute("data-field-id")!==t)&&n()}}return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[t,n]),o.useEffect(()=>{u&&v.current&&(v.current.focus(),v.current.select())},[u]);const S=x=>x==null||x===""?"—":String(x),N=()=>{i(h),n()};return e.jsxs("div",{ref:p,className:"bg-white border border-slate-200 rounded-lg shadow-md p-3 mt-2 text-sm animate-in fade-in slide-in-from-top-2 duration-200 max-w-md w-full",children:[e.jsxs("div",{className:"font-medium text-slate-800 mb-1",children:["Value used: ",e.jsx("span",{className:"text-primary",children:S(a)})]}),c&&e.jsxs("div",{className:"text-[11px] text-slate-400 mb-2",children:["Click row to use • ",e.jsx(Lo,{className:"w-3 h-3 inline-block -mt-0.5"})," to set as default"]}),e.jsx("div",{className:"h-px bg-slate-200 my-2"}),u?e.jsxs("div",{className:"space-y-2",onClick:x=>x.stopPropagation(),children:[e.jsx("input",{ref:v,type:"text",value:h,onChange:x=>f(x.target.value),onKeyDown:x=>{x.key==="Enter"&&N(),x.key==="Escape"&&m(!1)},onClick:x=>x.stopPropagation(),className:"w-full px-3 py-2 text-sm border border-slate-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary",placeholder:"Enter value...","data-testid":`manual-input-${t}`}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:x=>{x.stopPropagation(),N()},className:"flex-1 px-3 py-1.5 text-xs font-medium bg-primary text-white rounded-md hover:bg-primary/90","data-testid":`save-manual-${t}`,children:"Save"}),e.jsx("button",{onClick:x=>{x.stopPropagation(),m(!1)},className:"px-3 py-1.5 text-xs font-medium text-slate-500 border border-slate-200 rounded-md hover:bg-slate-50",children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-1",children:[s.map((x,y)=>{const b=String(x.value)===String(a)&&a!==null,j=l===x.source;return e.jsxs("div",{className:Q("w-full flex items-center gap-2 px-3 py-2 rounded-md transition-colors cursor-pointer",b?"bg-primary/10 border border-primary/20":"hover:bg-slate-50 border border-transparent"),onClick:()=>r(x.value,x.source),"data-testid":`source-option-${x.source.toLowerCase().replace(/\s/g,"-")}`,children:[e.jsx(kt,{variant:"outline",className:Q("text-[11px] px-1.5 py-0 font-medium shrink-0",lD(x.source)??oD),children:iD(x.source,{abbreviated:!0})}),e.jsx("span",{className:Q("text-sm flex-1 min-w-0 truncate",b?"text-primary font-medium":"text-slate-700"),children:S(x.value)}),c&&e.jsx("button",{className:"shrink-0 p-1 rounded hover:bg-slate-100 transition-colors",onClick:T=>{T.stopPropagation(),j&&d?d(t):c(t,x.source)},title:j?"Remove as default":"Set as default source","data-testid":`pref-star-${x.source.toLowerCase().replace(/\s/g,"-")}`,children:e.jsx(Lo,{className:Q("w-4 h-4 transition-colors",j?"fill-amber-400 text-amber-400":"text-slate-300 hover:text-amber-300")})}),b&&e.jsx(Bs,{className:"w-4 h-4 text-primary shrink-0"})]},y)}),e.jsxs("button",{onClick:()=>m(!0),className:"w-full flex items-center gap-2 px-3 py-2 rounded-md text-left transition-colors hover:bg-slate-50 border border-transparent mt-1","data-testid":`manual-edit-${t}`,children:[e.jsx(kt,{variant:"outline",className:"text-[11px] px-1.5 py-0 font-medium bg-amber-50 text-amber-600 border-amber-200",children:"Manual"}),e.jsx("span",{className:"text-sm text-slate-500",children:"Enter custom value..."})]})]})]})}o.forwardRef(function({fieldId:a,label:s,currentValue:r,currentSource:n,helperText:i,conflictState:l="none",sources:c=[],preferredSource:d,onSetPreference:p,onClearPreference:u,onCh
4angeValue:m,onFieldOverride:h,isPopoverOpen:f=!1,onPopoverToggle:v},S){const[N,x]=o.useState(!1),[y,b]=o.useState(!1),j=o.useRef(null),T=v?f:N,O=F=>{v?v(a,F):x(F)};o.useImperativeHandle(S,()=>({openPopover:()=>{O(!0),b(!0),setTimeout(()=>b(!1),1500)},closePopover:()=>O(!1),scrollIntoView:()=>{j.current?.scrollIntoView({behavior:"smooth",block:"center"})}}));const E=()=>{O(!T)},R=(F,A)=>{const M=r;m&&m(F,{fieldId:a,chosenSource:A,previousValue:M}),h&&h({fieldId:a,oldValue:M,newValue:F,chosenSource:A,allSources:c}),O(!1)},G=F=>{const A=r;let M=F;if(typeof r=="number"||!isNaN(Number(F))){const B=parseFloat(F);isNaN(B)||(M=B)}m&&m(M,{fieldId:a,chosenSource:"User",previousValue:A}),h&&h({fieldId:a,oldValue:A,newValue:M,chosenSource:"User",allSources:c})},U=r!=null&&r!==""?String(r):"—",C=l!=="none"&&c.length>0;return e.jsxs("div",{ref:j,"data-field-row":!0,"data-field-id":a,"data-testid":`field-row-${a}`,children:[e.jsxs("div",{onClick:E,className:Q("px-3 py-2.5 rounded-md transition-all cursor-pointer hover:bg-slate-50",C&&"ring-1 ring-amber-200",y&&"bg-amber-50",T&&"bg-slate-50"),children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase text-slate-500 tracking-wide",children:s}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[(()=>{const F=n&&String(n)!==""?String(n):"Derived";return e.jsx(kt,{variant:"outline",className:Q("text-[11px] px-1.5 py-0 font-medium",lD(F)??oD),"data-testid":`badge-source-${F.toLowerCase().replace(/\s+/g,"-")}`,children:iD(F,{abbreviated:!0})})})(),e.jsx(Hq,{state:l})]})]}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-800",children:U}),i&&e.jsx("div",{className:"text-[11px] text-slate-400 mt-0.5",children:i})]}),T&&e.jsx("div",{className:"px-3",children:e.jsx(Wq,{fieldId:a,currentValue:r,sources:c,onSelectSource:R,onClose:()=>O(!1),onManualEdit:G,preferredSource:d,onSetPreference:p,onClearPreference:u})})]})});function Kq(t,a,s,r){if(r)return"none";if(s)return"overridden";const n=t.filter(c=>c.value!==null&&c.value!==void 0&&c.value!=="");return n.length<=1?"none":n.every(c=>String(c.value)===String(n[0].value))?"matched":n.some(c=>String(c.value)===String(a))?"mismatch":"overridden"}function PT(t){return t?.alternatives?Object.entries(t.alternatives).map(([a,s])=>({source:cD(a),value:s})).filter(a=>a.value!==null&&a.value!==void 0&&a.value!==""):[]}function hy(t){if(!t)return"none";const a=PT(t);return Kq(a,t.value,t.isEdited,t.isConfirmed)}function Qq({state:t}){return t==="none"?null:t==="matched"?e.jsx(Bs,{size:10,className:"text-slate-400"}):t==="mismatch"?e.jsx(Ns,{size:10,className:"text-amber-500"}):e.jsx(WO,{size:10,className:"text-sky-500"})}const zw=Qq;function qw(){return e.jsx("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded bg-slate-100 text-slate-500 border border-slate-200","data-testid":"badge-not-applicable",children:"N/A"})}function Yw({text:t}){return e.jsx("span",{title:t,className:"inline-flex shrink-0 cursor-help align-middle",children:e.jsx(on,{className:"w-3 h-3 text-slate-400","aria-label":t})})}function cg({label:t,field:a,onUpdate:s,wide:r,isSelect:n,isDate:i,selectOptions:l,selectOptionPairs:c,labelInfo:d,notApplicable:p,testId:u,custom:m,readOnly:h}){const f=a||{value:null},[v,S]=o.useState(!1),[N,x]=o.useState(f.value!=null?String(f.value):""),[y,b]=o.useState(!1);if(o.useEffect(()=>{!v&&a&&x(a.value!=null?String(a.value):"")},[a?.value,v]),!a)return h?e.jsxs("div",{className:Q("flex items-center gap-2 px-2.5 py-[6px]",r&&"col-span-2"),"data-testid":u,children:[e.jsx("span",{className:"text-[11px] font-medium uppercase text-slate-400 tracking-wide whitespace-nowrap min-w-[80px]",children:t}),e.jsx("span",{className:"text-[13px] font-semibold text-slate-300 italic",children:"—"})]}):e.jsxs("div",{className:Q("flex items-center gap-2 px-2.5 py-[6px] cursor-pointer hover:bg-slate-50 rounded transition-colors",r&&"col-span-2"),"data-testid":u,onClick:()=>{s({value:"",source:"User",isEdited:!0,alternatives:{}}),S(!0)},children:[e.jsx("span",{className:"text-[11px] font-medium uppercase text-slate-400 tracking-wide whitespace-nowrap min-w-[80px]",children:t}),e.jsx("span",{className:"text-[13px] font-semibold text-slate-300 italic",children:"—"})]});const j=hy(a),T=j==="mismatch"||j==="overridden",O=a.alternatives&&Object.keys(a.alternatives).length>1,E=!a.value||String(a.value).trim()==="",R=()=>{s({...a,value:N,source:"User",isEdited:!0}),S(!1)};if(n&&(l||c)){const G=c??(l??[]).map(F=>({value:F,label:F})),U=a.value!=null?String(a.value):"",C=!U||G.some(F=>F.value===U);return e.jsxs("div",{className:Q("flex items-center gap-2 px-2.5 py-[6px] hover:bg-blue-50/40 transition-colors",r&&"col-span-2"),"data-testid":u,children:[e.jsxs("span",{className:"flex items-center gap-1 text-[11px] font-medium uppercase text-slate-400 tracking-wide whitespace-nowrap min-w-[80px]",children:[t,d&&e.jsx(Yw,{text:d})]}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("select",{value:U,onChange:F=>s({...a,value:F.target.value,source:"User",isEdited:!0}),className:"w-full h-6 px-1 text-[13px] font-semibold rounded border border-slate-200 bg-white focus:ring-1 focus:ring-primary/20 outline-none text-slate-800","data-testid":u?`${u}-select`:void 0,children:[e.jsx("option",{value:"",children:"Select..."}),G.map(F=>e.jsx("option",{value:F.value,children:F.label},F.value)),!C&&e.jsxs("option",{value:U,children:[U," (saved value)"]})]})}),e.jsxs("div",{className:"shrink-0 flex items-center gap-1",children:[e.jsx(zw,{state:j}),E?p?e.jsx(qw,{}):e.jsx(UE,{}):e.jsx(pd,{source:a.source})]})]})}return e.jsxs("div",{className:Q("relative",r&&"col-span-2"),children:[e.jsxs("div",{onClick:()=>{O&&!h?b(!y):!v&&!h&&S(!0)},className:Q("flex items-center gap-2 px-2.5 py-[6px] transition-all",!h&&"cursor-pointer hover:bg-slate-50",T&&"ring-1 ring-amber-200 bg-amber-50/30",y&&"bg-slate-50 ring-1 ring-slate-300"),"data-testid":u,children:[e.jsxs("span",{className:"flex items-center gap-1 text-[11px] font-medium uppercase text-slate-400 tracking-wide whitespace-nowrap min-w-[80px]",children:[t,d&&e.jsx(Yw,{text:d})]}),e.jsx("div",{className:"flex-1 min-w-0",children:m||(v?e.jsx("input",{type:i?"date":"text",autoFocus:!0,value:N,onChange:G=>x(G.target.value),onBlur:R,onKeyDown:G=>{G.key==="Enter"&&R(),G.key==="Escape"&&(x(a.value!=null?String(a.value):""),S(!1))},onClick:G=>G.stopPropagation(),className:"w-full h-6 px-1 text-[13px] font-semibold rounded border border-slate-300 bg-white focus:ring-1 focus:ring-primary/20 outline-none text-slate-800 -mx-1","data-testid":u?`${u}-input`:void 0}):E?p?e.jsx("span",{className:"text-[12px] text-slate-400 italic",children:"Not applicable"}):e.jsxs("span",{className:"text-[12px] text-slate-400 italic flex items-center gap-1",children:[e.jsx(ur,{className:"w-3 h-3"}),"No data"]}):e.jsx("span",{className:Q("text-[13px] font-semibold text-slate-800",r?"":"truncate block"),children:String(a.value)}))}),e.jsxs("div",{className:"shrink-0 flex items-center gap-1",children:[e.jsx(zw,{state:j}),E?p?e.jsx(qw,{}):e.jsx(UE,{}):e.jsx(pd,{source:a.source})]})]}),e.jsx(I0,{children:y&&O&&a.alternatives&&e.jsxs(Kh.div,{initial:{opacity:0,y:-4}
4,animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.12},className:"absolute left-0 right-0 top-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg p-2.5 z-50","data-testid":u?`${u}-popover`:void 0,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("span",{className:"text-[10px] font-medium text-slate-500",children:["Using: ",e.jsx("span",{className:"text-indigo-600 font-semibold",children:String(a.value)})]}),e.jsx("button",{onClick:G=>{G.stopPropagation(),b(!1)},className:"p-0.5 text-slate-400 hover:text-slate-600 rounded",children:e.jsx(ur,{size:12})})]}),e.jsxs("div",{className:"space-y-0.5",children:[Object.entries(a.alternatives).map(([G,U])=>{if(U==null||String(U).trim()==="")return null;const C=cD(G),F=String(U)===String(a.value);return e.jsxs("div",{onClick:A=>{A.stopPropagation();const M=typeof U=="object"&&U!==null&&!Array.isArray(U)?U.Message??U.value??U.Value??(()=>{try{return JSON.stringify(U)}catch{return""}})():U;s({...a,value:
4M,source:C,isEdited:!0}),b(!1)},className:Q("flex items-center gap-2 px-2 py-1 rounded transition-colors cursor-pointer",F?"bg-indigo-50 border border-indigo-200":"hover:bg-slate-50 border border-transparent"),children:[e.jsx(pd,{source:C}),e.jsx("span",{className:Q("text-[12px] flex-1",F?"text-slate-900 font-medium":"text-slate-600"),children:String(U)}),F&&e.jsx(Bs,{size:11,className:"text-indigo-600 shrink-0"})]},G)}),e.jsxs("div",{onClick:G=>{G.stopPropagation(),b(!1),S(!0)},className:"flex items-center gap-2 px-2 py-1 rounded hover:bg-slate-50 cursor-pointer border border-transparent mt-0.5",children:[e.jsx(pd,{source:"User"}),e.jsx("span",{className:"text-[11px] text-slate-400 italic",children:"Enter custom..."})]})]})]})})]})}function Iu({title:t,rightAction:a}){return e.jsxs("div",{className:"wiz-compact-section-header flex items-center justify-between px-2.5 py-1.5 bg-slate-50/80 border-b border-slate-200 border-l-2 border-l-[#C5A572] col-span-2",children:[e.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-slate-500",children:t}),a]})}function oj({fields:t,filterMode:a="all"}){const s=a==="conflicts"?t.filter(i=>{if(!i.field)return!1;const l=hy(i.field);return l==="mismatch"||l==="overridden"}):a==="missing"?t.filter(i=>i.notApplicable?!1:i.field?!i.field.value&&i.field.value!==!1&&i.field.value!==0:!0):t,r=s.filter(i=>i.wide),n=s.filter(i=>!i.wide);return e.jsxs("div",{className:"grid grid-cols-2 gap-0",children:[r.map(i=>e.jsx("div",{className:"col-span-2 border-b border-slate-100 last:border-b-0",children:e.jsx(cg,{...i})},i.label)),e.jsx("div",{className:"divide-y divide-slate-100 border-r border-slate-100",children:n.filter((i,l)=>l%2===0).map(i=>e.jsx(cg,{...i},i.label))}),e.jsx("div",{className:"divide-y divide-slate-100",children:n.filter((i,l)=>l%2===1).map(i=>e.jsx(cg,{...i},i.label))})]})}function Bb(t){if(!t||typeof t!="object")return!1;const a=t,s=a.payload&&typeof a.payload=="object"?a.payload:a,r=s.mappedFields&&typeof s.mappedFields=="object"?s.mappedFields.fields:null,n=s.rawData&&typeof s.rawData=="object"?s.rawData.extractedFields:null,i=s.banksEvidence&&typeof s.banksEvidence=="object"?s.banksEvidence:null,l=d=>{if(!d)return!1;for(const p of Object.values(d))if(!(!p||typeof p!="object"))for(const u of Object.values(p)){const m=u&&typeof u=="object"&&"value"in u?u.value:u;if(m!=null&&m!=="")return!0}return!1};if(l(r)||l(n))return!0;const c=i?.categories;return["data","uad36","photos","sketch","video","notes","audio"].some(d=>Array.isArray(c?.[d])&&(c?.[d]).length>0)}function Zq(t,a,s,r){const n={};if(!t)return n;for(const[i,l]of Object.entries(t))if(l?.source==="Inspection"&&!r){const c=s.find(u=>u.id===i),d=c?.propertyDataKey?a[c.propertyDataKey]:void 0,p=d&&typeof d=="object"&&d.source!=null?String(d.source):"User";n[i]={...l,source:p}}else n[i]=l;return n}function ny(t,a){if(a||!t||typeof t!="object")return t;const s={...t};let r=!1;for(const[n,i]of Object.entries(t)){if(!i||typeof i!="object")continue;const l=i,c=l.source!=null?String(l.source):"",d=c==="Inspection"||c==="inspection",p=l.alternatives&&typeof l.alternatives=="object"&&("inspection"in l.alternatives||"Inspection"in l.alternatives);if(!d&&!p)continue;const u=l.alternatives&&typeof l.alternatives=="object"?Object.fromEntries(Object.entries(l.alternatives).filter(([h])=>h!=="inspection"&&h!=="Inspection")):l.alternatives;let m=c;if(d){const h=[["public_record","PR"],["publicrecord","PR"],["PR","PR"],["mls","MLS"],["MLS","MLS"],["zoneomics","Zoneomics"],["Zoneomics","Zoneomics"],["fema","FEMA"],["FEMA","FEMA"],["bt","Derived"],["echo","Derived"],["BT","Derived"]];let f=null;const v=u??{};for(const[S,N]of h){const x=v[S];if(x!=null&&x!==""){f=N;break}}m=f??"Derived"}s[n]={...l,source:m,alternatives:u},r=!0}return r?s:t}function S0(t){if(t.manualOverride)return"User";const a=t.smartFieldSource;if(a&&a!=="")return a;const s=t.localSource;return s&&s!==""?s:t.hasDefault?"Default":"Derived"}function Jq(t){switch((t??"").trim().toLowerCase()){case"borrower":return"Borrower";case"seller":return"PropertySeller";case"owner":return"PropertyOwner";default:return(t??"").trim()}}function Xq(t){switch((t??"").trim()){case"Borrower":return"borrower";case"PropertySeller":return"seller";case"PropertyOwner":return"owner";default:return(t??"").trim().toLowerCase()}}function xk(t){return t.partyType==="entity"?{partyType:"legalEntity",fullName:(t.entityName??"").trim(),roles:[]}:{partyType:"individual",firstName:(t.firstName??"").trim(),middleName:(t.middleName??"").trim(),lastName:(t.lastName??"").trim(),suffixName:(t.suffix??"").trim(),roles:[]}}function eY(t){const a=new Map;for(const s of t){const r=xk(s);if(pg(r).length===0)continue;const n=Jq(s.partyRole);if(!n)continue;const i=AL(r),l=a.get(i);l?l.roles.includes(n)||l.roles.push(n):a.set(i,{...r,roles:[n]})}return Array.from(a.values())}function Gw(t,a){return`${t}|${AL(a)}`}function tY(t,a){return a.partyType==="legalEntity"?{partyRole:t,partyType:"entity",firstName:null,middleName:null,lastName:null,suffix:null,entityName:(a.fullName??"").trim()||null}:{partyRole:t,partyType:"individual",firstName:(a.firstName??"").trim()||null,middleName:(a.middleName??"").trim()||null,lastName:(a.lastName??"").trim()||null,suffix:(a.suffixName??"").trim()||null,entityName:null}}function aY(t,a){const s=new Map;for(const l of t){if(pg(l).length===0)continue;const c=Array.isArray(l.roles)?l.roles:[];for(const d of c){const p=Xq(d);if(!p)continue;const u=Gw(p,l);s.has(u)||s.set(u,tY(p,l))}}const r=new Map;for(const l of a){const c=xk(l);if(pg(c).length===0)continue;const d=(l.partyRole??"").trim().toLowerCase();r.set(Gw(d,c),l)}const n=[];for(const[l,c]of Array.from(s.entries()))r.has(l)||n.push(c);const i=[];for(const[l,c]of Array.from(r.entries()))s.has(l)||i.push(c.id);return{creates:n,deleteIds:i}}const Hw=800;function QI(t){const a=ku(),s=Vr({queryKey:["order",t,"parties"],enabled:!!t,queryFn:async()=>(await Qo("GET",`/api/v2/orders/${t}/parties`)).json()}),r=Vr({queryKey:["order",t,"interested-parties"],enabled:!!t,queryFn:async()=>(await Qo("GET",`/api/v2/orders/${t}/interested-parties`)).json()}
4),[n,i]=o.useState([]),[l,c]=o.useState([]),[d,p]=o.useState(!1),u=o.useRef([]),m=o.useRef([]),h=o.useRef([]),f=o.useRef(!1),v=o.useRef(!1);o.useEffect(()=>{const O=s.data?.parties;if(O&&(u.current=O.map(E=>({id:E.id,partyRole:E.partyRole,partyType:E.partyType,firstName:E.firstName??null,middleName:E.middleName??null,lastName:E.lastName??null,suffix:E.suffix??null,entityName:E.entityName??null})),!f.current)){const E=eY(u.current);m.current=E,i(E)}},[s.data]),o.useEffect(()=>{const O=r.data?.interestedParties;O&&(v.current||(h.current=O,c(O)))},[r.data]);const S=o.useCallback(()=>{a.invalidateQueries({queryKey:["order",t]}),a.invalidateQueries({queryKey:["orders"]}),a.invalidateQueries({queryKey:["admin-orders-vault"]})},[a,t]),N=o.useCallback(async O=>{const{creates:E,deleteIds:R}=aY(O,u.current);if(E.length===0&&R.length===0){f.current=!1;return}p(!0);try{for(const G of E)await Qo("POST",`/api/v2/orders/${t}/parties`,G);for(const G of R)await Qo("DELETE",`/api/v2/orders/${t}/parties/${G}`);f.current=!1,await a.invalidateQueries({queryKey:["order",t,"parties"]}),S()}finally{p(!1)}},[t,a,S]),x=o.useCallback(async O=>{p(!0);try{await Qo("PUT",`/api/v2/orders/${t}/interested-parties`,{interestedParties:O}),v.current=!1,await a.invalidateQueries({queryKey:["order",t,"interested-parties"]}),S()}finally{p(!1)}},[t,a,S]),y=o.useRef(null),b=o.useRef(null),j=o.useCallback(O=>{f.current=!0,m.current=O,i(O),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{N(O)},Hw)},[N]),T=o.useCallback(O=>{v.current=!0,h.current=O,c(O),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{x(O)},Hw)},[x]);return o.useEffect(()=>()=>{y.current&&(clearTimeout(y.current),f.current&&N(m.current)),b.current&&(clearTimeout(b.current),v.current&&x(h.current))},[]),{contacts:n,setContacts:j,interested:l,setInterested:T,isLoading:s.isLoading||r.isLoading,isSaving:d}}function OT(t){return j_(t)?null:t.name.trim()?"confirmed":"missing"}function LT(t){const a=pg(t).trim(),s=Array.isArray(t.roles)?t.roles:[];return!a&&s.length===0?null:a?"confirmed":"missing"}function Ww(t,a){return a==="all"?!0:t===null?!1:t===a}function Kw(t){const a={missing:0,conflicts:0,unconfirmed:0,confirmed:0};for(const s of t)s&&a[s]++;return a}function sY({orderId:t,compact:a=!1,onInterestedChange:s,rowVisible:r}){const{interested:n,setInterested:i}=QI(t);return e.jsx(T_,{value:n,onChange:l=>{i(l),s?.(l)},compact:a,rowVisible:r,emptyStateText:'No interested parties added — this list is optional and an empty list is never counted as unfilled. Use "Add party" to add a Client, Lender, AMC, or other party involved in the assignment.',rowUnfilled:l=>OT(l)==="missing"})}function rY({orderId:t,testIdPrefix:a="core-contact",onContactsChange:s,rowVisible:r}){const{contacts:n,setContacts:i}=QI(t);return e.jsx(BU,{testIdPrefix:a,value:n,onChange:l=>{i(l),s?.(l)},rowVisible:r,addButtonLabel:"Add contact",emptyStateText:'No contacts added — this list is optional and an empty list is never counted as unfilled. Use "Add contact" to add a Borrower, Seller, or Owner of Public Record.',rowUnfilled:l=>LT(l)==="missing"})}const rv="PropertyOwner",nY=/\b(llc|l\.l\.c\.?|inc\.?|incorporated|corp\.?|corporation|trust|trustee|trustees|estate|company|co\.|ltd\.?|lp|llp|lllp|partners|partnership|holdings|properties|investments|ventures|group|bank|association|assn\.?|hoa|church|ministries|foundation|city of|county of|state of|university|school|authority)\b/i;function iY(t){return nY.test(t)}function lj(t){const a=t.trim().split(/\s+/).filter(Boolean);return a.length===0?{firstName:"",middleName:"",lastName:""}:a.length===1?{firstName:a[0],middleName:"",lastName:""}:a.length===2?{firstName:a[0],middleName:"",lastName:a[1]}:{firstName:a[0],middleName:a.slice(1,-1).join(" "),lastName:a[a.length-1]}}function oY(t){const a=(t??"").trim().replace(/\s+/g," ");if(!a)return[];if(iY(a))return[{partyType:"legalEntity",fullName:a,roles:[rv]}];const s=a.split(/\s*&\s*|\s+and\s+/i).map(n=>n.trim()).filter(Boolean);if(s.length<=1)return[{partyType:"individual",...lj(a),roles:[rv]}];const r=lj(s[s.length-1]);return s.map((n,i)=>{const l=lj(n),c=l.lastName||(i<s.length-1?r.lastName:"");return{partyType:"individual",firstName:l.firstName,middleName:l.middleName,lastName:c,roles:[rv]}})}const DT=[{value:"OwnerOccupied",label:"Owner-occupied"},{value:"Tenant",label:"Tenant"},{value:"Vacant",label:"Vacant"}],Qw="Who occupies the subject property as of the effective date — the owner, a tenant, or no one (vacant). This drives the occupancy status reported in the appraisal.";function lY(t){const a=String(t??"").trim();if(!a)return null;const s=DT.find(r=>r.value.toLowerCase()===a.toLowerCase());return s?s.value:/^owner([\s-]?occupied|[\s-]?occupant)?$/i.test(a)?"OwnerOccupied":/^tenant([\s-]?occupied)?$/i.test(a)?"Tenant":/^vacant$/i.test(a)?"Vacant":null}const cY={contract:"Purchase Contract",engagement:"Engagement Letter",order_form:"Order Form",addendum:"Addendum",other:"Other"},dY=[{id:"order",label:"Assignment"},{id:"parties",label:"Parties"},{id:"appraiser",label:"Appraiser"},{id:"revision",label:"Revision"},{id:"documents",label:"Documents"}],uY=["Active","ACT","New","NEW","Pending","PND","PEND","Under Contract","UCB","UC","Price Change","PC","Sold","SOLD","Closed","CLSD","CL"];function pY({data:t,setData:a,mlsListingData:s,mlsLookupNoListing:r=!1,documents:n=[],onDocumentsChange:i,orderId:l,inspectionCaptured:c=!1,evalStyle:d=!1}){const p=o.useMemo(()=>ny(t,c),[t,c]),u=o.useRef(null),m=o.useRef(null),[h,f]=o.useState(null),[v,S]=o.useState(null),[N,x]=o.use
4State(!1),[y,b]=o.useState(!1),[j,T]=o.useState(null),[O,E]=o.useState(null),[R,G]=o.useState("all"),[U,C]=o.useState("order"),[F,A]=o.useState({}),M=o.useCallback((Ce,St)=>{A(vt=>{const Ve=vt[Ce];return Ve&&Ve.missing===St.missing&&Ve.conflicts===St.conflicts&&Ve.unconfirmed===St.unconfirmed&&Ve.confirmed===St.confirmed?vt:{...vt,[Ce]:St}})},[]);o.useEffect(()=>{if(h?.file){const Ce=URL.createObjectURL(h.file);return S(Ce),()=>URL.revokeObjectURL(Ce)}S(h?.url||null)},[h]);const oe=Vr({queryKey:["/api/v2/orders",l,"participants"],enabled:!!l}).data?.participants??[],ae=o.useCallback(Ce=>oe.find(St=>(St.roleName||"").toLowerCase()===Ce),[oe]),D=o.useRef({}),_=o.useRef({}),$=o.useCallback(async Ce=>{if(!l)return;const St=_.current[Ce];if(!St)return;delete _.current[Ce];const vt=ae(Ce),Ve=St.name!==void 0?St.name?.trim()||null:vt?.displayName??null,sa=St.contact!==void 0?St.contact?.trim()||null:vt?.contact??null;try{if(vt){const tt={};if(St.name!==void 0&&(tt.displayName=Ve,vt.companyId&&(tt.companyId=null)),St.contact!==void 0&&(tt.contact=sa),Object.keys(tt).length===0)return;await Qo("PATCH",`/api/v2/orders/${l}/participants/${vt.id}`,tt)}else{if(!Ve)return;await Qo("POST",`/api/v2/orders/${l}/participants`,{roleName:Ce,displayName:Ve,contact:sa})}fi.invalidateQueries({queryKey:["/api/v2/orders",l,"participants"]}),fi.invalidateQueries({queryKey:["/api/v2/orders",l]})}catch(tt){console.error(`[Step1] participant upsert (${Ce}) failed`,tt)}},[l,ae]),z=o.useCallback((Ce,St)=>{l&&(_.current[Ce]={..._.current[Ce],...St},D.current[Ce]&&clearTimeout(D.current[Ce]),D.current[Ce]=setTimeout(()=>{$(Ce)},600))},[l,$]);o.useEffect(()=>()=>{for(const Ce of["client","lender"])D.current[Ce]&&(clearTimeout(D.current[Ce]),$(Ce))},[]);const V=o.useCallback((Ce,St)=>{if(a({...p,[Ce]:St}),!l||!St.isEdited)return;const vt=St.value,Ve=vt==null?null:String(vt);Ce==="client"?z("client",{name:Ve}):Ce==="clientAddress"?z("client",{contact:Ve}):Ce==="lender"?z("lender",{name:Ve}):Ce==="lenderAddress"&&z("lender",{contact:Ve})},[p,a,l,z]),le=o.useCallback(Ce=>{a({...p,...Ce})},[p,a]),W=o.useCallback(Ce=>{const St=vt=>{const Ve=Ce.find(sa=>Array.isArray(sa.roles)&&sa.roles.includes(vt));return Ve?pg(Ve):""};a({...p,borrower:{value:St("Borrower"),source:"User",isEdited:!0,alternatives:{}},coBorrower:{value:St("co-borrower"),source:"User",isEdited:!0,alternatives:{}},owner:{value:St("PropertyOwner"),source:"User",isEdited:!0,alternatives:{}}})},[p,a]),me=o.useCallback(Ce=>{const St=vt=>{const Ve=Ce.find(sa=>Array.isArray(sa.roles)&&sa.roles.includes(vt));return Ve?(Ve.name||"").trim():""};a({...p,client:{value:St("Client"),source:"User",isEdited:!0,alternatives:{}},lender:{value:St("Lender"),source:"User",isEdited:!0,alternatives:{}}})},[p,a]),Z=o.useCallback(Ce=>{if(!Ce||!i)return;const St=Array.from(Ce).map(vt=>({id:`upload-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,name:vt.name,type:vt.name.toLowerCase().includes("contract")?"contract":vt.name.toLowerCase().includes("engagement")?"engagement":vt.name.toLowerCase().includes("order")?"order_form":vt.name.toLowerCase().includes("addendum")?"addendum":"other",source:"Upload",file:vt,uploadedAt:new Date().toISOString(),size:vt.size}));i([...n,...St])},[n,i]),pe=o.useCallback(Ce=>{i&&i(n.filter(St=>St.id!==Ce))},[n,i]),se=Ce=>Ce?Ce<1024?`${Ce} B`:Ce<1024*1024?`${(Ce/1024).toFixed(1)} KB`:`${(Ce/(1024*1024)).toFixed(1)} MB`:"",fe=o.useCallback(async Ce=>{if(Ce.type!=="application/pdf"){E("Please upload a PDF file.");return}if(Ce.size>20*1024*1024){E("File is too large. Maximum size is 20 MB.");return}b(!0),E(null),T(Ce.name);try{const St=new FormData;St.append("file",Ce);const vt=await fetch("/api/analyze-contract",{method:"POST",body:St});if(!vt.ok){const it=await vt.json().catch(()=>null);E(it?.error||`Analysis failed (${vt.status})`);return}const Ve=await vt.json();if(!Ve.success){E(Ve.error||"Analysis failed");return}const sa={};Ve.contractPrice&&(sa.contractPrice={value:Ve.contractPrice,source:"Derived",isEdited:!1,alternatives:{}}),Ve.contractDate&&(sa.contractDate={value:Ve.contractDate,source:"Derived",isEdited:!1,alternatives:{}});let tt=Ve.analysisExplanation||"";Ve.concessions&&Ve.concessionsDescription?tt+=`
5
6Financial Assistance/Concessions: $${Number(Ve.concessions).toLocaleStr
6ing()} - ${Ve.concessionsDescription}`:Ve.concessions&&(tt+=`
7
8Financial Assistance/Concessions: $${Number(Ve.concessions).toLocaleString()}`),Ve.saleType&&(tt+=`
9Sale Type: ${Ve.saleType}`),Ve.sellerIsOwnerOfRecord!==null&&Ve.sellerIsOwnerOfRecord!==void 0&&(tt+=`
10Seller is owner of record: ${Ve.sellerIsOwnerOfRecord?"Yes":"No/Unable to determine"}`),tt.trim()&&(sa.contractAnalysisExplanation={value:tt.trim(),source:"Derived",isEdited:!1,alternatives:{}}),sa.contractAnalyzed={value:!0,source:"Derived",isEdited:!1,alternatives:{}},le(sa)}catch(St){E(St instanceof Error?St.message:"Failed to analyze contract")}finally{b(!1)}},[le]),ue=p.assignmentType.value==="Purchase Transaction",be=p.offeredForSale?.value===!0,H=o.useMemo(()=>{const Ce=String(p.assignmentType.value??""),St=Ce!==""&&Ce!=="Purchase Transaction"&&Ce!=="Refinance Transaction",vt=!p.loanNumber?.value&&p.loanNumber?.value!==0;return St&&vt},[p.assignmentType.value,p.loanNumber?.value]),ye=o.useMemo(()=>{const Ce=Qt=>!Qt?.value&&Qt?.value!==!1&&Qt?.value!==0,St={subjectAddress:Ce(p.subjectAddress),effectiveDate:Ce(p.effectiveDate),assignmentType:Ce(p.assignmentType)},vt={lender:Ce(p.lender),client:Ce(p.client),loanNumber:Ce(p.loanNumber)&&!(String(p.assignmentType.value??"")!==""&&p.assignmentType.value!=="Purchase Transaction"&&p.assignmentType.value!=="Refinance Transaction")},Ve={owner:Ce(p.owner),borrower:Ce(p.borrower),coBorrower:Ce(p.coBorrower),occupant:Ce(p.occupant)},sa={appraiser:Ce(p.appraiser),appraiserLicense:Ce(p.appraiserLicense)},tt=Object.values(St).filter(Boolean).length,it=Ce(p.offeredForSale)?1:0,Je=Object.values(vt).filter(Boolean).length,ht=Object.values(Ve).filter(Boolean).length,Kt=Object.values(sa).filter(Boolean).length,Sa=tt+Je+ht+Kt;return{orderEmpty:tt,listingEmpty:it,lenderEmpty:Je,ownerEmpty:ht,appraiserEmpty:Kt,totalEmpty:Sa}},[p]),de=o.useCallback(Ce=>Ce?!Ce.value&&Ce.value!==!1&&Ce.value!==0:!0,[]),ge=o.useCallback(Ce=>{const St=de(Ce),vt=Ce&&hy(Ce)==="mismatch"?"mismatch":St?"missing":"matched";return dD({state:vt,hasValue:!St,source:Ce?.source,confirmed:!!Ce?.isConfirmed},{prefilledCountsAsDone:!0})},[de]),Be=o.useCallback(Ce=>{if(Ce==="loanNumber"&&H)return null;const St=p[Ce];return Ce==="assignmentType"&&String(St?.value??"")==="Other"&&!String(p.assignmentTypeOtherDescription?.value??"").trim()?"missing":ge(St)},[p,ge,H]),He=o.useCallback((...Ce)=>R==="all"?!0:Ce.some(St=>ge(St)===R),[R,ge]),Ie=o.useCallback((...Ce)=>R==="all"?!0:Ce.some(St=>Be(St)===R),[R,Be]),ce=o.useMemo(()=>["subjectAddress","effectiveDate","assignmentType","lender","client","loanNumber","owner","borrower","coBorrower","occupant","appraiser","appraiserLicense","appraiserLicenseExpiration","appraiserLicenseType","lenderAddress","clientAddress","appraiserCompany","appraiserLicenseState"],[]),Pe=o.useMemo(()=>{const Ce={missing:0,conflicts:0,unconfirmed:0,confirmed:0};for(const St of ce){const vt=Be(St);vt&&Ce[vt]++}return Ce},[ce,Be]);Pe.missing+Pe.conflicts+Pe.unconfirmed+Pe.confirmed;const{interested:We,contacts:Re,setContacts:ne,isLoading:Me}=QI(l||""),lt=o.useRef(!1);o.useEffect(()=>{if(lt.current||!l||Me)return;const Ce=String(p.owner?.value??"").trim();if(!Ce)return;const St=Re||[];if(St.some(tt=>(Array.isArray(tt.roles)?tt.roles:[]).includes(rv))){lt.current=!0;return}const vt=oY(Ce),Ve=new Set(St.map(tt=>pg(tt).trim().toLowerCase())),sa=vt.filter(tt=>!Ve.has(pg(tt).trim().toLowerCase()));lt.current=!0,sa.length>0&&ne([...St,...sa])},[l,Me,Re,p.owner?.value,ne]);const Tt=o.useCallback((...Ce)=>{const St={missing:0,conflicts:0,unconfirmed:0,confirmed:0};for(const vt of Ce)St.missing+=vt.missing,St.conflicts+=vt.conflicts,St.unconfirmed+=vt.unconfirmed,St.confirmed+=vt.confirmed;return St},[]),je=o.useMemo(()=>{const Ce={missing:0,conflicts:0,unconfirmed:0,confirmed:0},St=["subjectAddress","effectiveDate","assignmentType"];He(p.offeredForSale)&&St.push("offeredForSale");for(const vt of St){const Ve=Be(vt);Ve&&Ce[Ve]++}return Ce},[p,Be,He]),Le=o.useMemo(()=>{if(!l){const sa={missing:0,conflicts:0,unconfirmed:0,confirmed:0};for(const tt of["lender","client","lenderAddress","clientAddress","loanNumber","owner","borrower","coB
10orrower","occupant"]){const it=Be(tt);it&&sa[it]++}return sa}const Ce=Kw((We||[]).map(OT)),St=Kw((Re||[]).map(LT)),vt={missing:0,conflicts:0,unconfirmed:0,confirmed:0},Ve=Be("loanNumber");return Ve&&vt[Ve]++,vt[ge(p.occupant)]++,Tt(Ce,St,vt)},[l,We,Re,p,ge,Be,Tt]),ut={missing:0,conflicts:0,unconfirmed:0,confirmed:0},st=o.useMemo(()=>({order:je,parties:Le,appraiser:F.appraiser??ut,revision:F.revision??ut,documents:F.documents??ut}),[je,Le,F]),Xt=o.useMemo(()=>Tt(st.order,st.parties,st.appraiser,st.revision,st.documents),[st,Tt]),ua=d?Xt:Pe,Oa=ua.missing+ua.conflicts+ua.unconfirmed+ua.confirmed,Xa=o.useMemo(()=>{const Ce=p.occupant||{value:"",source:"User",isEdited:!1,alternatives:{}},St=lY(Ce.value);return St!==null&&St!==Ce.value?{...Ce,value:St}:Ce},[p.occupant]),qa=MA(),os=MA(),ya=MA(),At=o.useCallback(Ce=>Ww(OT(Ce),R),[R]),Fe=o.useCallback(Ce=>Ww(LT(Ce),R),[R]),Oe=o.useCallback(()=>{const Ce={};for(const St of ce){const vt=p[St];vt&&ge(vt)==="unconfirmed"&&(Ce[St]={...vt,isConfirmed:!0})}Object.keys(Ce).length>0&&le(Ce)},[ce,p,ge,le]),rt=o.useMemo(()=>{if(!s?.status)return!1;const St=(typeof s.status=="string"?s.status:Array.isArray(s.status)?s.status[0]:String(s.status))?.toLowerCase()||"",vt=uY.some(ht=>St.includes(ht.toLowerCase())||ht.toLowerCase().includes(St));if(!vt)return!1;const Ve=p.effectiveDate?.value?Hy(p.effectiveDate.value,"MM/dd/yyyy",new Date):new Date,sa=Ex(Ve)?Ve:new Date,tt=KO(sa,12),it=s.listDate||s.saleDate;if(!it)return vt;const Je=new Date(it);return Ex(Je)?!A5(Je,tt):vt},[s?.status,s?.listDate,s?.saleDate,p.effectiveDate?.value]);o.useEffect(()=>{if(!rt||!s?.mlsNumber)return;const Ce=p.offeredForSale?.isEdited||p.offeredForSaleDataSource?.isEdited,St=p.offeredForSaleDataSource?.source==="MLS"&&p.offeredForSaleDataSource?.value;if(Ce||St)return;const vt=s.mlsNumber,Ve=typeof s.status=="string"?s.status:Array.isArray(s.status)?s.status[0]:String(s.status||""),sa=["Sold","SOLD","Closed","CLSD","CL"].some(ea=>ea.toLowerCase()===Ve?.toLowerCase()),tt=sa&&s.salePrice?`$${s.salePrice.toLocaleString()}`:s.listPrice?`$${s.listPrice.toLocaleString()}`:"",it=s.saleDate||s.listDate||"",Je=sa?"Sold":"Listed",Kt=(ea=>{if(!ea)return"";try{const tr=new Date(ea);return Ex(tr)?Vi(tr,"MM/dd/yyyy"):ea}catch{return ea}})(it),Sa=[];Sa.push(`MLS# ${vt}`),tt&&Sa.push(tt),Kt&&Sa.push(`${Je} ${Kt}`);const Qt=Sa.join(", ");le({offeredForSale:{value:!0,source:"MLS",isEdited:!1,alternatives:{}},offeredForSaleDataSource:{value:Qt,source:"MLS",isEdited:!1,alternatives:{}},offeredForSaleMlsNumber:{value:vt,source:"MLS",isEdited:!1,alternatives:{}},offeredForSalePrice:{value:tt,source:"MLS",isEdited:!1,alternatives:{}},offeredForSaleListDate:{value:Kt,source:"MLS",isEdited:!1,alternatives:{}}})},[rt,s?.mlsNumber,p.offeredForSale?.isEdited,p.offeredForSaleDataSource?.isEdited,p.offeredForSaleDataSource?.source,p.offeredForSaleDataSource?.value,le]),o.useEffect(()=>{rt||!s?.status&&!r||p.offeredForSale?.isEdited||p.offeredForSale?.value===!1&&p.offeredForSale?.source==="Derived"||le({offeredForSale:{value:!1,source:"Derived",isEdited:!1,alternatives:{}}})},[rt,s?.status,r,p.offeredForSale?.isEdited,p.offeredForSale?.value,p.offeredForSale?.source,le]);const $t=()=>{if(!p.effectiveDate.value)return;const Ce=Hy(p.effectiveDate.value,"MM/dd/yyyy",new Date);if(Ex(Ce))return Ce;const St=Hy(p.effectiveDate.value,"M/d/yyyy",new Date);if(Ex(St))return St},na=Ce=>{Ce&&V("effectiveDate",{...p.effectiveDate,value:Vi(Ce,"MM/dd/yyyy"),source:"User",isEdited:!0})},zt=e.jsx(uD,{counts:ua,active:R,onChange:G,onReset:()=>G("all"),onConfirmAll:Oe,showUnconfirmed:!1,showConfirmed:!1,progress:{verified:ua.confirmed,total:Oa}}),Ua=e.jsxs("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-blue-50 text-blue-600 border border-blue-100 uppercase tracking-tight","data-testid":"text-order-number",children:["Order # ",p.orderNumber?.value||"BV-2026-0052"]});return e.jsxs("div",{className:Q("animate-in fade-in duration-200",d&&"wizard-step1"),"data-testid":"step1-order",children:[d?e.jsxs("div",{className:"p-2 pb-0 space-y-3",children:[e.jsxs("div",{className:"bg-white border border-slate-200 border-l-2 border-l-[#C5A572] rounded-lg px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"text-base font-semibold flex items-center gap-2 text-[#293757]",children:[e.jsx(fN,{className:"h-5 w-5 text-[#293757]"}),"Order"]}),e.jsx("div",{className:"flex items-center gap-2",children:Ua})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:zt}),e.jsx("div",{className:"mt-2",children:e.jsx(Z0,{})})]}),e.jsx("div",{className:"flex flex-wrap items-end gap-1.5 border-b-2 border-[#C5A572]",role:"tablist","data-testid":"step1-eval-tabs",children:dY.map(Ce=>{const St=st[Ce.id],vt=St.missing+St.conflicts+St.unconfirmed+St.confirmed,Ve=R==="all"?vt:St[R];return e.jsxs("button",{type:"button",role:"tab","aria-selected":U===Ce.id,onClick:()=>C(Ce.id),className:Q("relative px-5 py-2.5 text-sm font-semibold rounded-t-md border transition-colors flex items-center gap-1.5",U===Ce.id?"z-10 -mb-0.5 border-[#C5A572] border-t-2 border-b-2 border-b-white bg-[#C5A572]/15 text-[#293757] shadow-sm":"border-slate-300 bg-slate-100 text-slate-500 hover:bg-slate-50 hover:text-[#293757]"),"data-testid":`tab-step1-eval-${Ce.id}`,children:[Ce.label,Ve>0&&e.jsx("span",{className:Q("text-[10px] font-bold px-1.5 py-0.5 rounded-full border leading-none",pD(R==="all"?"all":R)),"data-testid":`badge-step1-eval-${Ce.id}`,children:Ve})]},Ce.id)})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"h-10 border-b border-slate-200 bg-slate-50/80 flex items-center justify-between px-4 sticky top-0 z-10",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-[13px] font-semibold text-slate-700",children:"Order Details"}),zt]}),e.jsx("div",{className:"flex items-center gap-2",children:Ua})]}),e.jsx("div",{className:"px-4 py-1 border-b border-slate-100",children:e.jsx(Z0,{})})]}),e.jsx("div",{children:e.jsxs("div",{className:d?"p-2 space-y-3"
10:"py-3 px-4 space-y-3",children:[(!d||U==="order")&&(Ie("subjectAddress","effectiveDate","assignmentType")||qa.held)&&e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden",ref:qa.bind.ref,onPointerDownCapture:qa.bind.onPointerDownCapture,onFocusCapture:qa.bind.onFocusCapture,onBlurCapture:qa.bind.onBlurCapture,children:[e.jsx(Iu,{title:"Order Information",rightAction:ye.orderEmpty>0?e.jsxs("span",{className:"text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-red-50 text-red-500 border border-red-100",children:[ye.orderEmpty," missing"]}):void 0}),e.jsxs("div",{className:"grid grid-cols-2 gap-0 divide-x divide-slate-100",children:[e.jsxs("div",{className:"divide-y divide-slate-100",children:[e.jsx(cg,{label:"Subject Address",field:p.subjectAddress,onUpdate:Ce=>V("subjectAddress",Ce),wide:!0,testId:"field-subject-address"}),e.jsx(cg,{label:"Effective Date",field:p.effectiveDate,onUpdate:Ce=>V("effectiveDate",Ce),testId:"field-effective-date",custom:e.jsxs(xn,{children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{className:"flex items-center gap-1.5 text-[13px] font-medium text-slate-800 hover:text-primary transition-colors","data-testid":"button-effective-date",children:[e.jsx(mc,{className:"w-3 h-3 text-slate-400"}),p.effectiveDate.value||e.jsx("span",{className:"text-slate-400 italic",children:"Select date..."})]})}),e.jsx(yn,{className:"w-auto p-0",align:"start",children:e.jsx(Uv,{mode:"single",selected:$t(),onSelect:na,initialFocus:!0})})]})})]}),e.jsxs("div",{className:"divide-y divide-slate-100",children:[e.jsx(cg,{label:"Order #",field:p.orderNumber||{value:"BV-2026-0052",source:"Echo",isEdited:!1,alternatives:{}},onUpdate:Ce=>V("orderNumber",Ce),readOnly:!0,testId:"field-order-number"}),e.jsx(cg,{label:"Assignment",field:p.assignmentType,onUpdate:Ce=>V("assignmentType",Ce),testId:"field-assignment-type",custom:d?e.jsx("div",{className:"flex items-center gap-1.5 w-full",children:(()=>{const Ce=[{value:"Construction",label:"Construction"},{value:"DeedInLieu",label:"Deed in Lieu"},{value:"HomeEquity",label:"Home Equity"},{value:"LoanModification",label:"Loan Modification"},{value:"PortfolioEvaluation",label:"Portfolio Evaluation"},{value:"Preforeclosure",label:"Preforeclosure"},{value:"Purchase",label:"Purchase"},{value:"Refinance",label:"Refinance"},{value:"REO",label:"REO"},{value:"ShortSale",label:"Short Sale"},{value:"Other",label:"Other"}],St=String(p.assignmentType.value??"").trim(),vt=St==="Purchase Transaction"?"Purchase":St==="Refinance Transaction"?"Refinance":St;return e.jsxs(e.Fragment,{children:[e.jsxs("select",{value:vt,onChange:Ve=>{V("assignmentType",{...p.assignmentType,value:Ve.target.value,isEdited:!0,source:"User"})},className:"h-6 px-1.5 text-[11px] font-medium rounded border border-slate-200 bg-white focus:ring-1 focus:ring-primary/20 outline-none text-[#072034] flex-1 min-w-0","data-testid":"select-assignment-type",children:[e.jsx("option",{value:"",children:"Select..."}),Ce.map(Ve=>e.jsx("option",{value:Ve.value,children:Ve.label},Ve.value))]}),vt==="Other"&&e.jsx("input",{type:"text",placeholder:"Specify...",maxLength:15,value:p.assignmentTypeOtherDescription?.value||"",onClick:Ve=>Ve.stopPropagation(),onChange:Ve=>V("assignmentTypeOtherDescription",{value:Ve.target.value,source:"User",isEdited:!0,alternatives:{}}),className:"px-1.5 py-0.5 text-[10px] font-medium rounded border border-slate-300 bg-white w-20 focus:outline-none focus:ring-1 focus:ring-primary","data-testid":"input-assignment-type-other"})]})})()}):e.jsxs("div",{className:"flex items-center gap-1",children:[["Purchase Transaction","Refinance Transaction","Other"].map(Ce=>e.jsx("button",{type:"button",onClick:St=>{St.stopPropagation();const vt=p.assignmentType.value===Ce?"":Ce;V("assignmentType",{...p.assignmentType,value:vt,isEdited:!0,source:"User"})},className:Q("px-2 py-0.5 text-[10px] font-semibold rounded border transition-all cursor-pointer",p.assignmentType.value===Ce?"bg-[#072034] text-white border-[#072034]":"bg-white text-slate-500 border-slate-200 hover:bg-slate-100"),"data-testid":`button-assignment-${Ce.toLowerCase().replace(/\s+/g,"-")}`,children:Ce==="Purchase Transaction"?"Purchase":Ce==="Refinance Transaction"?"Refi":"Other"},Ce)),p.assignmentType.value==="Other"&&e.jsx("input",{type:"text",placeholder:"Specify...",maxLength:15,value:p.assignmentTypeOtherDescription?.value||"",onClick:Ce=>Ce.stopPropagation(),onChange:Ce=>V("assignmentTypeOtherDescription",{value:Ce.target.value,source:"User",isEdited:!0,alternatives:{}}),className:"px-1.5 py-0.5 text-[10px] font-medium rounded border border-slate-300 bg-white w-16 focus:outline-none focus:ring-1 focus:ring-primary","data-testid":"input-assignment-type-other"})]})})]})]})]}),(!d||U==="order")&&He(p.offeredForSale)&&e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden",children:[e.jsx(Iu,{title:"Listing Status",rightAction:ye.listingEmpty>
100?e.jsxs("span",{className:"text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-red-50 text-red-500 border border-red-100",children:[ye.listingEmpty," missing"]}):void 0}),e.jsxs("div",{className:"px-2.5 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase text-slate-400 tracking-wide min-w-[80px]",children:"Offered for Sale"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{type:"button",onClick:()=>V("offeredForSale",{value:p.offeredForSale?.value===!0?null:!0,source:"User",isEdited:!0,alternatives:{}}),className:Q("px-2.5 py-0.5 text-[10px] font-semibold rounded border transition-all cursor-pointer",p.offeredForSale?.value===!0?"bg-[#072034] text-white border-[#072034]":"bg-white text-slate-500 border-slate-200 hover:bg-slate-100"),"data-testid":"button-offered-for-sale-yes",children:"Yes"}),e.jsx("button",{type:"button",onClick:()=>V("offeredForSale",{value:p.offeredForSale?.value===!1?null:!1,source:"User",isEdited:!0,alternatives:{}}),className:Q("px-2.5 py-0.5 text-[10px] font-semibold rounded border transition-all cursor-pointer",p.offeredForSale?.value===!1?"bg-[#072034] text-white border-[#072034]":"bg-white text-slate-500 border-slate-200 hover:bg-slate-100"),"data-testid":"button-offered-for-sale-no",children:"No"})]}),e.jsx(pd,{source:de(p.offeredForSale)?"Empty":p.offeredForSale?.source||"Derived"})]}),be&&e.jsx("div",{className:"mt-1",children:e.jsx(yi,{placeholder:"MLS# 12345678, $450,000, Listed 01/15/2024",value:p.offeredForSaleDataSource?.value||"",onChange:Ce=>V("offeredForSaleDataSource",{value:Ce.target.value,source:"User",isEdited:!0,alternatives:{}}),className:"min-h-[32px] h-8 text-[12px] py-1","data-testid":"input-data-source"})})]})]}),d&&U==="order"&&R!=="all"&&je[R]===0&&e.jsx("div",{className:"px-3 py-6 text-sm text-muted-foreground","data-testid":"step1-order-empty-state",children:VE(R)}),d&&U==="parties"&&R!=="all"&&Le[R]===0&&!os.held&&e.jsx("div",{className:"px-3 py-6 text-sm text-muted-foreground","data-testid":"step1-parties-empty-state",children:VE(R)}),(!d||U==="parties")&&l&&(!(d&&R!=="all"&&Le[R]===0)||os.held)&&e.jsxs("div",{className:"space-y-3","data-testid":"core-parties-section",ref:os.bind.ref,onPointerDownCapture:os.bind.onPointerDownCapture,onFocusCapture:os.bind.onFocusCapture,onBlurCapture:os.bind.onBlurCapture,children:[e.jsx(sY,{orderId:l,compact:!!d,onInterestedChange:me,rowVisible:At}),e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden",children:[e.jsx(Iu,{title:"Contacts"}),e.jsx("div",{className:"p-3",children:e.jsx(rY,{orderId:l,testIdPrefix:"core-contact",onContactsChange:W,rowVisible:Fe})})]}),(Ie("loanNumber","occupant")||os.held)&&e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden",children:[e.jsx(Iu,{title:"Loan & Occupancy"}),e.jsx(oj,{filterMode:os.held?"all":R==="missing"||R==="conflicts"?R:"all",fields:[{label:"Loan #",field:p.loanNumber,onUpdate:Ce=>V("loanNumber",Ce),notApplicable:H,testId:"field-loan-number"},{label:"Occupant",field:Xa,onUpdate:Ce=>V("occupant",Ce),isSelect:!0,selectOptionPairs:DT,labelInfo:Qw,testId:"field-occupant"}]})]})]}),(!d||U==="parties")&&!l&&(Ie("lender","client","lenderAddress","clientAddress","loanNumber","owner","borrower","coBorrower","occupant")||os.held)&&e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden",ref:os.bind.ref,onPointerDownCapture:os.bind.onPointerDownCapture,onFocusCapture:os.bind.onFocusCapture,onBlurCapture:os.bind.onBlurCapture,children:[e.jsx(Iu,{title:"Parties",rightAction:ye.lenderEmpty+ye.ownerEmpty>0?e.jsxs("span",{className:"text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-red-50 text-red-500 border border-red-100",children:[ye.lenderEmpty+ye.ownerEmpty," ","missing"]}):void 0}),e.jsx(oj,{fields:[{label:"Lender",field:p.lender,onUpdate:Ce=>V("lender",Ce),testId:"field-lender"},{label:"Client",field:p.client,onUpdate:Ce=>V("client",Ce),testId:"field-client"},{label:"Lender Addr",field:p.lenderAddress||{value:"",source:"Echo",isEdited:!1,alternatives:{}},onUpdate:Ce=>
10V("lenderAddress",Ce),testId:"field-lender-address"},{label:"Client Addr",field:p.clientAddress||{value:"",source:"Echo",isEdited:!1,alternatives:{}},onUpdate:Ce=>V("clientAddress",Ce),testId:"field-client-address"},{label:"Loan #",field:p.loanNumber,onUpdate:Ce=>V("loanNumber",Ce),notApplicable:H,testId:"field-loan-number"},{label:"Owner",field:p.owner,onUpdate:Ce=>V("owner",Ce),testId:"field-owner"},{label:"Borrower",field:p.borrower,onUpdate:Ce=>V("borrower",Ce),testId:"field-borrower"},{label:"Co-Borrower",field:p.coBorrower,onUpdate:Ce=>V("coBorrower",Ce),testId:"field-co-borrower"},{label:"Occupant",field:Xa,onUpdate:Ce=>V("occupant",Ce),isSelect:!0,selectOptionPairs:DT,labelInfo:Qw,testId:"field-occupant"}]})]}),!d&&(He(p.appraiser,p.appraiserLicense,p.appraiserLicenseExpiration,p.appraiserLicenseType,p.appraiserCompany,p.appraiserLicenseState)||ya.held)&&e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden",ref:ya.bind.ref,onPointerDownCapture:ya.bind.onPointerDownCapture,onFocusCapture:ya.bind.onFocusCapture,onBlurCapture:ya.bind.onBlurCapture,children:[e.jsx(Iu,{title:"Appraiser",rightAction:ye.appraiserEmpty>0?e.jsxs("span",{className:"text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-red-50 text-red-500 border border-red-100",children:[ye.appraiserEmpty," missing"]}):void 0}),e.jsx(oj,{fields:[{label:"Appraiser",field:p.appraiser,onUpdate:Ce=>V("appraiser",Ce),testId:"field-appraiser"},{label:"Company",field:p.appraiserCompany||{value:"",source:"User",isEdited:!1,alternatives:{}},onUpdate:Ce=>V("appraiserCompany",Ce),testId:"field-appraiser-company"},{label:"License #",field:p.appraiserLicense,onUpdate:Ce=>V("appraiserLicense",Ce),testId:"field-appraiser-license"},{label:"License Type",field:p.appraiserLicenseType||{value:"",source:"Echo",isEdited:!1,alternatives:{}},onUpdate:Ce=>V("appraiserLicenseType",Ce),isSelect:!0,selectOptions:["Certified","Certified General","Licensed","Trainee"],testId:"select-license-type"},{label:"License State",field:p.appraiserLicenseState||{value:"",source:"Echo",isEdited:!1,alternatives:{}},onUpdate:Ce=>V("appraiserLicenseState",Ce),testId:"field-appraiser-state"},{label:"Expiration",field:p.appraiserLicenseExpiration,onUpdate:Ce=>V("appraiserLicenseExpiration",Ce),isDate:!0,testId:"field-appraiser-expiration"}]})]}),d&&e.jsx(c$,{orderId:l||"new",embedded:!0,tab:U==="appraiser"||U==="revision"||U==="documents"?U:void 0,verificationFilter:R,onVerificationCounts:M}),(!d||U==="order")&&ue&&R==="all"&&e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden animate-in fade-in duration-300",children:[e.jsx(Iu,{title:"Contract Analysis"}),e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{"data-testid":"contract-upload-btn",type:"button",disabled:y,onClick:()=>m.current?.click(),className:Q("flex items-center gap-1.5 px-3 py-1.5 text-[11px] font-semibold rounded border transition-all",y?"bg-slate-100 text-slate-400 border-slate-200 cursor-not-allowed":j?"bg-green-50 text-green-700 border-green-200 hover:bg-green-100":"bg-[#A18A60]/10 text-[#A18A60] border-[#A18A60]/20 hover:bg-[#A18A60]/20"),children:y?e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"w-3 h-3 animate-spin"})," ","Analyzing..."]}):j?e.jsxs(e.Fragment,{children:[e.jsx(kr,{className:"w-3 h-3"})," ",j]}):e.jsxs(e.Fragment,{children:[e.jsx(ul,{className:"w-3 h-3"})," Upload Contract"]})}),!j&&!y&&e.jsx("span",{className:"text-[10px] text-slate-400",children:"PDF — extracts price, date, concessions"}),e.jsx("input",{ref:m,type:"file",accept:".pdf",className:"hidden",onChange:Ce=>{const St=Ce.target.files?.[0];St&&fe(St),Ce.target&&(Ce.target.value="")}})]}),O&&e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-red-600 bg-red-50 px-2.5 py-1.5 rounded","data-testid":"contract-error",children:[e.jsx(Di,{className:"w-3 h-3 shrink-0"}),O]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-slate-600",children:[e.jsx("span",{children:"I"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{type:"button","data-testid":"contract-did-btn",onClick:()=>V("contractAnalyzed",{value:p.contractAnalyzed?.value===!0?null:!0,source:"User",isEdited:!0,alternatives:{}}),className:Q("px-2 py-0.5 text-[10px] font-bold rounded border transition-all",p.contractAnalyzed?.value===!0?"bg-green-600 text-white border-green-600":"bg-white text-slate-500 border-slate-200 hover:bg-slate-50"),children:"did"}),e.jsx("button",{type:"button","data-testid":"contract-didnot-btn",onClick:()=>V("contractAnalyzed",{value:p.contractAnalyzed?.value===!1?null:!1,source:"User",isEdited:!0,alternatives:{}}),className:Q("px-2 py-0.5 text-[10px] font-bold rounded border transition-all",p.contractAnalyzed?.value===!1?"bg-amber-600 text-white border-amber-600":"bg-white text-slate-500 border-slate-200 hover:bg-slate-50"),children:"did not"})]}),e.jsx("span",{children:"analyze the contract for the subject purchase transaction."})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase text-slate-500 block mb-1",children:"Explanation"}),e.jsx(yi,{"data-testid":"contract-explanation",placeholder:"Enter contract analysis explanation...",value:p.contractAnalysisExplanation?.value||"",onChange:Ce=>V("contractAnalysisExplanation",{value:Ce.target.value,source:"User",isEdited:!0,alternatives:{}}),className:"min-h-[80px] text-[12px]"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase text-slate-500 block mb-1",children:"Contract Price"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-2 top-1/2 -translate-y-1/2 text-slate-400 text-[12px]",children:"$"}),e.jsx("input",{"data-testid":"contract-price",type:"text",value:p.contractPrice?.value||"",onChange:Ce=>V("contractPrice",{value:Ce.target.value.replace(/[^0-9,]/g,""),source:"User",isEdited:!0,alternatives:{}}),className:"w-full h-8 pl-5 pr-2 text-[12px] font-semibold rounded border border-slate-200 focus:ring-1 focus:ring-primary/20 outline-none"})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase text-slate-500 block mb-1",children:"Date of Contract"}),e.jsxs(xn,{children:[e.jsx(bn,{asChild:!0,children:e.jsxs(De,{"data-testid":"contract-date",variant:"outline",className:"w-full justify-start text-left font-medium h-8 text-[12px] border-slate-200",children:[e.jsx(mc,{className:"mr-1.5 h-3 w-3 text-slate-400"}),p.contractDate?.value||"Select date..."]})}),e.jsx(yn,{className:"w-auto p-0",align:"start",children:e.jsx(Uv,{mode:"single",selected:p.contractDate?.value?Hy(p.contractDate.value,"MM/dd
10/yyyy",new Date):void 0,onSelect:Ce=>Ce&&V("contractDate",{value:Vi(Ce,"MM/dd/yyyy"),source:"User",isEdited:!0,alternatives:{}})})})]})]})]})]})]})]}),!d&&R==="all"&&e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden",children:[e.jsx(Iu,{title:"Documents",rightAction:n.length>0?e.jsxs("span",{className:"text-[10px] text-slate-400",children:[n.length," file",n.length!==1?"s":""]}):void 0}),e.jsxs("div",{className:"p-2.5 space-y-2",children:[n.length>0&&e.jsx("div",{className:"space-y-1",children:n.map(Ce=>e.jsxs("div",{"data-testid":`doc-row-${Ce.id}`,className:"flex items-center justify-between py-1.5 px-2.5 rounded bg-slate-50/80 hover:bg-slate-100/80 transition-colors group text-[12px]",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx(gn,{className:"w-3.5 h-3.5 text-slate-400 shrink-0"}),e.jsx("span",{className:"font-medium text-[#072034] truncate",children:Ce.name}),e.jsx(pd,{source:Ce.source}),e.jsx("span",{className:"text-[10px] text-slate-400",children:cY[Ce.type]}),Ce.size&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["• ",se(Ce.size)]})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{"data-testid":`doc-preview-${Ce.id}`,onClick:()=>f(Ce),className:"p-1 rounded hover:bg-white text-slate-400 hover:text-[#072034] transition-colors",title:"Preview",children:e.jsx(of,{className:"w-3 h-3"})}),Ce.source==="Upload"&&e.jsx("button",{"data-testid":`doc-remove-${Ce.id}`,onClick:()=>pe(Ce.id),className:"p-1 rounded hover:bg-red-50 text-slate-400 hover:text-red-500 transition-colors",title:"Remove",children:e.jsx(Ci,{className:"w-3 h-3"})})]})]},Ce.id))}),e.jsxs("div",{"data-testid":"doc-upload-zone",className:Q("border border-dashed rounded-lg py-4 flex flex-col items-center justify-center cursor-pointer transition-all",N?"border-[#A18A60] bg-[#A18A60]/5":"border-slate-200 hover:border-slate-300 hover:bg-slate-50/50"),onClick:()=>u.current?.click(),onDragOver:Ce=>{Ce.preventDefault(),x(!0)},onDragLeave:()=>x(!1),onDrop:Ce=>{Ce.preventDefault(),x(!1),Z(Ce.dataTransfer.files)},children:[e.jsx(Zx,{className:Q("w-5 h-5 mb-1.5",N?"text-[#A18A60]":"text-slate-300")}),e.jsxs("span",{className:"text-[11px] font-medium text-slate-500",children:["Drop files or"," ",e.jsx("span",{className:"text-[#A18A60] underline",children:"browse"})]})]}),e.jsx("input",{ref:u,type:"file",multiple:!0,accept:".pdf,.doc,.docx,.jpg,.jpeg,.png",className:"hidden",onChange:Ce=>{Z(Ce.target.files),Ce.target&&(Ce.target.value="")}})]})]}),!d&&R!=="all"&&Pe[R]===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-6 text-center",children:[e.jsx("div",{className:"text-green-600 text-2xl mb-2","data-testid":"text-all-resolved",children:"✓"}),e.jsx("h3",{className:"text-sm font-medium text-slate-700",children:R==="conflicts"?"All conflicts resolved":R==="missing"?"All fields populated":R==="unconfirmed"?"No unconfirmed fields":"No confirmed fields"}),e.jsx("p",{className:"text-[11px] text-slate-500 mt-0.5",children:'Click "Reset" to see all fields.'})]})]})}),h&&e.jsx("div",{className:"fixed inset-0 z-[100] bg-black/60 flex items-center justify-center p-4",onClick:()=>f(null),children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl max-w-3xl w-full max-h-[85vh] flex flex-col",onClick:Ce=>Ce.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(gn,{className:"w-4 h-4 text-slate-500"}),e.jsx("span",{className:"font-semibold text-sm text-[#072034]",children:h.name}),e.jsx(pd,{source:h.source})]}),e.jsx("button",{"data-testid":"doc-preview-close",onClick:()=>f(null),className:"p-1.5 rounded-lg hover:bg-slate-100 transition-colors",children:e.jsx(ur,{className:"w-4 h-4 text-slate-500"})})]}),e.jsx("div",{className:"flex-1 overflow-auto p-6",children:v?h.file?.type?.startsWith("image/")?e.jsx("img",{src:v,alt:h.name,className:"max-w-full h-auto rounded-lg mx-auto"}):e.jsx("iframe",{src:v,className:"w-full h-[65vh] rounded-lg border border-slate-200",title:h.name}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(gn,{className:"w-12 h-12 text-slate-300 mb-3"}),e.jsx("span",{className:"text-sm text-slate-500",children:"No preview available"})]})})]})})]})}const mY={id:"subject",name:"Subject",description:"Subject property identification and basic information",requiredForGeneration:!0,fields:[{pdfFieldName:"Property Address",fieldType:"text",wizardDataPath:"subject.address",label:"Property Address",required:!0},{pdfFieldName:"City",fieldType:"text",wizardDataPath:"subject.city",label:"City",required:!0}
10,{pdfFieldName:"State",fieldType:"text",wizardDataPath:"subject.state",label:"State",required:!0,maxLength:2},{pdfFieldName:"Zip Code",fieldType:"text",wizardDataPath:"subject.zipCode",label:"Zip Code",required:!0},{pdfFieldName:"County",fieldType:"text",wizardDataPath:"subject.county",label:"County",required:!0},{pdfFieldName:"Borrower",fieldType:"text",wizardDataPath:"orderData.borrower.value",label:"Borrower",required:!0},{pdfFieldName:"Owner of Public Record",fieldType:"text",wizardDataPath:"subject.owner",label:"Owner of Public Record",required:!0},{pdfFieldName:"Legal Description",fieldType:"textarea",wizardDataPath:"subject.legalDescription",label:"Legal Description",required:!0},{pdfFieldName:"Assessors Parcel",fieldType:"text",wizardDataPath:"subject.pinNumber",label:"Assessor's Parcel #",required:!0},{pdfFieldName:"Tax Year",fieldType:"text",wizardDataPath:"subject.taxYear",label:"Tax Year",required:!0},{pdfFieldName:"R.E. Taxes",fieldType:"text",wizardDataPath:"subject.taxes",label:"R.E. Taxes $",required:!0},{pdfFieldName:"Neighborhood Name",fieldType:"text",wizardDataPath:"subject.neighborhoodName",label:"Neighborhood Name",required:!1},{pdfFieldName:"Map Reference",fieldType:"text",wizardDataPath:"subject.mapReference",label:"Map Reference",required:!0},{pdfFieldName:"Census Tract",fieldType:"text",wizardDataPath:"subject.censusTract",label:"Census Tract",required:!0},{pdfFieldName:"Occupant Owner",fieldType:"checkbox",wizardDataPath:"subject.occupantOwner",label:"Owner",required:!1,group:"occupant"},{pdfFieldName:"Occupant Tenant",fieldType:"checkbox",wizardDataPath:"subject.occupantTenant",label:"Tenant",required:!1,group:"occupant"},{pdfFieldName:"Occupant Vacant",fieldType:"checkbox",wizardDataPath:"subject.occupantVacant",label:"Vacant",required:!1,group:"occupant"},{pdfFieldName:"Special Assessments",fieldType:"text",wizardDataPath:"subject.specialAssessments",label:"Special Assessments $",required:!1},{pdfFieldName:"HOA Fees",fieldType:"text",wizardDataPath:"subject.hoaFees",label:"HOA $",required:!1},{pdfFieldName:"PUD",fieldType:"checkbox",wizardDataPath:"subject.isPud",label:"PUD",required:!1},{pdfFieldName:"HOA Fee Per Year",fieldType:"checkbox",wizardDataPath:"subject.hoaPerYear",label:"per year",required:!1,group:"hoaFrequency"},{pdfFieldName:"HOA Fee Per Month",fieldType:"checkbox",wizardDataPath:"subject.hoaPerMonth",label:"per month",required:!1,group:"hoaFrequency"},{pdfFieldName:"Property Rights Fee Simple",fieldType:"checkbox",wizardDataPath:"subject.propertyRightsFeeSimple",label:"Fee Simple",required:!1,group:"propertyRights"},{pdfFieldName:"Property Rights Leasehold",fieldType:"checkbox",wizardDataPath:"subject.propertyRightsLeasehold",label:"Leasehold",required:!1,group:"propertyRights"},{pdfFieldName:"Property Rights Other",fieldType:"checkbox",wizardDataPath:"subject.propertyRightsOther",label:"Other (describe)",required:!1,group:"propertyRights"},{pdfFieldName:"Property Rights Other Describe",fieldType:"text",wizardDataPath:"subject.propertyRightsOtherDescribe",label:"Property Rights Description",required:!1},{pdfFieldName:"Assignment Purchase",fieldType:"checkbox",wizardDataPath:"subject.assignmentPurchase",label:"Purchase Transaction",required:!1,group:"assignmentType"},{pdfFieldName:"Assignment Refinance",fieldType:"checkbox",wizardDataPath:"subject.assignmentRefinance",label:"Refinance Transaction",required:!1,group:"assignmentType"},{pdfFieldName:"Assignment Other",fieldType:"checkbox",wizardDataPath:"subject.assignmentOther",label:"Other (describe)",required:!1,group:"assignmentType"},{pdfFieldName:"Assignment Other Describe",fieldType:"text",wizardDataPath:"subject.assignmentOtherDescribe",label:"Assignment Description",required:!1},{pdfFieldName:"Lender Client",fieldType:"text",wizardDataPath:"orderData.lender.value",label:"Lender/Client",required:!0},{pdfFieldName:"Lender Client Address",fieldType:"text",wizardDataPath:"orderData.lenderAddress.value",label:"Address",required:!1},{pdfFieldName:"Property Offered For Sale Yes",fieldType:"checkbox",wizardDataPath:"subject.offeredForSaleYes",label:"Yes",required:!1,group:"offeredForSale"},{pdfFieldName:"Property Offered For Sale No",fieldType:"checkbox",wizardDataPath:"subject.offeredForSaleNo",label:"No",required:!1,group:"offeredForSale"},{pdfFieldName:"Offering Data Sources",fieldType:"textarea",wizardDataPath:"subject.offeringDataSources",label:"Report data source(s) used, offering price(s), and date(s).",required:!0}]},hY={id:"contract",name:"Contract",description:"Contract and sale information",requiredForGeneration:!1,fields:[{pdfFieldName:"Is Purchase Transaction",fieldType:"checkbox",wizardDataPath:"contract.isPurchase",label:"Purchase",required:!1},{pdfFieldName:"Is Refinance Transaction",fieldType:"checkbox",wizardDataPath:"contract.isRefinance",label:"Refinance / Other",required:!1},{pdfFieldName:"Contract Price",fieldType:"text",wizardDataPath:"contract.contractPrice",label:"Contract Price $",required:!1}
10,{pdfFieldName:"Date of Contract",fieldType:"text",wizardDataPath:"contract.contractDate",label:"Date of Contract",required:!1},{pdfFieldName:"Seller Name",fieldType:"text",wizardDataPath:"contract.sellerName",label:"Seller",required:!1},{pdfFieldName:"Is Property Seller Owner",fieldType:"checkbox",wizardDataPath:"contract.isSellerOwner",label:"Is the property seller the owner of public record?",required:!1},{pdfFieldName:"Seller Owner Data Source",fieldType:"text",wizardDataPath:"contract.sellerOwnerDataSource",label:"Data Source(s)",required:!1},{pdfFieldName:"Did Analyze Contract",fieldType:"checkbox",wizardDataPath:"contract.didAnalyzeContract",label:"did",required:!1,group:"contractAnalysis"},{pdfFieldName:"Did Not Analyze Contract",fieldType:"checkbox",wizardDataPath:"contract.didNotAnalyzeContract",label:"did not",required:!1,group:"contractAnalysis"},{pdfFieldName:"Contract Analysis Explanation",fieldType:"textarea",wizardDataPath:"contract.contractAnalysisExplanation",label:"Contract Analysis Explanation",required:!1}]},fY={id:"neighborhood",name:"Neighborhood",description:"Neighborhood characteristics from market analysis",requiredForGeneration:!1,fields:[{pdfFieldName:"Location Urban",fieldType:"checkbox",wizardDataPath:"neighborhood.locationUrban",label:"Urban",required:!1,group:"location"},{pdfFieldName:"Location Suburban",fieldType:"checkbox",wizardDataPath:"neighborhood.locationSuburban",label:"Suburban",required:!1,group:"location"},{pdfFieldName:"Location Rural",fieldType:"checkbox",wizardDataPath:"neighborhood.locationRural",label:"Rural",required:!1,group:"location"},{pdfFieldName:"Built Up Over 75",fieldType:"checkbox",wizardDataPath:"neighborhood.builtUpOver75",label:"Over 75%",required:!1,group:"builtUp"},{pdfFieldName:"Built Up 25-75",fieldType:"checkbox",wizardDataPath:"neighborhood.builtUp25to75",label:"25-75%",required:!1,group:"builtUp"},{pdfFieldName:"Built Up Under 25",fieldType:"checkbox",wizardDataPath:"neighborhood.builtUpUnder25",label:"Under 25%",required:!1,group:"builtUp"},{pdfFieldName:"Growth Rapid",fieldType:"checkbox",wizardDataPath:"neighborhood.growthRapid",label:"Rapid",required:!1,group:"growth"},{pdfFieldName:"Growth Stable",fieldType:"checkbox",wizardDataPath:"neighborhood.growthStable",label:"Stable",required:!1,group:"growth"},{pdfFieldName:"Growth Slow",fieldType:"checkbox",wizardDataPath:"neighborhood.growthSlow",label:"Slow",required:!1,group:"growth"},{pdfFieldName:"Property Values Increasing",fieldType:"checkbox",wizardDataPath:"neighborhood.propertyValuesIncreasing",label:"Increasing",required:!1,group:"propertyValues"},{pdfFieldName:"Property Values Stable",fieldType:"checkbox",wizardDataPath:"neighborhood.propertyValuesStable",label:"Stable",required:!1,group:"propertyValues"},{pdfFieldName:"Property Values Declining",fieldType:"checkbox",wizardDataPath:"neighborhood.propertyValuesDeclining",label:"Declining",required:!1,group:"propertyValues"},{pdfFieldName:"Demand Supply Shortage",fieldType:"checkbox",wizardDataPath:"neighborhood.demandSupplyShortage",label:"Shortage",required:!1,group:"demandSupply"},{pdfFieldName:"Demand Supply In Balance",fieldType:"checkbox",wizardDataPath:"neighborhood.demandSupplyInBalance",label:"In Balance",required:!1,group:"demandSupply"},{pdfFieldName:"Demand Supply Over Supply",fieldType:"checkbox",wizardDataPath:"neighborhood.demandSupplyOverSupply",label:"Over Supply",required:!1,group:"demandSupply"},{pdfFieldName:"Marketing Time Under 3 Mths",fieldType:"checkbox",wizardDataPath:"neighborhood.marketingTimeUnder3",label:"Under 3 mths",required:!1,group:"marketingTime"},{pdfFieldName:"Marketing Time 3-6 Mths",fieldType:"checkbox",wizardDataPath:"neighborhood.marketingTime3to6",label:"3-6 mths",required:!1,group:"marketingTime"},{pdfFieldName:"Marketing Time Over 6 Mths",fieldType:"checkbox",wizardDataPath:"neighborhood.marketingTimeOver6",label:"Over 6 mths",required:!1,group:"marketingTime"},{pdfFieldName:"Price Low",fieldType:"text",wizardDataPath:"neighborhood.priceLow",label:"Price Low ($000)",required:!1},{pdfFieldName:"Price High",fieldType:"text",wizardDataPath:"neighborhood.priceHigh",label:"Price High ($000)",required:!1}
10,{pdfFieldName:"Price Predominant",fieldType:"text",wizardDataPath:"neighborhood.pricePredominant",label:"Price Pred. ($000)",required:!1},{pdfFieldName:"Age Low",fieldType:"text",wizardDataPath:"neighborhood.ageLow",label:"Age Low (Yrs)",required:!1},{pdfFieldName:"Age High",fieldType:"text",wizardDataPath:"neighborhood.ageHigh",label:"Age High (Yrs)",required:!1},{pdfFieldName:"Age Predominant",fieldType:"text",wizardDataPath:"neighborhood.agePredominant",label:"Age Pred. (Yrs)",required:!1},{pdfFieldName:"Present Land Use One - Unit",fieldType:"text",wizardDataPath:"neighborhood.landUseOneUnit",label:"One-Unit %",required:!1},{pdfFieldName:"Present Land Use 2-4 Unit",fieldType:"text",wizardDataPath:"neighborhood.landUse2to4",label:"2-4 Unit %",required:!1},{pdfFieldName:"Present Land Use Multi-Family",fieldType:"text",wizardDataPath:"neighborhood.landUseMultiFamily",label:"Multi-Family %",required:!1},{pdfFieldName:"Present Land Use Commercial",fieldType:"text",wizardDataPath:"neighborhood.landUseCommercial",label:"Commercial %",required:!1},{pdfFieldName:"Present Land Use Other",fieldType:"text",wizardDataPath:"neighborhood.landUseOther",label:"Other %",required:!1},{pdfFieldName:"Neighborhood Boundaries",fieldType:"textarea",wizardDataPath:"neighborhood.boundaries",label:"Neighborhood Boundaries",required:!1},{pdfFieldName:"Neighborhood Description",fieldType:"textarea",wizardDataPath:"neighborhood.description",label:"Neighborhood Description",required:!1},{pdfFieldName:"Market Conditions",fieldType:"textarea",wizardDataPath:"neighborhood.marketConditions",label:"Market Conditions",required:!1}]},gY={id:"site",name:"Site",description:"Site characteristics, zoning, and utilities",requiredForGeneration:!0,fields:[{pdfFieldName:"Dimensions",fieldType:"text",wizardDataPath:"site.dimensions",label:"Dimensions",required:!1},{pdfFieldName:"Area",fieldType:"text",wizardDataPath:"site.area",label:"Area",required:!1},{pdfFieldName:"Shape",fieldType:"text",wizardDataPath:"site.shape",label:"Shape",required:!1},{pdfFieldName:"View",fieldType:"text",wizardDataPath:"site.view",label:"View",required:!1},{pdfFieldName:"Specific Zoning Classification",fieldType:"text",wizardDataPath:"site.zoningClassification",label:"Zoning Classification",required:!0},{pdfFieldName:"Zoning Description",fieldType:"text",wizardDataPath:"site.zoningDescription",label:"Zoning Description",required:!1},{pdfFieldName:"Zoning Compliance Legal",fieldType:"checkbox",wizardDataPath:"site.zoningLegal",label:"Legal",required:!1,group:"zoningCompliance"},{pdfFieldName:"Zoning Compliance Legal Non-Conforming",fieldType:"checkbox",wizardDataPath:"site.zoningLegalNonConforming",label:"Legal Non-Conforming",required:!1,group:"zoningCompliance"},{pdfFieldName:"Zoning Compliance Illegal",fieldType:"checkbox",wizardDataPath:"site.zoningIllegal",label:"Illegal",required:!1,group:"zoningCompliance"},{pdfFieldName:"Highest Best Use Yes",fieldType:"checkbox",wizardDataPath:"site.highestBestUseYes",label:"Yes",required:!1,group:"highestBestUse"},{pdfFieldName:"Highest Best Use No",fieldType:"checkbox",wizardDataPath:"site.highestBestUseNo",label:"No",required:!1,group:"highestBestUse"},{pdfFieldName:"Highest Best Use No Describe",fieldType:"text",wizardDataPath:"site.highestBestUseNoDescribe",label:"If No, describe",required:!1},{pdfFieldName:"Utilities Electricity Public",fieldType:"checkbox",wizardDataPath:"site.electricityPublic",label:"Public",required:!1,group:"electricityType"},{pdfFieldName:"Utilities Electricity Other",fieldType:"checkbox",wizardDataPath:"site.electricityOther",label:"Other",required:!1,group:"electricityType"},{pdfFieldName:"Utilities Gas Public",fieldType:"checkbox",wizardDataPath:"site.gasPublic",label:"Public",required:!1,group:"gasType"},{pdfFieldName:"Utilities Gas Other",fieldType:"checkbox",wizardDataPath:"site.gasOther",label:"Other",required:!1,group:"gasType"},{pdfFieldName:"Utilities Water Public",fieldType:"checkbox",wizardDataPath:"site.waterPublic",label:"Public",required:!1,group:"waterType"},{pdfFieldName:"Utilities Water Other",fieldType:"checkbox",wizardDataPath:"site.waterOther",label:"Other",required:!1,group:"waterType"},{pdfFieldName:"Utilities Sanitary Sewer Public",fieldType:"checkbox",wizardDataPath:"site.sanitarySewerPublic",label:"Public",required:!1,group:"sanitarySewerType"},{pdfFieldName:"Utilities Sanitary Sewer Other",fieldType:"checkbox",wizardDataPath:"site.sanitarySewerOther",label:"Other",required:!1,group:"sanitarySewerType"}
10,{pdfFieldName:"Offsite Street Public",fieldType:"checkbox",wizardDataPath:"site.streetPublic",label:"Public",required:!1,group:"streetType"},{pdfFieldName:"Offsite Street Private",fieldType:"checkbox",wizardDataPath:"site.streetPrivate",label:"Private",required:!1,group:"streetType"},{pdfFieldName:"Offsite Alley Public",fieldType:"checkbox",wizardDataPath:"site.alleyPublic",label:"Public",required:!1,group:"alleyType"},{pdfFieldName:"Offsite Alley Private",fieldType:"checkbox",wizardDataPath:"site.alleyPrivate",label:"Private",required:!1,group:"alleyType"},{pdfFieldName:"FEMA Special Flood Hazard Yes",fieldType:"checkbox",wizardDataPath:"site.femaFloodHazardYes",label:"Yes",required:!1,group:"femaFloodHazard"},{pdfFieldName:"FEMA Special Flood Hazard No",fieldType:"checkbox",wizardDataPath:"site.femaFloodHazardNo",label:"No",required:!1,group:"femaFloodHazard"},{pdfFieldName:"FEMA Flood Zone",fieldType:"text",wizardDataPath:"site.femaFloodZone",label:"FEMA Flood Zone",required:!1},{pdfFieldName:"FEMA Map Date",fieldType:"text",wizardDataPath:"site.femaMapDate",label:"FEMA Map Date",required:!1},{pdfFieldName:"FEMA Map Number",fieldType:"text",wizardDataPath:"site.femaMapNumber",label:"FEMA Map Number",required:!1},{pdfFieldName:"Adverse Site Conditions Yes",fieldType:"checkbox",wizardDataPath:"site.adverseConditionsYes",label:"Yes",required:!1,group:"adverseConditions"},{pdfFieldName:"Adverse Site Conditions No",fieldType:"checkbox",wizardDataPath:"site.adverseConditionsNo",label:"No",required:!1,group:"adverseConditions"},{pdfFieldName:"Adverse Site Conditions Describe",fieldType:"textarea",wizardDataPath:"site.adverseConditionsDescribe",label:"Describe any adverse site conditions...",required:!1}]},xY={id:"improvements",name:"Improvements",description:"Building improvements (from MLS/public record and inspection)",requiredForGeneration:!1,fields:[{pdfFieldName:"Improvements Existing",fieldType:"checkbox",wizardDataPath:"improvements.isExisting",label:"Existing",required:!1,group:"improvementStatus"},{pdfFieldName:"Improvements Proposed",fieldType:"checkbox",wizardDataPath:"improvements.isProposed",label:"Proposed",required:!1,group:"improvementStatus"},{pdfFieldName:"Improvements Under Construction",fieldType:"checkbox",wizardDataPath:"improvements.isUnderConstruction",label:"Under Const.",required:!1,group:"improvementStatus"},{pdfFieldName:"Design Style",fieldType:"text",wizardDataPath:"improvements.designStyle",label:"Design (Style)",required:!1},{pdfFieldName:"Year Built",fieldType:"text",wizardDataPath:"improvements.yearBuilt",label:"Year Built",required:!1},{pdfFieldName:"Effective Age Yrs",fieldType:"text",wizardDataPath:"improvements.effectiveAge",label:"Effective Age (Yrs)",required:!1},{pdfFieldName:"Exterior Foundation",fieldType:"text",wizardDataPath:"improvements.foundation",label:"Foundation",required:!1},{pdfFieldName:"Exterior Walls",fieldType:"text",wizardDataPath:"improvements.exteriorWalls",label:"Exterior Walls",required:!1},{pdfFieldName:"Roof Surface",fieldType:"text",wizardDataPath:"improvements.roofSurface",label:"Roof Surface",required:!1},{pdfFieldName:"Gutters Downspouts",fieldType:"text",wizardDataPath:"improvements.guttersDownspouts",label:"Gutters & Dwnspots",required:!1},{pdfFieldName:"Window Type",fieldType:"text",wizardDataPath:"improvements.windowType",label:"Window Type",required:!1},{pdfFieldName:"Storm Sash Insulated",fieldType:"text",wizardDataPath:"improvements.stormSash",label:"Storm Sash/Insul.",required:!1},{pdfFieldName:"Screens",fieldType:"text",wizardDataPath:"improvements.screens",label:"Screens",required:!1},{pdfFieldName:"Foundation Concrete Slab",fieldType:"checkbox",wizardDataPath:"improvements.foundationConcreteSlab",label:"Concrete Slab",required:!1,group:"foundationType"},{pdfFieldName:"Foundation Crawl Space",fieldType:"checkbox",wizardDataPath:"improvements.foundationCrawlSpace",label:"Crawl Space",required:!1,group:"foundationType"},{pdfFieldName:"Foundation Full Basement",fieldType:"checkbox",wizardDataPath:"improvements.foundationFullBasement",label:"Full Basement",required:!1,group:"foundationType"},{pdfFieldName:"Foundation Partial Basement",fieldType:"checkbox",wizardDataPath:"improvements.foundationPartialBasement",label:"Partial Basement",required:!1,group:"foundationType"},{pdfFieldName:"Basement Area",fieldType:"text",wizardDataPath:"improvements.basementArea",label:"Basement Area",required:!1},{pdfFieldName:"Basement Percent Finished",fieldType:"text",wizardDataPath:"improvements.basementPercentFinished",label:"Basement % Finished",required:!1},{pdfFieldName:"Outside Entry Exit",fieldType:"checkbox",wizardDataPath:"improvements.outsideEntryExit",label:"Outside Entry/Exit",required:!1},{pdfFieldName:"Sump Pump",fieldType:"checkbox",wizardDataPath:"improvements.sumpPump",label:"Sump Pump",required:!1},{pdfFieldName:"Dampness",fieldType:"checkbox",wizardDataPath:"improvements.dampness",label:"Dampness",required:!1},{pdfFieldName:"Infestation Termites",fieldType:"checkbox",wizardDataPath:"improvements.infestationTermites",label:"Termites",required:!1,group:"infestation"},{pdfFieldName:"Infestation Settlement",fieldType:"checkbox",wizardDataPath:"improvements.infestationSettlement",label:"Settlement",required:!1,group:"infestation"},{pdfFieldName:"Interior Floors",fieldType:"text",wizardDataPath:"improvements.interiorFloors",label:"Floors",required:!1},{pdfFieldName:"Interior Walls",fieldType:"text",wizardDataPath:"improvements.interiorWalls",label:"Walls",required:!1},{pdfFieldName:"Interior Trim Finish",fieldType:"text",wizardDataPath:"improvements.trimFinis
10h",label:"Trim/Finish",required:!1},{pdfFieldName:"Interior Bath Floor",fieldType:"text",wizardDataPath:"improvements.bathFloor",label:"Bath Floor",required:!1},{pdfFieldName:"Interior Bath Wainscot",fieldType:"text",wizardDataPath:"improvements.bathWainscot",label:"Bath Wainscot",required:!1},{pdfFieldName:"Heating Type",fieldType:"text",wizardDataPath:"improvements.heatingType",label:"Heating",required:!1},{pdfFieldName:"Cooling Type",fieldType:"text",wizardDataPath:"improvements.coolingType",label:"Cooling",required:!1},{pdfFieldName:"Rooms Total",fieldType:"text",wizardDataPath:"improvements.totalRooms",label:"Total Rooms",required:!1},{pdfFieldName:"Bedrooms",fieldType:"text",wizardDataPath:"improvements.bedrooms",label:"Bedrooms",required:!1},{pdfFieldName:"Bathrooms",fieldType:"text",wizardDataPath:"improvements.bathrooms",label:"Bath(s)",required:!1},{pdfFieldName:"Square Feet GLA",fieldType:"text",wizardDataPath:"improvements.gla",label:"GLA (sq ft)",required:!1},{pdfFieldName:"Garage Carport",fieldType:"text",wizardDataPath:"improvements.garageCarport",label:"Garage/Carport",required:!1},{pdfFieldName:"Garage Cars",fieldType:"text",wizardDataPath:"improvements.garageCars",label:"# Cars",required:!1},{pdfFieldName:"Driveway Surface",fieldType:"text",wizardDataPath:"improvements.drivewaySurface",label:"Driveway Surface",required:!1},{pdfFieldName:"Fireplace Count",fieldType:"text",wizardDataPath:"improvements.fireplaceCount",label:"Fireplace(s) #",required:!1},{pdfFieldName:"Patio Deck",fieldType:"text",wizardDataPath:"improvements.patioDeck",label:"Patio/Deck",required:!1},{pdfFieldName:"Pool",fieldType:"text",wizardDataPath:"improvements.pool",label:"Pool",required:!1},{pdfFieldName:"Fence",fieldType:"text",wizardDataPath:"improvements.fence",label:"Fence",required:!1},{pdfFieldName:"Porch",fieldType:"text",wizardDataPath:"improvements.porch",label:"Porch",required:!1},{pdfFieldName:"Other Amenities",fieldType:"text",wizardDataPath:"improvements.otherAmenities",label:"Other",required:!1},{pdfFieldName:"Additional Features",fieldType:"textarea",wizardDataPath:"improvements.additionalFeatures",label:"Additional features",required:!1}]},bY={id:"salesComparison",name:"Sales Comparison",description:"Comparable sales grid with adjustments",requiredForGeneration:!0,fields:[{pdfFieldName:"Subject Address",fieldType:"text",wizardDataPath:"subject.address",label:"Subject Address",required:!0},{pdfFieldName:"Subject Sale Price",fieldType:"text",wizardDataPath:"subject.salePrice",label:"Subject Sale Price",required:!1},{pdfFieldName:"Subject Price Per GLA",fieldType:"text",wizardDataPath:"subject.pricePerGla",label:"Sale Price / GLA",required:!1},{pdfFieldName:"Subject Data Sources",fieldType:"text",wizardDataPath:"subject.dataSources",label:"Data Source(s)",required:!1},{pdfFieldName:"Subject Verification Sources",fieldType:"text",wizardDataPath:"subject.verificationSources",label:"Verification Source(s)",required:!1},{pdfFieldName:"Subject Sales Financing",fieldType:"text",wizardDataPath:"subject.salesFinancing",label:"Sales or Financing",required:!1},{pdfFieldName:"Subject Concessions",fieldType:"text",wizardDataPath:"subject.concessions",label:"Concessions",required:!1},{pdfFieldName:"Subject Date of Sale",fieldType:"text",wizardDataPath:"subject.dateOfSale",label:"Date of Sale/Time",required:!1},{pdfFieldName:"Subject Location",fieldType:"text",wizardDataPath:"subject.location",label:"Location",required:!0,uadFormat:"N;Res;A"},{pdfFieldName:"Subject Leasehold Fee Simple",fieldType:"text",wizardDataPath:"subject.leaseholdFeeSimple",label:"Leasehold/Fee Simple",required:!1},{pdfFieldName:"Subject Site",fieldType:"text",wizardDataPath:"subject.site",label:"Site",required:!0},{pdfFieldName:"Subject View",fieldType:"text",wizardDataPath:"subject.viewRating",label:"View",required:!0,uadFormat:"N;Res"},{pdfFieldName:"Subject Design Style",fieldType:"text",wizardDataPath:"subject.designStyle",label:"Design (Style)",required:!0},{pdfFieldName:"Subject Quality",fieldType:"text",wizardDataPath:"subject.quality",label:"Quality of Construction",required:!0,uadFormat:"Q1-Q6"},{pdfFieldName:"Subject Actual Age",fieldType:"text",wizardDataPath:"subject.actualAge",label:"Actual Age",required:!0},{pdfFieldName:"Subject Condition",fieldType:"text",wizardDataPath:"subject.condition",label:"Condition",required:!0,uadFormat:"C1-C6"},{pdfFieldName:"Subject Above Grade Room Count",fieldType:"text",wizardDataPath:"subject.aboveGradeRoomCount",label:"Above Grade Room Count",required:!1},{pdfFieldName:"Subject GLA",fieldType:"text",wizardDataPath:"subject.gla",label:"Gross Living Area",required:!1},{pdfFieldName:"Subject Basement Finished",fieldType:"text",wizardDataPath:"subject.basementFinished",label:"Basement & Finished",required:!1},{pdfFieldName:"Subject Functional Utility",fieldType:"text",wizardDataPath:"subject.functionalUtility",label:"Functional Utility",required:!1},{pdfFieldName:"Subject Heating Cooling",fieldType:"text",wizardDataPath:"subject.heatingCooling",label:"Heating/Cooling",required:!1},{pdfFieldName:"Subject Energy Efficient",fieldType:"text",wizardDataPath:"subject.energyEfficient",label:"Energy Efficient Items",required:!1},{pdfFieldName:"Subject Garage Carport",fieldType:"text",wizardDataPath:"subject.garageCarport",label:"Garage/Carport",required:!1},{pdfFieldName:"Subject Porch Patio Deck",fieldType:"text",wizardDataPath:"subject.porchPatioDeck",label:"Porch/Patio/Deck",required:!1},{pdfFieldName:"Comparable Sale 1",fieldType:"text",wizardDataPath:"comps[0].address",label:"Comp 1 Address",required:!0},{pdfFieldName:"Comparable Sale 1 Sale Price",fieldType:"text",wizardDataPath:"comps[0].salePrice",label:"Comp 1 
10Sale Price",required:!0},{pdfFieldName:"Comp 1 Price Per GLA",fieldType:"text",wizardDataPath:"comps[0].pricePerSqFt",label:"Comp 1 Price/GLA",required:!1},{pdfFieldName:"Comp 1 Data Sources",fieldType:"text",wizardDataPath:"comps[0].dataSources",label:"Comp 1 Data Sources",required:!1},{pdfFieldName:"Comp 1 Verification Sources",fieldType:"text",wizardDataPath:"comps[0].verificationSources",label:"Comp 1 Verification",required:!1},{pdfFieldName:"Comp 1 Sales Financing",fieldType:"text",wizardDataPath:"comps[0].saleOrFinancingConcessions",label:"Comp 1 Financing/Concessions",required:!1},{pdfFieldName:"Comp 1 Date of Sale",fieldType:"text",wizardDataPath:"comps[0].dateOfSale",label:"Comp 1 Date of Sale",required:!1,uadFormat:"s##/##;c##/##"},{pdfFieldName:"Comp 1 Location",fieldType:"text",wizardDataPath:"comps[0].location",label:"Comp 1 Location",required:!1,uadFormat:"N;Res;A"},{pdfFieldName:"Comp 1 Leasehold Fee Simple",fieldType:"text",wizardDataPath:"comps[0].leaseholdFeeSimple",label:"Comp 1 Leasehold/Fee",required:!1},{pdfFieldName:"Comp 1 Site",fieldType:"text",wizardDataPath:"comps[0].site",label:"Comp 1 Site",required:!1},{pdfFieldName:"Comp 1 View",fieldType:"text",wizardDataPath:"comps[0].view",label:"Comp 1 View",required:!1,uadFormat:"N;Res"},{pdfFieldName:"Comp 1 Design Style",fieldType:"text",wizardDataPath:"comps[0].design",label:"Comp 1 Design",required:!1},{pdfFieldName:"Comp 1 Quality",fieldType:"text",wizardDataPath:"comps[0].quality",label:"Comp 1 Quality",required:!1,uadFormat:"Q1-Q6"},{pdfFieldName:"Comp 1 Actual Age",fieldType:"text",wizardDataPath:"comps[0].actualAge",label:"Comp 1 Age",required:!1},{pdfFieldName:"Comp 1 Condition",fieldType:"text",wizardDataPath:"comps[0].condition",label:"Comp 1 Condition",required:!1,uadFormat:"C1-C6"},{pdfFieldName:"Comp 1 Above Grade Room Count",fieldType:"text",wizardDataPath:"comps[0].aboveGradeTotal",label:"Comp 1 Room Count",required:!1},{pdfFieldName:"Comp 1 GLA",fieldType:"text",wizardDataPath:"comps[0].gla",label:"Comp 1 GLA",required:!1},{pdfFieldName:"Comp 1 Basement Finished",fieldType:"text",wizardDataPath:"comps[0].basement",label:"Comp 1 Basement",required:!1},{pdfFieldName:"Comp 1 Functional Utility",fieldType:"text",wizardDataPath:"comps[0].functionalUtility",label:"Comp 1 Functional",required:!1},{pdfFieldName:"Comp 1 Heating Cooling",fieldType:"text",wizardDataPath:"comps[0].heatingCooling",label:"Comp 1 HVAC",required:!1},{pdfFieldName:"Comp 1 Energy Efficient",fieldType:"text",wizardDataPath:"comps[0].energyEfficient",label:"Comp 1 Energy",required:!1},{pdfFieldName:"Comp 1 Garage Carport",fieldType:"text",wizardDataPath:"comps[0].garageCarport",label:"Comp 1 Garage",required:!1},{pdfFieldName:"Comp 1 Porch Patio Deck",fieldType:"text",wizardDataPath:"comps[0].porchPatioDeck",label:"Comp 1 Porch/Patio",required:!1},{pdfFieldName:"Comparable Sale 2",fieldType:"text",wizardDataPath:"comps[1].address",label:"Comp 2 Address",required:!1},{pdfFieldName:"Comparable Sale 2 Sale Price",fieldType:"text",wizardDataPath:"comps[1].salePrice",label:"Comp 2 Sale Price",required:!1},{pdfFieldName:"Comp 2 Price Per GLA",fieldType:"text",wizardDataPath:"comps[1].pricePerSqFt",label:"Comp 2 Price/GLA",required:!1},{pdfFieldName:"Comp 2 Data Sources",fieldType:"text",wizardDataPath:"comps[1].dataSources",label:"Comp 2 Data Sources",required:!1},{pdfFieldName:"Comp 2 Verification Sources",fieldType:"text",wizardDataPath:"comps[1].verificationSources",label:"Comp 2 Verification",required:!1},{pdfFieldName:"Comp 2 Sales Financing",fieldType:"text",wizardDataPath:"comps[1].saleOrFinancingConcessions",label:"Comp 2 Financing/Concessions",required:!1},{pdfFieldName:"Comp 2 Date of Sale",fieldType:"text",wizardDataPath:"comps[1].dateOfSale",label:"Comp 2 Date of Sale",required:!1,uadFormat:"s##/##;c##/##"},{pdfFieldName:"Comp 2 Location",fieldType:"text",wizardDataPath:"comps[1].location",label:"Comp 2 Location",required:!1,uadFormat:"N;Res;A"},{pdfFieldName:"Comp 2 Leasehold Fee Simple",fieldType:"text",wizardDataPath:"comps[1].leaseholdFeeSimple",label:"Comp 2 Leasehold/Fee",required:!1},{pdfFieldName:"Comp 2 Site",fieldType:"text",wizardDataPath:"comps[1].site",label:"Comp 2 Site",required:!1},{pdfFieldName:"Comp 2 View",fieldType:"text",wizardDataPath:"comps[1].view",label:"Comp 2 View",required:!1,uadFormat:"N;Res"},{pdfFieldName:"Comp 2 Design Style",fieldType:"text",wizardDataPath:"comps[1].design",label:"Comp 2 Design",required:!1},{pdfFieldName:"Comp 2 Quality",fieldType:"text",wizardDataPath:"comps[1].quality",label:"Comp 2 Quality",required:!1,uadFormat:"Q1-Q6"},{pdfFieldName:"Comp 2 Actual Age",fieldType:"text",wizardDataPath:"comps[1].actualAge",label:"Comp 2 Age",required:!1},{pdfFieldName:"Comp 2 Condition",fieldType:"text",wizardDataPath:"comps[1].condition",label:"Comp 2 Condition",required:!1,uadFormat:"C1-C6"},{pdfFieldName:"Comp 2 Above Grade Room Count",fieldType:"text",wizardDataPath:"comps[1].aboveGradeTotal",label:"Comp 2 Room Count",required:!1},{pdfFieldName:"Comp 2 GLA",fieldType:"text",wizardDataPath:"comps[1].gla",label:"Comp 2 GLA",required:!1},{pdfFieldName:"Comp 2 Basement Finished",fieldType:"text",wizardDataPath:"comps[1].basement",label:"Comp 2 Basement",required:!1},{pdfFieldName:"Comp 2 Functional Utility",fieldType:"text",wizardDataPath:"comps[1].functionalUtility",label:"Comp 2 Functional",required:!1},{pdfFieldName:"Comp 2 Heating Cooling",fieldType:"text",wizardDataPath:"comps[1].heatingCooling",label:"Comp 2 HVAC",required:!1},{pdfFieldName:"Comp 2 Energy Efficient",fieldType:"text",wizardDataPath:"comps[1].energyEfficient",label:"Comp 2 Energy",required:!1},{pdfFieldName:"Comp 2 Garage Carport",fieldType:"text",wizardDataPath:"comps[1].garageCarport",label:"Comp 2 Garage",required:!1},{pdfFieldName:"Comp 2 Porch Patio Deck",fieldType:"text",wizardDataPath:"comps[1].porchPatioDeck",label:"Comp 2 Porch/Patio",required:!1},{pdfFieldName:"Comparable Sale 3",fieldType:"text",wizardDataPath:"comps[2].address",label:"Comp 3 Address",required:!1},{pdfFieldName:"Comparable Sale 3 Sale Price",fieldType:"text",wizardDataPath:"comps[2].salePrice",label:"Comp 3 Sale Price",required:!1},{pdfFieldName:"Comp 3 Price Per GLA",fieldType:"text",wizardDataPath:"comps[2].pricePerSqFt",label:"Comp 3 Price/GLA",required:!1},{pdfFieldName:"Comp 3 Data Sources",fieldType:"text",wizardDataPath:"comps[2].dataSources",label:"Comp 3 Data Sources",required:!1},{pdfFieldName:"Comp 3 Verification Sources",fieldType:"text",wizardDataPath:"comps[2].verificationSources",label:"Comp 3 Verification",required:!1}
10,{pdfFieldName:"Comp 3 Sales Financing",fieldType:"text",wizardDataPath:"comps[2].saleOrFinancingConcessions",label:"Comp 3 Financing/Concessions",required:!1},{pdfFieldName:"Comp 3 Date of Sale",fieldType:"text",wizardDataPath:"comps[2].dateOfSale",label:"Comp 3 Date of Sale",required:!1,uadFormat:"s##/##;c##/##"},{pdfFieldName:"Comp 3 Location",fieldType:"text",wizardDataPath:"comps[2].location",label:"Comp 3 Location",required:!1,uadFormat:"N;Res;A"},{pdfFieldName:"Comp 3 Leasehold Fee Simple",fieldType:"text",wizardDataPath:"comps[2].leaseholdFeeSimple",label:"Comp 3 Leasehold/Fee",required:!1},{pdfFieldName:"Comp 3 Site",fieldType:"text",wizardDataPath:"comps[2].site",label:"Comp 3 Site",required:!1},{pdfFieldName:"Comp 3 View",fieldType:"text",wizardDataPath:"comps[2].view",label:"Comp 3 View",required:!1,uadFormat:"N;Res"},{pdfFieldName:"Comp 3 Design Style",fieldType:"text",wizardDataPath:"comps[2].design",label:"Comp 3 Design",required:!1},{pdfFieldName:"Comp 3 Quality",fieldType:"text",wizardDataPath:"comps[2].quality",label:"Comp 3 Quality",required:!1,uadFormat:"Q1-Q6"},{pdfFieldName:"Comp 3 Actual Age",fieldType:"text",wizardDataPath:"comps[2].actualAge",label:"Comp 3 Age",required:!1},{pdfFieldName:"Comp 3 Condition",fieldType:"text",wizardDataPath:"comps[2].condition",label:"Comp 3 Condition",required:!1,uadFormat:"C1-C6"},{pdfFieldName:"Comp 3 Above Grade Room Count",fieldType:"text",wizardDataPath:"comps[2].aboveGradeTotal",label:"Comp 3 Room Count",required:!1},{pdfFieldName:"Comp 3 GLA",fieldType:"text",wizardDataPath:"comps[2].gla",label:"Comp 3 GLA",required:!1},{pdfFieldName:"Comp 3 Basement Finished",fieldType:"text",wizardDataPath:"comps[2].basement",label:"Comp 3 Basement",required:!1},{pdfFieldName:"Comp 3 Functional Utility",fieldType:"text",wizardDataPath:"comps[2].functionalUtility",label:"Comp 3 Functional",required:!1},{pdfFieldName:"Comp 3 Heating Cooling",fieldType:"text",wizardDataPath:"comps[2].heatingCooling",label:"Comp 3 HVAC",required:!1},{pdfFieldName:"Comp 3 Energy Efficient",fieldType:"text",wizardDataPath:"comps[2].energyEfficient",label:"Comp 3 Energy",required:!1},{pdfFieldName:"Comp 3 Garage Carport",fieldType:"text",wizardDataPath:"comps[2].garageCarport",label:"Comp 3 Garage",required:!1},{pdfFieldName:"Comp 3 Porch Patio Deck",fieldType:"text",wizardDataPath:"comps[2].porchPatioDeck",label:"Comp 3 Porch/Patio",required:!1},{pdfFieldName:"Comp 1 Net Adjustment",fieldType:"text",wizardDataPath:"comps[0].netAdjustment",label:"Net Adjustment",required:!1},{pdfFieldName:"Comp 2 Net Adjustment",fieldType:"text",wizardDataPath:"comps[1].netAdjustment",label:"Net Adjustment",required:!1},{pdfFieldName:"Comp 3 Net Adjustment",fieldType:"text",wizardDataPath:"comps[2].netAdjustment",label:"Net Adjustment",required:!1},{pdfFieldName:"Comp 1 Adjusted Sale Price",fieldType:"text",wizardDataPath:"comps[0].adjustedSalePrice",label:"Adjusted Sale Price",required:!1},{pdfFieldName:"Comp 2 Adjusted Sale Price",fieldType:"text",wizardDataPath:"comps[1].adjustedSalePrice",label:"Adjusted Sale Price",required:!1},{pdfFieldName:"Comp 3 Adjusted Sale Price",fieldType:"text",wizardDataPath:"comps[2].adjustedSalePrice",label:"Adjusted Sale Price",required:!1},{pdfFieldName:"Summary of Sales Comparison Approach",fieldType:"textarea",wizardDataPath:"salesComparison.summary",label:"Summary of Sales Comparison Approach",required:!0}]},yY={id:"values",name:"Values",description:"Cost Approach and Income Approach to Value (Not required by Fannie Mae)",requiredForGeneration:!1,fields:[{pdfFieldName:"Site Value Explanation",fieldType:"textarea",wizardDataPath:"costApproach.siteValueExplanation",label:"Site Value Estimation Method",required:!1,group:"Cost Approach — Site Value"},{pdfFieldName:"Opinion of Site Value",fieldType:"text",wizardDataPath:"costApproach.opinionOfSiteValue",label:"Opinion of Site Value ($)",required:!1,group:"Cost Approach — Site Value"},{pdfFieldName:"Dwelling Sq Ft",fieldType:"text",wizardDataPath:"costApproach.dwellingSqFt",label:"Dwelling Area (Sq.Ft.)",required:!1,group:"Cost Approach — Dwelling Cost"},{pdfFieldName:"Dwelling Cost Per Sq Ft",fieldType:"text",wizardDataPath:"costApproach.dwellingCostPerSqFt",label:"Dwelling Cost per Sq.Ft. ($)",required:!1,group:"Cost Approach — Dwelling Cost"},{pdfFieldName:"Dwelling Total",fieldType:"text",wizardDataPath:"costApproach.dwellingTotal",label:"Total Dwelling Value ($)",required:!1,group:"Cost Approach — Dwelling Cost"},{pdfFieldName:"Basement Sq Ft",fieldType:"text",wizardDataPath:"costApproach.basementSqFt",label:"Basement Area (Sq.Ft.)",required:!1,group:"Cost Approach — Basement Cost"},{pdfFieldName:"Basement Cost Per Sq Ft",fieldType:"text",wizardDataPath:"costApproach.basementCostPerSqFt",label:"Basement Cost per Sq.Ft. ($)",required:!1,group:"Cost Approach — Basement Cost"},{pdfFieldName:"Basement Total",fieldType:"text",wizardDataPath:"costApproach.basementTotal",label:"Total Basement Value ($)",required:!1,group:"Cost Approach — Basement Cost"},{pdfFieldName:"As Is Value Site Improvements",fieldType:"text",wizardDataPath:"costApproach.asIsValueSiteImprovements",label:"As-is Value of Site Improvements ($)",required:!1,group:"Cost Approach — Cost Summary"},{pdfFieldName:"Total Estimate Cost New",fieldType:"text",wizardDataPath:"costApproach.totalEstimateCostNew",label:"Total Estimated Cost-New ($)",required:!1,group:"Cost Approach — Cost Summary"},{pdfFieldName:"Depreciation Physical",fieldType:"text",wizardDataPath:"costApproach.depreciationPhysical",label:"Depreciation — Physical ($)",required:!1,group:"Cost Approach — Depreciation"},{pdfFieldName:"Depreciation Functional",fieldType:"text",wizardDataPath:"costApproach.depreciationFunctional",label:"Depreciation — Functional ($)",required:!1,group:"Cost Approach — Depreciation"},{pdfFieldName:"Depreciation External",fieldType:"text",wizardDataPath:"costApproach.depreciationExternal",label:"Depreciation — External ($)",required:!1,group:"Cost Approach — Depreciation"},{pdfFieldName:"Depreciation Total",fieldType:"text",wizardDataPath:"costApproach.depreciationTotal",label:"Total Depreciation ($)",required:!1,group:"Cost Approach — Depreciation"},{pdfFieldName:"Depreciated Cost Improvements",fieldType:"text",wizardDataPath:"costApproach.depreciatedCostImprovements",label:"Depreciated Cost of Improvements ($)",required:!1,group:"Cost Approach — Indicated Value"},{pdfFieldName:"Indicated Value Cost Approach",fieldType:"text",wizardDataPath:"costApproach.indicatedValue",label:"Indicated Value by Cost Approach ($)",required:!1,group:"Cost Approach — Indicated Value"},{pdfFieldName:"Estimated Remaining Economic Life",fieldType:"text",wizardDataPath:"costApproach.estimatedRemainingEconomicLife",label:"Estimated Remaining Economic Life (Years)",required:!1,group:"Cost Approach — Supporting Data"},{pdfFieldName:"Source of Cost Data",fieldType:"text",wizardDataPath:"costApproach.sourceOfCostData",label:"Source of Cost Data",required:!1,group:"Cost Approach — Supporting Data"},{pdfFieldName:"Quality Rating Cost Service",fieldType:"text",wizardDataPath:"costApproach.qualityRatingCostService",label:"Quality Rating from Cost Service",required:!1,group:"Cost Approach — Supporting Data"},{pdfFieldName:"Effective Date Cost Data",fieldType:"text",wizardDataPath:"costApproach.effectiveDateCostData",label:"Effective Date of Cost Data",required:!1,group:"Cost Approach — Supporting Data"},{pdfFieldName:"Comments Cost Approach",fieldType:"textarea",wizardDataPath:"costApproach.comments",label:"Comments on Cost Approach",required:!1,group:"Cost Approach — Supporting Data"},{pdfFieldName:"Estimated Market Rent",fieldType:"text",wizardDataPath:"incomeApproach.estimatedMarketRent",label:"Estimated Monthly Market Rent ($)",required:!1,group:"Income Approach"},{pdfFieldName:"Gross Rent Multiplier",fieldType:"text",wizardDataPath:"incomeApproach.grossRentMultiplier",label:"Gross Rent Multiplier (GRM)",required:!1,group:"Income Approach"},{pdfFieldName:"Indicated Value Income Approach",fieldType:"text",wizardDataPath:"incomeApproach.indicatedValue",label:"Indicated Value by Income Approach ($)",required:!1,group:"Income Approach"},{pdfFieldName:"Summary Income Approach",fieldType:"textarea",wizardDataPath:"incomeApproach.summary",label:"Summary of Income Approach",required:!1,group:"Income Approach"}]},SY={id:"reconciliation",name:"Reconciliation",description:"Value reconciliation and final opinion",requiredForGeneration:!0,fields:[{pdfFieldName:"Indicated Value Sales Comparison",fieldType:"text",wizardDataPath:"reconciliation.indicatedValueBySalesComparison",label:"Indicated Value by: Sales Comparison Approach $",required:!1},{pdfFieldName:"Indicated Value Cost Approach",fieldType:"text",wizardDataPath:"reconciliation.indicatedValueByCostApproach",label:"Indicated Value by: Cost Approach $",required:!1},{pdfFieldName:"Indicated Value Income Approach",fieldType:"text",wizardDataPath:"reconciliation.indicatedValueByIncomeApproach",label:"Indicated Value by: Income Approach $",required:!1},{pdfFieldName:"Appraisal Made As Is",fieldType:"checkbox",wizardDataPath:"reconciliation.appraisalMadeAsIs",label:"This appraisal is made 'as is'",required:!1},{pdfFieldName:"Subject To Completion",fieldType:"checkbox",wizardDataPath:"reconciliation.subjectToCompletion",label:"Subject to completion per plans and specifications",required:!1},{pdfFieldName:"Subject To Repairs",fieldType:"checkbox",wizardDataPath:"reconciliation.subjectToRepairs",label:"Subject to the following repairs or alterations",required:!1},{pdfFieldName:"Subject To Inspection",fieldType:"checkbox",wizardDataPath:"reconciliation.subjectToInspection",label:"Subject to the following required inspection",required:!1},{pdfFieldName:"Conditions of Appraisal",fieldType:"textarea",wizardDataPath:"reconciliation.conditionsOfAppraisal",label:"Conditions of Appraisal",required:!1},{pdfFieldName:"Market Value",fieldType:"text",wizardDataPath:"reconciliation.finalOpinionOfValue",label:"Opinion of Market Value is $",required:!0},{pdfFieldName:"Effective Date of Appraisal",fieldType:"text",wizardDataPath:"reconciliation.effectiveDateOfAppraisal",label:"Effective Date of Appraisal",required:!0}]},vY={id:"signature",name:"Signature",description:"Appraiser information and certification",requiredForGeneration:!0,fields:[{pdfFieldName:"Appraiser Name",fieldType:"text",wizardDataPath:"appraiser.name",label:"Appraiser Name",required:!0},{pdfFieldName:"Company Name",fieldType:"text",wizardDataPath:"appraiser.companyName",label:"Company Name",required:!0},{pdfFieldName:"License Number",fieldType:"text",wizardDataPath:"appraiser.licenseNumber",label:"License Number",required:!0}
10,{pdfFieldName:"License State",fieldType:"text",wizardDataPath:"appraiser.licenseState",label:"License State",required:!0},{pdfFieldName:"License Expiration",fieldType:"text",wizardDataPath:"appraiser.licenseExpiration",label:"License Expiration",required:!0},{pdfFieldName:"Signature",fieldType:"text",wizardDataPath:"appraiser.signatureImage",label:"Signature",required:!0},{pdfFieldName:"Date of Signature",fieldType:"text",wizardDataPath:"appraiser.signatureDate",label:"Date of Signature",required:!0}]},Yp=[mY,hY,fY,gY,xY,bY,SY,yY,vY];function NY(t=3){return Yp.map(a=>{const s=new Set;let r=0,n=0,i=0,l=0;return a.fields.forEach(c=>{if(!c.wizardDataPath)return;const d=c.wizardDataPath.match(/comps\[(\d+)\]/);if(d){if(parseInt(d[1])>=t)return;l++}if(c.group){if(s.has(c.group))return;s.add(c.group)}r++,c.required?n++:i++}),{sectionId:a.id,sectionName:a.name,interactiveFields:r,requiredFields:n,optionalFields:i,compDependentFields:l}})}const AY=[{sectionId:"subject",fieldId:"subject.Property Address",label:"Property Address"},{sectionId:"subject",fieldId:"subject.City",label:"City"},{sectionId:"subject",fieldId:"subject.State",label:"State"},{sectionId:"subject",fieldId:"subject.Zip Code",label:"Zip Code"},{sectionId:"subject",fieldId:"subject.County",label:"County"},{sectionId:"subject",fieldId:"subject.Borrower",label:"Borrower"},{sectionId:"subject",fieldId:"subject.Owner of Public Record",label:"Owner of Public Record"},{sectionId:"subject",fieldId:"subject.Legal Description",label:"Legal Description"},{sectionId:"subject",fieldId:"subject.Assessors Parcel",label:"Assessor's Parcel #"},{sectionId:"subject",fieldId:"subject.Tax Year",label:"Tax Year"},{sectionId:"subject",fieldId:"subject.R.E. Taxes",label:"R.E. Taxes"},{sectionId:"subject",fieldId:"subject.Map Reference",label:"Map Reference"},{sectionId:"subject",fieldId:"subject.Census Tract",label:"Census Tract"},{sectionId:"subject",fieldId:"subject.Lender Client",label:"Lender/Client"},{sectionId:"subject",fieldId:"subject.Offering Data Sources",label:"Report data source(s) used, offering price(s), and date(s)"},{sectionId:"site",fieldId:"site.Specific Zoning Classification",label:"Zoning Classification"},{sectionId:"salesComparison",fieldId:"salesComparison.Subject Address",label:"Subject Address"},{sectionId:"salesComparison",fieldId:"salesComparison.Subject Location",label:"Subject Location"},{sectionId:"salesComparison",fieldId:"salesComparison.Subject Site",label:"Subject Site"},{sectionId:"salesComparison",fieldId:"salesComparison.Subject View",label:"Subject View"},{sectionId:"salesComparison",fieldId:"salesComparison.Subject Design Style",label:"Subject Design (Style)"},{sectionId:"salesComparison",fieldId:"salesComparison.Subject Quality",label:"Subject Quality"},{sectionId:"salesComparison",fieldId:"salesComparison.Subject Actual Age",label:"Subject Actual Age"},{sectionId:"salesComparison",fieldId:"salesComparison.Subject Condition",label:"Subject Condition"},{sectionId:"salesComparison",fieldId:"salesComparison.Comparable Sale 1",label:"Comp 1 Address"},{sectionId:"salesComparison",fieldId:"salesComparison.Comparable Sale 1 Sale Price",label:"Comp 1 Sale Price"},{sectionId:"salesComparison",fieldId:"salesComparison.Summary of Sales Comparison Approach",label:"Summary of Sales Comparison Approach"},{sectionId:"reconciliation",fieldId:"reconciliation.Opinion of Market Value",label:"Opinion of Market Value"},{sectionId:"reconciliation",fieldId:"reconciliation.Effective Date of Appraisal",label:"Effective Date of Appraisal"},{sectionId:"signature",fieldId:"signature.Appraiser Name",label:"Appraiser Name"},{sectionId:"signature",fieldId:"signature.Company Name",label:"Company Name"},{sectionId:"signature",fieldId:"signature.License Number",label:"License Number"},{sectionId:"signature",fieldId:"signature.License State",label:"License State"},{sectionId:"signature",fieldId:"signature.License Expiration",label:"License Expiration"},{sectionId:"signature",fieldId:"signature.Signature",label:"Signature"},{sectionId:"signature",fieldId:"signature.Date of Signature",label:"Date of Signature"}];function ud(t,a){return a?t[a]??null:null}function op(t){return t==null?!1:typeof t=="boolean"?!0:!(typeof t=="string"&&t.trim()==="")}const jY=["C1","C2","C3","C4","C5","C6"],TY=["Q1","Q2","Q3","Q4","Q5","Q6"],IY=["N;Res;","N;Ind;","B;
10Res;","B;Ind;","A;Res;","A;Ind;"],CY=["N;Res;","N;Ind;","B;Res;","B;Ind;","A;Res;","A;Ind;"];function RY(t){if(t.fieldType==="checkbox")return"checkbox";if(t.fieldType==="textarea")return"textarea";const a=t.label.toLowerCase(),s=t.pdfFieldName.toLowerCase();return t.uadFormat?.includes("C1-C6")||s.includes("condition")?"uad-condition":t.uadFormat?.includes("Q1-Q6")||s.includes("quality")?"uad-quality":t.uadFormat?.includes("N;Res;A")&&(a.includes("location")||s.includes("location"))?"uad-location":t.uadFormat?.includes("N;Res")&&(a.includes("view")||s.includes("view"))?"uad-view":a.includes("date")||a.includes("expiration")?"date":a.includes("year built")||a.includes("tax year")||a.includes("effective age")||a.includes("actual age")||a.includes("age low")||a.includes("age high")||a.includes("age pred")?"year":a.includes("$")||a.includes("price")||a.includes("value")||a.includes("taxes")||a.includes("hoa")||a.includes("rent")||a.includes("cost")||a.includes("assessment")?"currency":a.includes("%")||a.includes("percent")?"percentage":a.includes("rooms")||a.includes("bedroom")||a.includes("bath")||a.includes("gla")||a.includes("sq ft")||a.includes("square feet")||a.includes("# cars")||a.includes("fireplace")||a.includes("stories")||a.includes("multiplier")?"number":"text"}const EY=new Set(["contract.isPurchase","contract.contractPrice","contract.contractDate","contract.sellerName","contract.isSellerOwner","contract.sellerOwnerDataSource"]);function Vv(t,a){return!!(t.wizardDataPath==="subject.propertyRightsOtherDescribe"&&!a["subject.propertyRightsOther"]||t.wizardDataPath==="subject.assignmentOtherDescribe"&&!a["subject.assignmentOther"]||t.wizardDataPath&&EY.has(t.wizardDataPath)&&!a["subject.assignmentPurchase"])}function nv(t,a,s){return t.fields.filter(r=>r.group===a&&r.wizardDataPath).some(r=>op(ud(s,r.wizardDataPath)))}function wY({section:t,formData:a}){const s=new Set;let r=0,n=0;t.fields.forEach(c=>{if(!c.wizardDataPath||Vv(c,a))return;if(c.group){if(s.has(c.group))return;s.add(c.group),n++,nv(t,c.group,a)&&r++;return}n++;const d=ud(a,c.wizardDataPath);op(d)&&r++});const i=n>0?Math.round(r/n*100):0,l=i===100;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-16 h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:Q("h-full rounded-full transition-all duration-300",l?"bg-emerald-500":"bg-primary"),style:{width:`${i}%`}})}),e.jsxs("span",{className:Q("text-[10px] font-medium tabular-nums",l?"text-emerald-600":"text-slate-500"),children:[r,"/",n]})]})}function _0({field:t,value:a,onChange:s}){const[r,n]=o.useState(!1),[i,l]=o.useState(""),c=t.wizardDataPath;if(!c)return null;const d=op(a),p=d?typeof a=="boolean"?a?"Yes":"No":String(a):"",u=RY(t);if(u==="checkbox")return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>s(c,!a),className:Q("w-4 h-4 rounded border flex items-center justify-center transition-colors",a?"bg-primary border-primary text-white":"border-slate-300 hover:border-primary"),"data-testid":`report-checkbox-${t.pdfFieldName.replace(/\s+/g,"-").toLowerCase()}`,children:a&&e.jsx(Bs,{className:"w-3 h-3"})}),e.jsx("span",{className:"text-xs text-slate-600",children:t.label})]});if(r){const m=u==="textarea";if(u.startsWith("uad-")){const f=u==="uad-condition"?jY:u==="uad-quality"?TY:u==="uad-location"?IY:CY;return e.jsxs("div",{className:"flex items-center gap-1.5 w-full",children:[e.jsxs(sr,{value:i,onValueChange:v=>{s(c,v),n(!1)},children:[e.jsx(rr,{className:"h-7 text-xs flex-1",children:e.jsx(or,{placeholder:"Select..."})}),e.jsx(nr,{children:f.map(v=>e.jsx(vs,{value:v,className:"text-xs",children:v},v))})]}),e.jsx(De,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>n(!1),children:e.jsx(ur,{className:"w-3 h-3"})})]})}return e.jsxs("div",{className:"flex items-center gap-1.5 w-full",children:[m?e.jsx(yi,{value:i,onChange:f=>l(f.target.value),className:"text-xs min-h-[60px] flex-1",autoFocus:!0}):e.jsx(ze,{value:i,onChange:f=>l(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(s(c,i),n(!1)),f.key==="Escape"&&n(!1)},type:u==="date"?"date":"text",inputMode:u==="number"||u==="currency"||u==="percentage"||u==="year"?"numeric":void 0,className:"text-xs h-7 flex-1",autoFocus:!0}),e.jsx(De,{size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{s(c,i),n(!1)},children:e.jsx(Bs,{className:"w-3 h-3"})}),e.jsx(De,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>n(!1),children:e.jsx(ur,{className:"w-3 h-3"})})]})}return e.jsxs("div",{className:Q("flex items-center justify-between gap-2 group cursor-pointer rounded px-2 py-1 -mx-2 hover:bg-slate-50 transition-colors",!d&&"bg-amber-50/50"),onClick:()=>{l(p),n(!0)},"data-testid":`report-field-${t.pdfFieldName.replace(/\s+/g,"-").toLowerCase()}`,children:[e.jsx("span",{className:Q("text-xs truncate",d?"text-slate-800":"text-slate-400 italic"),children:d?p:"Missing"}),e.jsx(Ru,{className:"w-3 h-3 text-slate-300 opacity-0 group-hover:opacity-100 transition-opacity shrink-0"})]})}function PY({section:t,formData:a,onFieldChange:s}){const r=t.fields.filter(m=>m.wizardDataPath?.startsWith("subject.")&&!m.wizardDataPath?.startsWith("subject.assignment")&&!m.wizardDataPath?.startsWith("subject.offered")),n=t.fields.filter(m=>m.wizardDataPath?.startsWith("comps[0]")),i=t.fields.filter(m=>m.wizardDataPath?.startsWith("comps[1]")),l=t.fields.filter(m=>m.wizardDataPath?.startsWith("comps[2]")),c=t.fields.find(m=>m.wizardDataPath==="salesComparison.summary"),d=n.some(m=>op(ud(a,m.wizardDataPath))),p=["Address","Sale Price","Price/GLA","Data Sources","Verification","Financing","Concessions","Date of Sale","Location","
10Leasehold/Fee","Site","View","Design","Quality","Age","Condition","Room Count","GLA","Basement","Functional","HVAC","Energy","Garage","Porch/Patio","Net Adj.","Gross Adj.","Adj. Price"],u=(m,h)=>{const f=h.toLowerCase();return m.find(v=>{const S=v.label.toLowerCase();return f==="address"?S.includes("address"):f==="sale price"?S.includes("sale price")&&!S.includes("adj")&&!S.includes("per"):f==="price/gla"?S.includes("price")&&(S.includes("gla")||S.includes("per")):f==="data sources"?S.includes("data source"):f==="verification"?S.includes("verif"):f==="financing"?S.includes("financ")||S.includes("sales or"):f==="concessions"?S.includes("concess"):f==="date of sale"?S.includes("date"):f==="location"?S.includes("location"):f==="leasehold/fee"?S.includes("leasehold")||S.includes("fee simple"):f==="site"?S.includes("site")&&!S.includes("data"):f==="view"?S.includes("view"):f==="design"?S.includes("design"):f==="quality"?S.includes("quality"):f==="age"?S.includes("age"):f==="condition"?S.includes("condition"):f==="room count"?S.includes("room"):f==="gla"?S.includes("gla")||S.includes("gross living"):f==="basement"?S.includes("basement"):f==="functional"?S.includes("functional"):f==="hvac"?S.includes("heating")||S.includes("hvac"):f==="energy"?S.includes("energy"):f==="garage"?S.includes("garage"):f==="porch/patio"?S.includes("porch")||S.includes("patio"):f==="net adj."?S.includes("net adj"):f==="gross adj."?S.includes("gross adj"):f==="adj. price"?S.includes("adjusted sale"):!1})};return e.jsxs("div",{className:"space-y-3",children:[!d&&e.jsxs("div",{className:"text-xs text-slate-500 italic bg-slate-50 rounded-lg px-3 py-2 flex items-center gap-2",children:[e.jsx(Di,{className:"w-3.5 h-3.5 text-amber-400"}),"Comparables will populate from the Sales Comparison step"]}),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",{children:e.jsxs("tr",{className:"bg-slate-50 border-b border-slate-200",children:[e.jsx("th",{className:"text-left px-2 py-1.5 font-semibold text-slate-600 w-[100px] sticky left-0 bg-slate-50 z-10",children:"Field"}),e.jsx("th",{className:"text-left px-2 py-1.5 font-semibold text-slate-600 min-w-[120px]",children:"Subject"}),e.jsx("th",{className:"text-left px-2 py-1.5 font-semibold text-slate-600 min-w-[120px]",children:"Comp 1"}),e.jsx("th",{className:"text-left px-2 py-1.5 font-semibold text-slate-600 min-w-[120px]",children:"Comp 2"}),e.jsx("th",{className:"text-left px-2 py-1.5 font-semibold text-slate-600 min-w-[120px]",children:"Comp 3"})]})}),e.jsx("tbody",{children:p.map((m,h)=>{const f=u(r,m),v=u(n,m),S=u(i,m),N=u(l,m);return!f&&!v&&!S&&!N?null:e.jsxs("tr",{className:Q("border-b border-slate-100",h%2===0&&"bg-white",h%2===1&&"bg-slate-50/30"),children:[e.jsx("td",{className:"px-2 py-1 font-medium text-slate-500 sticky left-0 bg-inherit z-10 text-[10px]",children:m}),[f,v,S,N].map((x,y)=>e.jsx("td",{className:"px-2 py-0.5",children:x?e.jsx(_0,{field:x,value:ud(a,x.wizardDataPath),onChange:s}):e.jsx("span",{className:"text-slate-300 text-[10px]",children:"—"})},y))]},m)})})]})}),c&&e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"text-[10px] font-semibold uppercase text-slate-400 mb-1",children:"Summary of Sales Comparison Approach"}),e.jsx(_0,{field:c,value:ud(a,c.wizardDataPath),onChange:s})]})]})}function OY({section:t,formData:a,onFieldChange:s,filterMode:r,defaultOpen:n,sectionRef:i,showQcSidebar:l,onAddFieldRule:c,orderId:d}){const[p,u]=o.useState(n),m=o.useMemo(()=>{const S=[];let N=null;return t.fields.forEach(x=>{x.wizardDataPath&&(x.group?N&&N.groupName===x.group?N.fields.push(x):(N={groupName:x.group,fields:[x]},S.push(N)):(N=null,S.push({groupName:null,fields:[x]})))}),S},[t.fields]),h=o.useMemo(()=>m.map(S=>({...S,fields:S.fields.filter(N=>!Vv(N,a))})).filter(S=>S.fields.length>0),[m,a]),f=o.useMemo(()=>r==="all"?h:r==="missing"?h.filter(S=>S.groupName&&S.fields.every(x=>x.fieldType==="checkbox")?!S.fields.some(y=>op(ud(a,y.wizardDataPath))):S.fields.some(x=>
10!op(ud(a,x.wizardDataPath)))):h,[h,r,a]);if(r==="missing"&&f.length===0)return null;const v=t.id==="salesComparison";return e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden","data-testid":`report-section-${t.id}`,ref:i,children:[e.jsxs("button",{onClick:()=>u(!p),className:"w-full px-4 py-3 flex items-center justify-between bg-slate-50/80 hover:bg-slate-100/80 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[p?e.jsx(Rr,{className:"w-4 h-4 text-slate-400"}):e.jsx(fo,{className:"w-4 h-4 text-slate-400"}),e.jsx("span",{className:"text-sm font-semibold text-slate-800",children:t.name}),t.requiredForGeneration&&e.jsx(kt,{variant:"outline",className:"text-[9px] px-1 py-0 bg-red-50 text-red-500 border-red-200",children:"Required"})]}),e.jsx(wY,{section:t,formData:a})]}),p&&e.jsx("div",{className:"px-4 py-3 bg-white",children:v?e.jsx(PY,{section:t,formData:a,onFieldChange:s}):e.jsx("div",{className:"space-y-1.5",children:f.map((S,N)=>{if(S.groupName){const b=S.groupName.includes("—"),j=S.fields.every(T=>T.fieldType==="checkbox");return e.jsxs(Mn.Fragment,{children:[e.jsxs("div",{className:Q("py-1.5",b&&"border-b border-slate-100 last:border-b-0"),"data-testid":`report-group-${S.groupName}`,children:[e.jsxs("div",{className:Q("font-semibold tracking-wider mb-1.5",b?"text-[11px] text-slate-700 flex items-center gap-1.5":"text-[10px] uppercase text-slate-400"),children:[b&&e.jsx("div",{className:"w-1 h-3.5 rounded-full bg-primary/60 shrink-0"}),b?S.groupName:S.groupName.replace(/([A-Z])/g," $1").trim()]}),j?e.jsx("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:S.fields.map(T=>e.jsx(_0,{field:T,value:ud(a,T.wizardDataPath),onChange:s},T.pdfFieldName))}):e.jsx("div",{className:"space-y-1",children:S.fields.map(T=>e.jsxs("div",{className:"group/field flex items-start gap-3 py-0.5",children:[e.jsx("div",{className:"w-[200px] shrink-0 pt-0.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[op(ud(a,T.wizardDataPath))?e.jsx(kr,{className:"w-3 h-3 text-emerald-500 shrink-0"}):T.required?e.jsx(Di,{className:"w-3 h-3 text-amber-500 shrink-0"}):e.jsx(fv,{className:"w-3 h-3 text-slate-300 shrink-0"}),e.jsx("span",{className:"text-xs font-medium text-slate-600 truncate",title:T.label,children:T.label}),T.required&&e.jsx("span",{className:"text-red-400 text-xs",children:"*"}),l&&T.wizardDataPath&&c&&e.jsx("button",{className:"opacity-0 group-hover/field:opacity-100 transition-opacity p-0.5 rounded hover:bg-purple-100",title:"Add QC rule for this field",onClick:()=>c(T.wizardDataPath),"data-testid":`add-rule-${T.wizardDataPath}`,children:e.jsx(un,{className:"w-3 h-3 text-purple-400"})})]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(_0,{field:T,value:ud(a,T.wizardDataPath),onChange:s})})]},T.pdfFieldName))})]}),null]},`g-${N}`)}const y=S.fields[0];return e.jsxs(Mn.Fragment,{children:[e.jsxs("div",{className:"group/field flex items-start gap-3 py-1",children:[e.jsx("div",{className:"w-[200px] shrink-0 pt-0.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[op(ud(a,y.wizardDataPath))?e.jsx(kr,{className:"w-3 h-3 text-emerald-500 shrink-0"}):y.required?e.jsx(Di,{className:"w-3 h-3 text-amber-500 shrink-0"}):e.jsx(fv,{className:"w-3 h-3 text-slate-300 shrink-0"}),e.jsx("span",{className:"text-xs font-medium text-slate-600 truncate",title:y.label,children:y.label}),y.required&&e.jsx("span",{className:"text-red-400 text-[10px]",children:"*"}),l&&y.wizardDataPath&&c&&e.jsx("button",{className:"opacity-0 group-hover/field:opacity-100 transition-opacity p-0.5 rounded hover:bg-purple-100",title:"Add QC rule for this field",onClick:()=>c(y.wizardDataPath),"data-testid":`add-rule-${y.wizardDataPath}`,children:e.jsx(un,{className:"w-3 h-3 text-purple-400"})})]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(_0,{field:y,value:ud(a,y.wizardDataPath),onChange:s})})]}),null]},`f-${N}`)})})})]})}function LY({open:t,onClose:a,formData:s,onFieldChange:r,formType:n,orderId:i}){const[l,c]=o.useState("all"),[d,p]=o.useState(Yp[0]?.id||""),u=o.useRef(null),m=o.useRef({}
10),[h,f]=o.useState(!1),[v,S]=o.useState([]),[N,x]=o.useState([]),[y,b]=o.useState(!1),[j,T]=o.useState(!1),[O,E]=o.useState(null),{user:R}=jI(),G=R?.homeAccountId||R?.username||"anonymous",U=ku(),{data:C}=Vr({queryKey:["qc-user-rules-count",G],queryFn:()=>fetch(`/api/qc/user-rules?userId=${G}`).then($=>$.json()),enabled:t}),F=o.useCallback(async()=>{try{const $={};for(const[V,le]of Object.entries(s)){if(!V)continue;const W=V.split("."),me=W[0]||"general",Z=W.slice(1).join(".")||W[0];$[me]||($[me]={}),$[me][Z]=le}const z=await fetch("/api/qc/evaluate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({formData:$,formType:"1004",userId:G})});if(z.ok){const V=await z.json();S(V.findings||[])}}catch($){console.error("[QC] Evaluation error:",$)}},[s,G]),A=o.useCallback(async()=>{b(!0);try{const $=await fetch("/api/qc/ai-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({formData:s,formType:n||"1004"})});if($.ok){const z=await $.json();x(z.findings||[])}}catch($){console.error("[QC] AI Review error:",$)}finally{b(!1)}},[s,n]),M=o.useCallback($=>{$.targetField&&$.autoFixValue!==void 0&&$.autoFixValue!==null&&(r($.targetField,$.autoFixValue),S(z=>z.map(V=>V.id===$.id?{...V,resolved:!0}:V)))},[r]),B=o.useCallback(async $=>{T(!0);try{(await fetch("/api/qc/user-rules",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...$,userId:G})})).ok&&(U.invalidateQueries({queryKey:["qc-user-rules-count",G]}),F())}catch(z){console.error("[QC] Create user rule error:",z)}finally{T(!1)}},[G,U,F]);o.useEffect(()=>{t&&h&&v.length===0&&F()},[t,h]);const oe=n||"URAR Form 1004",ae=o.useCallback($=>{p($);const z=u.current;if(!z)return;let V=m.current[$];if(V||(V=z.querySelector(`[data-testid="report-section-${$}"]`)),V){const le=V.getBoundingClientRect(),W=z.getBoundingClientRect();z.scrollTo({top:le.top-W.top+z.scrollTop-8,behavior:"smooth"})}},[]),D=o.useCallback($=>{const V=$.split(".")[0];V&&ae(V)},[ae]);o.useEffect(()=>{const $=u.current;if(!$||!t)return;const z=()=>{const V=$.getBoundingClientRect().top;let le="",W=1/0;Yp.forEach(me=>{let Z=m.current[me.id];if(Z||(Z=$.querySelector(`[data-testid="report-section-${me.id}"]`),Z&&(m.current[me.id]=Z)),!Z)return;const pe=Math.abs(Z.getBoundingClientRect().top-V);pe<W&&(W=pe,le=me.id)}),le&&le!==d&&p(le)};return $.addEventListener("scroll",z,{passive:!0}),z(),()=>$.removeEventListener("scroll",z)},[t,d]),o.useEffect(()=>{if(!t)return;const $=setTimeout(()=>{const z=u.current;z&&Yp.forEach(V=>{if(!m.current[V.id]){const le=z.querySelector(`[data-testid="report-section-${V.id}"]`);le&&(m.current[V.id]=le)}})},100);return()=>clearTimeout($)},[t]);const _=o.useMemo(()=>{let $=0,z=0,V=0,le=0;const W=new Set;return Yp.forEach(me=>{me.fields.forEach(Z=>{if(!Z.wizardDataPath||Vv(Z,s))return;if(Z.group){if(W.has(Z.group))return;W.add(Z.group),z++,nv(me,Z.group,s)&&$++,Z.required&&(V++,nv(me,Z.group,s)&&le++);return}z++;const pe=ud(s,Z.wizardDataPath);op(pe)&&$++,Z.required&&(V++,op(pe)&&le++)})}),{filled:$,total:z,required:V,requiredFilled:le,pct:z>0?Math.round($/z*100):0}},[s]);return e.jsx(d$,{open:t,onOpenChange:$=>!$&&a(),children:e.jsxs(u$,{side:"right",className:Q("p-0 gap-0 overflow-hidden flex flex-col",h?"w-[900px] sm:max-w-[900px]":"w-[700px] sm:max-w-[700px]"),"data-testid":"see-report-modal",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 bg-white shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-lg font-serif font-bold text-accent","data-testid":"text-report-title",children:oe}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-24 h-2 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:Q("h-full rounded-full transition-all duration-500",_.pct===100?"bg-emerald-500":"bg-primary"),style:{width:`${_.pct}%`}})}),e.jsxs("span",{className:"text-xs font-medium text-slate-500 tabular-nums","data-testid":"text-report-progress",children:[_.filled,"/",_.total," fields (",_.pct,"%)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(De,{variant:"outline",size:"sm",onClick:()=>c(l==="missing"?"all":"missing"),className:Q("h-7 px-2.5 text-xs gap-1.5",l==="missing"?"bg-amber-50 border-amber-200 text-amber-700":""),"data-testid":"button-show-missing",children:[e.jsx(pf,{className:"w-3 h-3"}),l==="missing"?"Show All":"Missing Only"]}),e.jsxs(De,{variant:"outline",size:"sm",onClick:()=>{f(!h),!h&&v.length===0&&F()},className:Q("h-7 px-2.5 text-xs gap-1.5",h?"bg-[#A18A60]/10 border-[#A18A60]/30 text-[#A18A60]":""),"data-testid":"button-toggle-qc",children:[e.jsx(fN,{className:"w-3 h-3"}),"QC",e.jsx(FL,{issueCount:v.length+N.length,hardStopCount:v.filter($=>$.severity==="hard-stop").length})]}),e.jsx("button",{onClick:a,className:"p-1.5 rounded-md hover:bg-slate-100 transition-colors ml-1","data-testid":"button-close-report",children:e.jsx(ur,{className:"w-4 h-4 text-slate-500"})})]})]}),e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[e.jsx("nav",{className:"w-48 shrink-0 border-r border-slate-200 bg-slate-50/50 overflow-y-auto py-2","data-testid":"report-sidebar",children:Yp.map($=>{const z=new Set;let V=0,le=0;$.fields.forEach(pe=>{if(pe.wizardDataPath&&!Vv(pe,s)){if(pe.group){if(z.has(pe.group))return;z.add(pe.group),le++,nv($,pe.group,s)&&V++;return}
10le++,op(ud(s,pe.wizardDataPath))&&V++}});const W=le>0&&V===le,me=V<le,Z=$.name;return e.jsxs("button",{onClick:()=>ae($.id),className:Q("w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 hover:bg-slate-100 transition-colors rounded-r-sm",d===$.id&&"bg-white border-l-2 border-primary font-medium shadow-sm"),"data-testid":`nav-section-${$.id}`,children:[W?e.jsx(kr,{className:"w-3.5 h-3.5 text-emerald-500 shrink-0"}):me?e.jsx(Di,{className:"w-3.5 h-3.5 text-amber-400 shrink-0"}):e.jsx(fv,{className:"w-3.5 h-3.5 text-slate-300 shrink-0"}),e.jsx("span",{className:"truncate",children:Z}),e.jsxs("span",{className:"ml-auto text-[10px] text-slate-400 tabular-nums",children:[V,"/",le]})]},$.id)})}),e.jsxs("div",{ref:u,className:"flex-1 overflow-y-auto p-5 space-y-3","data-testid":"report-content",children:[l==="missing"&&_.filled===_.total&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(kr,{className:"w-10 h-10 text-emerald-500 mb-3"}),e.jsx("h3",{className:"text-base font-medium text-slate-700",children:"All fields completed!"}),e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:"Your form is ready for export."})]}),Yp.map($=>e.jsx(OY,{section:$,formData:s,onFieldChange:r,filterMode:l,defaultOpen:!0,sectionRef:z=>{m.current[$.id]=z},showQcSidebar:h,onAddFieldRule:z=>E(z),orderId:i},$.id))]}),h&&e.jsx(_L,{open:h,onClose:()=>f(!1),findings:v,aiFindings:N,aiLoading:y,onRunAiReview:A,onJumpToField:D,onAutoFix:M,onCreateUserRule:B,creatingRule:j,userRulesCount:Array.isArray(C)?C.length:0,prefillFieldPath:O,onClearPrefill:()=>E(null)})]}),e.jsxs("div",{className:"px-5 py-3 border-t border-slate-200 bg-slate-50/50 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"text-xs text-slate-500",children:[e.jsxs("span",{className:"font-medium text-slate-700",children:[_.requiredFilled,"/",_.required]})," required fields complete"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(De,{variant:"outline",size:"sm",onClick:a,className:"h-8 text-xs","data-testid":"button-close-report-bottom",children:"Close"})})]})]})})}new Set(CI.FunctionalIssueType??[]);new Set(CI.DataSourceType??[]);const ZI=[{reportKey:"address",gridKey:"Address"},{reportKey:"site",gridKey:"LotSizeAreaMeasure"},{reportKey:"quality",gridKey:"OverallQualityRatingCode"},{reportKey:"condition",gridKey:"OverallConditionRatingCode"},{reportKey:"gla",gridKey:"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure"},{reportKey:"aboveGradeTotal",gridKey:"TotalRoomCount"},{reportKey:"functionalUtility",gridKey:"FunctionalIssueType"},{reportKey:"design",gridKey:"ArchitecturalDesignCategoryType",fallbackGridKeys:["StructuralDesignType"],fallbackReadOnly:!0},{reportKey:"pricePerSqFt",gridKey:"PricePerTotalStandardAboveGradeFinishedAreaAmount",fallbackGridKeys:["PricePerUnitOfMeasureTypeForTotalFinishedAreaOfAllLivingUnitsIncludingADUAmount"]},{reportKey:"netAdjustment",gridKey:"NetAdjustmentAmount",fallbackGridKeys:["SalePriceNetTotalAdjustmentAmount"]},{reportKey:"adjustedSalePrice",gridKey:"AdjustedPrice",fallbackGridKeys:["AdjustedSalesPriceAmount"]}],DY={listPrice:"FinalListPriceAmount",listingStatus:"ListingStatusType",daysOnMarket:"DaysOnMarketCount",attachedDetached:"AttachmentType",neighborhoodName:"NeighborhoodName",site:"LotSizeAreaMeasure",proximity:"ProximityToSubjectDistanceLinearMeasure",priorSalesOrTransfersIndicator:"PriorSalesOrTransfersIndicator",saleHistoryDataSource:"SaleHistoryDataSource",quality:"OverallQualityRatingCode",condition:"OverallConditionRatingCode",gla:"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure",design:"ArchitecturalDesignCategoryType",functionalUtility:"FunctionalIssueType",saleType:"SaleType",financing:"MortgageType",concessions:"TotalSalesConcessionAmount",designOtherDescription:"ArchitecturalDesignCategoryTypeOtherDescription",functionalUtilityOtherDescription:"FunctionalIssueTypeOtherDescription",heatingOtherDescription:"HeatingSystemTypeOtherDescription",coolingOtherDescription:"CoolingSystemTypeOtherDescription",garageCarportOtherDescription:"CarStorageTypeOtherDescription",saleTypeOtherDescription:"SaleTypeOtherDescription",financingOtherDescription:"MortgageTypeOtherDescription",leaseholdFeeSimpleOtherDescription:"PropertyEstateTypeOtherDescription",amenityType:"AmenityType",amenityTypeOtherDescription:"AmenityTypeOtherDescription",dataSource:"DataSourceType",dataSourceIdentifier:"DataSourceIdentifier",dataSourceOtherDescription:"DataSourceTypeOtherDescription",constructionMethod:"ConstructionMethodType",constructionMethodOtherDescription:"ConstructionMethodTypeOtherDescription",heatingFuel:"HeatingFuelType",heatingFuelOtherDescription:"HeatingFuelTypeOtherDescription",interiorQuality:"InteriorQualityRatingCode",interior
10Condition:"InteriorConditionRatingCode",exteriorQuality:"ExteriorQualityRatingCode",exteriorCondition:"ExteriorConditionRatingCode",garageAttachment:"CarStorageAttachmentType",garageArea:"CarStorageAreaMeasure",garageSurface:"ImprovedSurfaceMaterialType",garageSurfaceOtherDescription:"ImprovedSurfaceMaterialTypeOtherDescription",garageTenOrMore:"TenOrMoreParkingSpacesIndicator"};function kY(t){const a=DY[t];if(a)return a;const s=t.match(/^catalog_([A-Za-z0-9]+)_(?:auto|\d+)$/);if(s&&MY.has(s[1]))return s[1];const r=t.match(/^saleHistory(\d+)_([A-Za-z0-9]+)$/);return r?`SaleHistory${r[1]}_${r[2]}`:null}const MY=new Set(["BedroomCount","FullBathroomCount","HalfBathroomCount"]);function FY(t){if(t==null)return null;const a=String(t).trim();if(a==="")return null;if(/^none$/i.test(a))return{finished:0,unfinished:0};if(a==="0"||!a.includes("/"))return a==="0"?{finished:0,unfinished:0}:null;const s=a.split("/"),r=parseFloat(s[0].replace(/[^0-9.]/g,"")),n=parseFloat((s[1]??"").split(" ")[0].replace(/[^0-9.]/g,""));return!Number.isFinite(r)||!Number.isFinite(n)?null:{finished:n,unfinished:Math.max(0,r-n)}}const _Y=/^basementUnit([2-4])$/;function UY(t,a){if(t==="gla"){if(a==null)return[];const r=typeof a=="number"?a:parseFloat(String(a).replace(/[^0-9.]/g,""));return Number.isFinite(r)?[{gridKey:"UnitStandardAboveGradeFinishedAreaMeasure",value:String(r)}]:[]}const s=_Y.exec(t);if(t==="basement"||s){const r=FY(a);if(!r)return[];const n=s?`Unit${s[1]}_`:"";return[{gridKey:`${n}UnitStandardBelowGradeFinishedAreaMeasure`,value:String(r.finished)},{gridKey:`${n}UnitBelowGradeUnfinishedAreaMeasure`,value:String(r.unfinished)}]}return[]}function VY(t,a){if(t!=="financing")return[];const s=String(a??"").trim();return s?s==="Cash"?[{gridKey:"NoFinancingTransactionIndicator",value:"true"},{gridKey:"MortgageType",value:""}]:[{gridKey:"NoFinancingTransactionIndicator",value:"false"}]:[]}function $Y(t,a,s,r){const i=(s-t)*Math.PI/180,l=(r-a)*Math.PI/180,c=Math.sin(i/2)**2+Math.cos(t*Math.PI/180)*Math.cos(s*Math.PI/180)*Math.sin(l/2)**2;return 3958.8*2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))}function BY(t,a,s={}){const r=s.maxComps??Math.max(a.length,3),n=s.subjectCoords??null;let i=null;const l=(d,p)=>{if(p==null)return;const u=typeof p=="number"?String(p):String(p).trim();if(u==="")return;const m=(i??t)[d];(m==null?"":typeof m=="boolean"?m?"true":"":String(m).trim())===""&&(i===null&&(i={...t}),i[d]=u)},c=(d,p)=>{if(p==null)return;const u=typeof p=="number"?String(p):String(p).trim();u!==""&&(i===null&&(i={...t}),i[d]=u)};for(let d=0;d<r;d++){const p=a[d];if(!p)continue;const u=d+1,m=`salesComparison.Comp${u}_bridgeCompId`,h=String((i??t)[m]??""),f=p.compId??"",v=f!==""&&h!==f;f!==""&&(v||h==="")&&(i===null&&(i={...t}),i[m]=f);const S=v?c:l;if(l(Wo(u,"Address"),p.address),l(Wo(u,"SalePrice"),p.price),l(Wo(u,"SaleDate"),p.saleDate),l(Wo(u,"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure"),p.gla),l(Wo(u,"OverallQualityRatingCode"),p.quality),l(Wo(u,"OverallConditionRatingCode"),p.condition),n&&p.latitude!=null&&p.longitude!=null&&p.latitude!==0&&p.longitude!==0){const x=`${$Y(n.lat,n.lng,p.latitude,p.longitude).toFixed(2)} Miles`,y=JY(n.lat,n.lng,p.latitude,p.longitude);S(Wo(u,"Proximity"),x),S(Wo(u,"ProximityToSubjectDistanceLinearMeasure"),x),S(Wo(u,"LinearUnitOfMeasureType"),"Miles"),S(Wo(u,"ComparableToSubjectDirectionType"),y)}else if(p.distanceMiles!=null&&p.distanceMiles>0){const N=`${p.distanceMiles.toFixed(2)} Miles`;S(Wo(u,"Proximity"),N),S(Wo(u,"ProximityToSubjectDistanceLinearMeasure"),N),S(Wo(u,"LinearUnitOfMeasureType"),"Miles")}}return i??t}const zY=/^comps\[(\d+)\]\.(.+)$/;function qY(t){const a=zY.exec(t);return a?{compIndex:Number(a[1]),reportKey:a[2]}:null}function Wo(t,a){return`salesComparison.Comp${t}${a}`}function $v(t){return t==null?null:typeof t=="object"&&"value"in t&&Object.keys(t).some(a=>a==="value")?$v(t.value):typeof t=="boolean"||typeof t=="string"?t:typeof t=="number"?String(t):null}function kT(t){return t==null?!1:typeof t=="boolean"?t===!0:typeof t=="string"?t.trim()!=="":!1}function YY(t,a,s){const r=ZI.find(l=>l.reportKey===s);if(!r)return null;const n=a+1,i=[r.gridKey,...r.fallbackGridKeys??[]];for(const l of i){const c=t[Wo(n,l)],d=$v(c);if(kT(d))return d}return null}function GY(t,a){const s=a+1,r=$v(t[Wo(s,"Address")]);if(kT(r))return!0;const n=$v(t[Wo(s,"SalePrice")]);return!!kT(n)}function HY(t,a={}){const s=a.maxComps??3,r={...t},n=["salePrice","dateOfSale"];for(let i=0;i<s;i++){for(const c of n)delete r[`comps[${i}].${c}`];const l=GY(t,i);for(const c of ZI){const d=`comps[${i}].${c.reportKey}`;if(!l){delete r[d];continue}const p=YY(t,i,c.reportKey);if(p===null){delete r[d];continue}r[d]=p}}return r}
10function WY(t,a){if(!a)return null;const s=r=>{if(r==null)return null;const n=String(r).trim();return n===""?null:n};switch(t){case"basement":{const r=[],n=s(a.basementFinishedSf);n&&r.push(`${n}sf finished`);const i=s(a.basement);return i&&r.push(i),r.length?r.join(" / "):null}case"garageCarport":{const r=s(a.garageSpaces),n=s(a.garageType);return r&&n?`${r}-car ${n}`:r?`${r}-car`:n}case"heatingCooling":{const r=s(a.heating),n=s(a.cooling);return r&&n?`${r} / ${n}`:r??n??null}case"porchPatioDeck":return s(a.patioFeatures);case"actualAge":return s(a.yearBuilt);case"energyEfficient":return s(a.energyEfficientItems);case"saleOrFinancingConcessions":return s(a.salesConcessions);case"leaseholdFeeSimple":return s(a.propertyRights);case"dataSources":return s(a.dataSources);case"verificationSources":return s(a.verificationSources);default:return null}}const KY=["basement","garageCarport","heatingCooling","porchPatioDeck","actualAge","energyEfficient","saleOrFinancingConcessions","leaseholdFeeSimple","dataSources","verificationSources"];function QY(t,a,s={}){const r=s.maxComps??Math.max(a.length,3),n={...t};for(let i=0;i<r;i++){const l=a[i];for(const c of KY){const d=`comps[${i}].${c}`;if(!l){delete n[d];continue}const p=WY(c,l);if(p===null){delete n[d];continue}n[d]=p}}return n}function ZY(t){const a=qY(t);if(!a)return null;const s=ZI.find(l=>l.reportKey===a.reportKey);if(!s)return null;const r=a.compIndex+1,n=s.fallbackReadOnly?[]:s.fallbackGridKeys??[];return{gridPaths:[Wo(r,s.gridKey),...n.map(l=>Wo(r,l))],reportKey:a.reportKey,compIndex:a.compIndex}}function JY(t,a,s,r){const n=(r-a)*Math.PI/180,i=t*Math.PI/180,l=s*Math.PI/180,c=Math.cos(l)*Math.sin(n),d=Math.cos(i)*Math.sin(l)-Math.sin(i)*Math.cos(l)*Math.cos(n),p=(Math.atan2(c,d)*180/Math.PI+360)%360;return["North","NorthEast","East","SouthEast","South","SouthWest","West","NorthWest"][Math.round(p/45)%8]}function XY(t){return!t||t.source==="Default"&&!t.confirmed}function cj(t,a,s){let r=!1;const n={...t};for(const[i,l]of Object.entries(a)){if(l==null)continue;const c=typeof l=="string"?l:String(l);if(!c)continue;const d=n[i];XY(d)&&(d&&d.value===c&&d.confirmed===s.confirmed||(n[i]={value:c,source:"Default",confirmed:s.confirmed},r=!0))}return r?n:t}function e6(t,a,s,r={}){const n=s[t];if(n!==void 0)return{value:n,source:"Default",confirmed:!0};const i=r[t];return i!=null&&String(i)!==""?{value:typeof i=="string"?i:String(i),source:"Default",confirmed:!1}:a!==void 0?{value:a,source:"Default",confirmed:!1}:null}const t6=new Set(["property_basics","identity_rights","tax_assessment","zoning","site_characteristics","utilities","flood","scope"]),a6=new Map([["flood",new Set(["femaFloodZone","femaMapNumber","femaMapDate"])]]),s6=new Set(["property_basics","identity_rights","site_characteristics","quick_basics"]),r6=new Map([["property_basics",new Set(["propertyType","yearBuilt","occupancy","neighborhoodName","numUnits"])],["identity_rights",new Set(["county","parcelId"])],["site_characteristics",new Set(["parcelArea","lotDimensions"])]]),MT={quickView:{key:"quickView",label:"Property Quick View",strictnessRank:0,showUadChips:!1,suppressMissingGating:!0,sectionIds:s6,sectionFieldAllowLists:r6},eval:{key:"eval",label:"Eval Subject",strictnessRank:1,showUadChips:!1,suppressMissingGating:!0,sectionIds:t6,sectionFieldAllowLists:a6},urar26:{key:"urar26",label:"1004 / Legacy URAR",strictnessRank:2,showUadChips:!0,suppressMissingGating:!1,sectionIds:new Set(["property_basics","identity_rights","tax_assessment","zoning","highest_best_use","site_characteristics","utilities","offsite_improvements","hoa_pud","flood","environmental","scope"]),stubBanner:"This order uses the legacy 1004/URAR form. A dedicated UAD 2.6 field set is in development — currently showing UAD 3.6 fields as a placeholder."},urar36:{key:"urar36",label:"UAD 3.6 (RAUR / CR)",strictnessRank:3,showUadChips:!0,suppressMissingGating:!1,sectionIds:new Set(["property_basics","identity_rights","tax_assessment","zoning","highest_best_use","site_characteristics","utilities","offsite_improvements","hoa_pud","flood","environmental","scope"])}},n6=new Set(["form_1004","urar","urar26","1004"]);function i6(t){const a=t.productType?.toLowerCase()??"";return a&&(a.includes("1004")||a.includes("urar"))?!0:(t.addOns??[]).some(r=>n6.has(r))}function o6(t){if(nD(t))return"urar36";if(i6(t))return"urar26";const a=t.addOns??[];
10if(a.includes("eval")||t.appId?.toLowerCase().includes("eval")||t.appId==="modum-eval")return"eval";const s=new Set(["str","leasehold","cedar-ground-lease","cedar","solar","land-lease","land-lease-estately","solar-compare","insight-green","insight-solar"]),r=a.filter(d=>!s.has(d)),n=new Set(["vault","core","","analysis","modifier"]),i=(t.productType??"").toLowerCase(),l=!!i&&!n.has(i);return(r.length>0||l)&&typeof console<"u"&&console.warn("[subjectProfileRegistry] resolveSubjectProfile: unrecognized profile product signals — falling back to quickView.",{appId:t.appId,unknownAddOns:r,productType:t.productType}),"quickView"}function FT(t){return t.sectionIds?Cv.filter(a=>t.sectionIds.has(a.id)):Cv}function l6(t,a,s){const r=t.sectionFieldAllowLists?.get(a);return r?r.has(s):!0}function Zw(t){return t==null||typeof t=="string"&&t.trim()===""}function Jw(t,a){return{...t,value:a,source:"Zoneomics",isEdited:!1,alternatives:{...t.alternatives,zoneomics:a}}}function _T(t,a){if(!a)return t;const s=a.zoneCode?.trim()||"",r=a.zoneDescription?.trim()||a.zoneName?.trim()||"",n=!!s&&Zw(t.zoningClassification?.value),i=!!r&&Zw(t.zoningDescription?.value);return!n&&!i?t:{...t,zoningClassification:n?Jw(t.zoningClassification,s):t.zoningClassification,zoningDescription:i?Jw(t.zoningDescription,r):t.zoningDescription}}new Set(UL.map(t=>t.fieldName));const c6=[...Cv.flatMap(t=>t.fields),...tg.flatMap(t=>t.fields)];new Set(c6.flatMap(t=>t.schemaRequirementIds??[]));function d6(t,a){const s=parseFloat(String(t.value??""));if(isNaN(s)||s===0)return!1;const r=t.alternatives??{};return Object.values(r).every(n=>{const i=parseFloat(String(n??""));return isNaN(i)||Math.abs((i-s)/s)*100<=a})}const u6={strProductEnabled:"STR product",evalProductEnabled:"Eval product",salesContractEnabled:"Sales contract",condoIndicator:"Condo/Co-op"},iv=[{id:"property",label:"Property & Identity",sectionIds:["property_basics","identity_rights","tax_assessment","scope","quick_basics"]},{id:"zoning",label:"Zoning & Use",sectionIds:["zoning","highest_best_use"]},{id:"site",label:"Site, Utilities & Flood",sectionIds:["site_characteristics","utilities","offsite_improvements","flood"]},{id:"project",label:"Project & Environmental",sectionIds:["hoa_pud","environmental"]}],p6=new Set(["salesApproach","costApproach","incomeApproach"]),m6=(()=>{const t={};return iv.forEach(a=>a.sectionIds.forEach(s=>{t[s]=a.id})),t})();function h6(t,a){const s=t.triggerFieldIds??[t.triggerFieldId];for(const r of s)if(t.triggerCondition(a(r)))return r;return t.triggerFieldId}function f6({active:t,blockId:a,children:s}){const r=o.useRef(null);return e.jsx(I0,{initial:!1,children:t&&e.jsx(Kh.div,{ref:r,initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.18,ease:"easeOut"},style:{overflow:"hidden"},onAnimationComplete:n=>{if(n&&typeof n=="object"&&n.opacity===1){const i=r.current;i&&i.getBoundingClientRect().bottom>window.innerHeight&&i.scrollIntoView({behavior:"smooth",block:"nearest"})}},children:s},a)})}function g6(t,a){if(!a)return t;let s=!1;const r={...t};for(const[n,i]of Object.entries(a)){const l=t[n];if(!l){r[n]=i,s=!0;continue}if(l.value===i.value&&l.source===i.source&&l.confirmed===i.confirmed&&l.flaggedBad===i.flaggedBad)continue;l.confirmed||l.source==="User"||l.source==="Manual"||(r[n]=i,s=!0)}return s?r:t}function x6(t){return t?.flaggedBad&&(!t.value||t.value==="")?"needs_decision":null}function Xw(t,a,s,r){return s||a!=="Default"&&a!=="Derived"?!1:String(t??"")===r}function b6(t){if(!t)return"missing";const a=t.value;return a==null||a===""?"missing":hy(t)==="mismatch"?"mismatch":"matched"}function y6(t,a){return t.pendingInspection&&!a?.confirmed&&!a?.value?"pending_inspection":t.needsDecision?a?.value&&a.confirmed?"matched":"needs_decision":a?.value?"matched":"missing"}function S6(t,a,s){return a==="missing"?s?"needs_confirmation":"missing":a==="confirmed"?"matched":t}function eP({state:t,onClick:a,sourceCount:s}){const r={matched:{label:"Matched",cls:"bg-green-50 text-green-700 border-green-200",Icon:kr},mismatch:{label:"Mismatch",cls:"bg-amber-50 text-amber-700 border-amber-300 cursor-pointer hover:bg-amber-100",Icon:Ns},needs_decision:{label:"Needs decision",cls:"bg-slate-100 text-slate-600 border-slate-300",Icon:Xx},missing:{label:"Missing",cls:"bg-red-50 text-red-600 border-red-200",Icon:nf},needs_confirmation:{label:"Needs confirmation",cls:"bg-orange-50 text-orange-600 border-orange-200",Icon:Xx},pending_inspection:{label:"Pending inspection",cls:"bg-blue-50 text-blue-600 border-blue-200",Icon:Pu}},{label:n,cls:i,Icon:l}=r[t],c="inline-flex items-center gap-0.5 text-[10px] font-semibold px-1.5 py-0.5 rounded border";return a&&t==="mismatch"?e.jsxs("button",{type:"button",onClick:a,title:s&&s>1?`${s} sources disagree — click to compare and resolve`:"Sources disagree — click to compare and resolve",className:Q(c,i,"curs
10or-pointer"),"data-testid":"chip-mismatch",children:[e.jsx(l,{className:"w-2.5 h-2.5"}),n,s&&s>1?e.jsxs("span",{className:"tabular-nums",children:["· ",s]}):null,e.jsx(fo,{className:"w-2.5 h-2.5 -mr-0.5"})]}):e.jsxs("span",{className:Q(c,i),children:[e.jsx(l,{className:"w-2.5 h-2.5"}),n]})}const v6=5;function N6(t){return t.type==="select"&&!!t.selectOptions&&t.selectOptions.length===2&&t.selectOptions.includes("Yes")&&t.selectOptions.includes("No")}function A6(t){return t.type==="select"&&!!t.selectOptions&&t.selectOptions.length>0&&t.selectOptions.length<=v6}function j6({def:t,state:a,bucket:s,value:r,source:n,personalDefault:i,onConfirm:l,onChange:c,onFlag:d,onMismatchClick:p,conflictSourceCount:u,onTogglePersonalDefault:m}){const[h,f]=o.useState(r??"");o.useEffect(()=>{f(r??"")},[r]);const v=o.useRef(!1),{inspecting:S}=fc(),N=S6(a,s,r!=null&&r!==""),x=N6(t),y=A6(t),b=!!r&&i===r;if(y)return e.jsxs("div",{className:Q("group flex items-center gap-2 px-3 py-[6px] border-b border-slate-100 last:border-0 hover:bg-slate-50/60 transition-colors",a==="mismatch"&&"bg-amber-50/40 hover:bg-amber-50/60",a==="missing"&&"bg-red-50/30"),"data-testid":`field-row-${t.id}`,children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400 w-[120px] shrink-0 truncate",children:t.label}),S&&(t.propertyDataKey?e.jsx(Fs,{section:"propertyData",fieldName:t.propertyDataKey}):e.jsx(Fs,{section:"subjectSiteLocalFields",fieldName:t.id})),e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-1.5 flex-wrap",children:[e.jsx("div",{className:"flex items-center gap-1","data-testid":`inline-buttons-${t.id}`,children:t.selectOptions.map(T=>{const O=r===T,E=x?T==="Yes"?"bg-green-600 text-white border-green-700":"bg-slate-600 text-white border-slate-700":"bg-blue-600 text-white border-blue-700";return e.jsx("button",{onClick:()=>c(T,"User"),className:Q("px-2.5 py-0.5 text-[11px] font-semibold rounded border transition-colors",O?E:"bg-white text-slate-600 border-slate-300 hover:bg-slate-50"),"data-testid":`btn-opt-${t.id}-${T.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,children:T},T)})}),n==="Default"&&r&&b?e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-semibold rounded border bg-amber-50 text-amber-600 border-amber-200",title:`"${r}" is your starred default for this field`,"data-testid":`badge-starred-default-${t.id}`,children:[e.jsx(Lo,{className:"w-2.5 h-2.5 fill-amber-500 text-amber-500"}),"MY DEFAULT"]}):n&&r&&(n==="Inspection"?R6.has(t.id):!0)&&e.jsx(pd,{source:n,onClick:(n==="Default"||n==="Derived")&&r?l:void 0,clickTitle:(n==="Default"||n==="Derived")&&r?`Confirm "${r}" — keeps source as ${n==="Default"?"DEFAULT":"DERIVED"}`:void 0}),N!=="matched"&&e.jsx(eP,{state:N,onClick:N==="mismatch"?p:void 0,sourceCount:u})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[r&&m&&e.jsx("button",{onClick:()=>m(r),title:b?`"${r}" is your default — click to remove`:`Star "${r}" as your default for this field`,className:Q("p-1 rounded border border-transparent transition-colors",b?"text-amber-500 hover:bg-amber-50":"text-slate-300 hover:text-amber-500 hover:bg-amber-50 opacity-0 group-hover:opacity-100"),"data-testid":`btn-star-default-${t.id}`,children:e.jsx(Lo,{className:Q("w-3.5 h-3.5",b&&"fill-amber-500")})}),e.jsx("button",{onClick:d,title:"Wrong / Missing",className:"flex items-center gap-0.5 text-[10px] text-red-600 hover:bg-red-50 px-1.5 py-0.5 rounded border border-transparent hover:border-red-200 transition-colors opacity-0 group-hover:opacity-100","data-testid":`btn-flag-${t.id}`,children:e.jsx(YR,{className:"w-3 h-3"})})]})]});const j=t.type==="select"&&!!t.selectOptions;return e.jsxs("div",{className:Q("group flex items-center gap-2 px-3 py-[6px] border-b border-slate-100 last:border-0 hover:bg-slate-50/60 transition-colors",a==="mismatch"&&"bg-amber-50/40 hover:bg-amber-50/60",a==="missing"&&"bg-red-50/30"),"data-testid":`field-row-${t.id}`,children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400 w-[120px] shrink-0 truncate",children:t.label}),S&&(t.propertyDataKey?e.jsx(Fs,{section:"propertyData",fieldName:t.propertyDataKey}):e.jsx(Fs,{section:"subjectSiteLocalFields",fieldName:t.id})),e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-1.5 flex-wrap",children:[j?e.jsxs("select",{value:r??"",onChange:T=>{T.target.value&&c(T.target.value,"User")},className:"h-7 min-w-0 max-w-[260px] text-[12px] px-1.5 border border-slate-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-400 bg-white","data-testid":`select-edit-${t.id}`,children:[e.jsx("option",{value:"",children:"— select —"}),t.selectOptions.map(T=>e.jsx("option",{value:T,children:T},T))]}):e.jsx("input",{value:h,onChange:T=>{f(T.target.value),v.current=!0},onBlur:()=>{const T=v.current;v.current=!1,T&&c(h,"User")},onKeyDown:T=>{T.key==="Enter"&&T.target.blur(),T.key==="Escape"&&(f(r??""),v.current=!1,T.target.blur())},placeholder:"—",className:"h-7 min-w-0 max-w-[260px] text-[12px] px-1.5 border border-slate-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-400 bg-white","data-testid":`input-edit-${t.id}`}),n==="Default"&&r&&b?e.jsxs("span",{className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-semibold rounded border bg-amber-50 text-amber-600 border-amber-200",title:`"${r}" is your starred default for this field`,"data-testid":`badge-starred-default-${t.id}`,children:[e.jsx(Lo,{className:"w-2.5 h-2.5 fill-amber-500 text-amber-500"}),"MY DEFAULT"]}):n&&r&&e.jsx(pd,{source:n,onClick:(n==="Default"||n==="Derived")&&r?l:void 0,clickTitle:(n==="Default"||n==="Derived")&&r?`
10Confirm "${r}" — keeps source as ${n==="Default"?"DEFAULT":"DERIVED"}`:void 0}),N!=="matched"&&e.jsx(eP,{state:N,onClick:N==="mismatch"?p:void 0,sourceCount:u})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[r&&m&&e.jsx("button",{onClick:()=>m(r),title:b?`"${r}" is your default — click to remove`:`Star "${r}" as your default for this field`,className:Q("p-1 rounded border border-transparent transition-colors",b?"text-amber-500 hover:bg-amber-50":"text-slate-300 hover:text-amber-500 hover:bg-amber-50 opacity-0 group-hover:opacity-100"),"data-testid":`btn-star-default-${t.id}`,children:e.jsx(Lo,{className:Q("w-3.5 h-3.5",b&&"fill-amber-500")})}),e.jsx("button",{onClick:d,title:"Wrong / Missing",className:"flex items-center gap-0.5 text-[10px] text-red-600 hover:bg-red-50 px-1.5 py-0.5 rounded border border-transparent hover:border-red-200 transition-colors opacity-0 group-hover:opacity-100","data-testid":`btn-flag-${t.id}`,children:e.jsx(YR,{className:"w-3 h-3"})})]})]})}function T6({label:t,stats:a}){return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[e.jsx(kr,{className:"w-3.5 h-3.5 text-green-500 shrink-0"}),e.jsx("span",{className:"text-[11px] font-semibold text-slate-600 uppercase tracking-wide",children:t}),e.jsxs("span",{className:"text-[10px] text-slate-400 ml-auto",children:[a.total," fields · all resolved"]})]})}const dj=["Measured on inspection","Public record outdated","MLS error","Other"];function I6({chooser:t,onClose:a,onUse:s,onEnterOwn:r,defaultShowOwn:n,currentDefault:i,onSetDefault:l}){const[c,d]=o.useState(""),[p,u]=o.useState(dj[0]),[m,h]=o.useState(!!n),[f,v]=o.useState(!1);if(o.useEffect(()=>{t&&(h(!!n),d(""),u(dj[0]),v(!1))},[t]),!t)return null;const S=t.sources.length>0,N=t.sources.some(x=>!!x.value);return e.jsx(xi,{open:!0,onOpenChange:x=>{x||a()},children:e.jsxs(bi,{className:"sm:max-w-lg p-0 gap-0 rounded-none border border-[#d8d0c6] bg-[#faf8f4] shadow-2xl overflow-hidden [font-family:'DM_Sans',sans-serif] [&>button]:text-white/70 [&>button:hover]:text-white [&>button]:top-3.5 [&>button]:right-3.5",overlayClassName:"bg-[#08243b]/50 backdrop-blur-[2px]",children:[e.jsxs($i,{className:"bg-[#1b3a5c] px-5 py-4 space-y-1 text-left",children:[e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.12em] text-[#f5c17a]",children:n?"Flag & Correct":"Fix a conflict"}),e.jsx(si,{className:"text-white text-[17px] leading-tight [font-family:'Space_Grotesk','DM_Sans',sans-serif] tracking-wide",children:t.label}),e.jsx(pl,{className:"text-[#c9d6e0] text-[12px] leading-snug",children:n?"Type the correct value below. You’ll pick a reason, and the change is saved to your audit trail.":"Your data sources report different values for this field. Pick the one that’s correct — it becomes the value in y
10our report, and the choice is saved to your audit trail."})]}),e.jsxs("div",{className:"space-y-2 px-5 py-4",children:[!m&&t.sources.map(x=>{const y=!!x.value&&i===x.value;return e.jsxs("div",{className:"flex items-center justify-between p-2.5 border border-[#d8d0c6] bg-white hover:border-[#1b3a5c] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(pd,{source:x.source}),e.jsx("span",{className:"text-[13px] font-medium text-[#26364b] truncate",children:x.value||"—"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[l&&!!x.value&&e.jsx("button",{type:"button",onClick:()=>l(x.value),title:y?`"${x.value}" is your default — click to remove`:`Set "${x.value}" as your default for future orders`,className:Q("p-1.5 border transition-colors",y?"text-[#e0b25b] border-[#e0b25b] bg-[#fdf6e8]":"text-[#c9c0b4] border-transparent hover:text-[#e0b25b] hover:bg-[#fdf6e8]"),"data-testid":`btn-set-default-${x.source.toLowerCase().replace(/\s+/g,"-")}`,children:e.jsx(Lo,{className:Q("w-3.5 h-3.5",y&&"fill-[#e0b25b]")})}),e.jsx(De,{size:"sm",className:"text-[11px] h-7 rounded-none bg-[#f16623] hover:bg-[#d5561a] text-white font-bold border-0",onClick:()=>{s(x.value,x.source),a()},"data-testid":`btn-use-${x.source.toLowerCase().replace(/\s+/g,"-")}`,children:"Use this"})]})]},x.source)}),!m&&!S&&e.jsx("div",{className:"p-3 border border-dashed border-[#c9c0b4] bg-[#f3eee7] text-center","data-testid":"text-no-sources",children:e.jsx("p",{className:"text-[12px] text-[#64717a]",children:"No other sources found for this field — enter your own value below."})}),!m&&l&&N&&e.jsxs("p",{className:"text-[10px] text-[#8b8577] px-1 pt-0.5 flex items-center gap-1",children:[e.jsx(Lo,{className:"w-2.5 h-2.5 text-[#e0b25b]"})," Star a source to reuse it automatically on future orders.",e.jsx("a",{href:"/profile#wizard-defaults",target:"_blank",rel:"noreferrer",className:"underline hover:text-[#1b3a5c]","data-testid":"link-manage-my-defaults",children:"Manage my defaults"})]}),!m&&(S?e.jsx("button",{onClick:()=>h(!0),className:"w-full text-[11px] font-bold uppercase tracking-wide text-[#1b3a5c] hover:text-[#f16623] py-1.5 border border-[#d8d0c6] bg-white hover:border-[#f16623] transition-colors","data-testid":"btn-enter-own-value",children:"+ Enter my own value"}):e.jsx(De,{size:"sm",className:"w-full text-[11px] h-8 rounded-none bg-[#f16623] hover:bg-[#d5561a] text-white font-bold",onClick:()=>h(!0),"data-testid":"btn-enter-own-value",children:"Enter my own value"})),m&&e.jsxs("div",{className:"p-3 border border-[#d8d0c6] bg-[#f3eee7] space-y-2",children:[e.jsx("label",{className:"block text-[10px] font-bold uppercase tracking-wide text-[#64717a]",children:"Correct value"}),e.jsx("input",{autoFocus:!0,value:c,onChange:x=>d(x.target.value),placeholder:"Enter correct value...",className:"w-full text-[12px] px-2 py-1.5 border border-[#d9d1c8] bg-white focus:outline-none focus:border-[#f16623] focus:ring-2 focus:ring-[#f16623]/15","data-testid":"input-own-value"}),e.jsx("label",{className:"block text-[10px] font-bold uppercase tracking-wide text-[#64717a] pt-1",children:"Why are you changing it?"}),e.jsx("select",{value:p,onChange:x=>u(x.target.value),className:"w-full text-[11px] px-2 py-1.5 border border-[#d9d1c8] bg-white focus:outline-none focus:border-[#f16623]","data-testid":"select-override-reason",children:dj.map(x=>e.jsx("option",{children:x},x))}),l&&e.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-[#64717a] cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:x=>v(x.target.checked),className:"accent-[#f16623]","data-testid":"checkbox-own-as-default"}),"Set as my default for future orders"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(De,{size:"sm",className:"text-[11px] h-7 flex-1 rounded-none bg-[#f16623] hover:bg-[#d5561a] text-white font-bold",onClick:()=>{r(c,p),f&&l&&l(c),a()},disabled:!c.trim(),children:"Save this value"}),!n&&e.jsx(De,{size:"sm",variant:"outline",className:"text-[11px] h-7 rounded-none border-[#d8d0c6] text-[#1b3a5c] bg-white hover:bg-[#f3eee7]",onClick:()=>h(!1),children:"Back"})]})]})]})]})})}function tP(t){return JSON.parse(JSON.stringify(t))}function C6(t){let a=0,s=0;for(const r of Object.keys(t)){const n=t[r];
10if(!n||typeof n!="object"||!("value"in n))continue;const i=n.alternatives?.inspection;i!=null&&i!==""&&(a++,hy(n)==="mismatch"&&s++)}return{updated:a,mismatch:s}}const zf=[...Cv.flatMap(t=>t.fields),...tg.flatMap(t=>t.fields)],R6=new Set(["propertyType","attachmentType","numUnits","aduIndicator","numParcels","estateType","allRightsAppraised","location","topography","viewType"]);function E6({data:t,setData:a,address:s="",occupancy:r,setOccupancy:n,subjectAddress:i,prefetchedZoningData:l,prefetchedZoningScreenshot:c,prefetchedZoningLoading:d,prefetchedZoningError:p,onRetryZoning:u,femaPanelLookupStatus:m,femaRefreshing:h,onRefreshFema:f,inspectionUpdatedAt:v,inspectionCaptured:S=!1,appId:N,hasSalesContract:x=!1,overrideLog:y=[],onOverrideLogged:b,persistedLocalFields:j,onLocalFieldsChange:T,onResetOverrideLog:O,profile:E,orderId:R,enableUad36:G=!1,marketLocationType:U,inspectionSiteData:C}){const{inspecting:F}=fc(),A=MT[E??"urar36"],M=o.useMemo(()=>{const Te=FT(A);return G?Te.map(at=>at.id==="scope"?{...at,fields:at.fields.filter(yt=>!p6.has(yt.id))}:at):Te},[E,G]),B=o.useCallback((Te,at)=>l6(A,Te,at),[E]),{preferences:oe,isLoading:ae}=_I(),[D,_]=o.useState("all"),[$,z]=o.useState("property"),[V,le]=o.useState(!1),W="wizard_firm_field_defaults",[me,Z]=o.useState($E),pe=o.useCallback((Te,at)=>{const yt={...me};yt[Te]===at?delete yt[Te]:yt[Te]=at,Z(yt),p$(yt)},[me]);o.useEffect(()=>{const Te=at=>{const yt=at.detail;yt?.map&&(Z(yt.map),yt.applyToOpenStep&&sa(nt=>cj(nt,yt.map,{confirmed:!0})))};return window.addEventListener(BE,Te),()=>window.removeEventListener(BE,Te)},[]),o.useEffect(()=>{let Te=!1;return(async()=>{try{const at=m$(),yt=await fetch("/api/v2/user-ui-preferences",{credentials:"include"});if(!yt.ok||Te)return;const nt=await yt.json().catch(()=>null),Wt=h$(nt);if(Te||Wt===null)return;const ts=f$(Wt,at);if(Te||ts===null)return;Z(ts),sa(gs=>cj(gs,ts,{confirmed:!0}))}catch{}})(),()=>{Te=!0}},[]),o.useEffect(()=>{let Te=!1;return(async()=>{try{const at=await fetch("/api/v2/company-ui-preferences",{credentials:"include"});if(!at.ok||Te)return;const nt=(await at.json().catch(()=>null))?.preferences?.[W];if(Te||!nt||typeof nt!="object"||Array.isArray(nt))return;const Wt={};for(const[ts,gs]of Object.entries(nt))gs==null||gs===""||(Wt[ts]=typeof gs=="string"?gs:String(gs));sa(ts=>cj(ts,Wt,{confirmed:!1}))}catch{}})(),()=>{Te=!0}},[]);const[se,fe]=o.useState(()=>{const Te={},at=$E();for(const nt of zf){if(j?.[nt.id])continue;const Wt=e6(nt.id,nt.defaultValue,at);Wt&&(Te[nt.id]=Wt)}const yt=Zq(j,t,zf,S);return{...Te,...yt}});o.useEffect(()=>{fe(Te=>g6(Te,j))},[j]),o.useEffect(()=>{U&&sa(Te=>Te.location?.value?Te:{...Te,location:{value:U,source:"Market",confirmed:!1}})},[U]),o.useEffect(()=>{const{topography:Te,viewType:at}=C??{};!Te&&!at||sa(yt=>{const nt={...yt};return Te&&!yt.topography?.value&&(nt.topography={value:Te,source:"Inspection",confirmed:!1}),at&&!yt.viewType?.value&&(nt.viewType={value:at,source:"Inspection",confirmed:!1}),nt})},[C?.topography,C?.viewType]);const[ue,be]=o.useState(new Set(["property_basics","identity_rights","zoning","flood"])),[H,ye]=o.useState(null),[de,ge]=o.useState(!1),[Be,He]=o.useState(!1),[Ie,ce]=o.useState("property_basics"),[Pe,We]=o.useState(l||null),[Re,ne]=o.useState(!1),[Me,lt]=o.useState(),[Tt,je]=o.useState(c||null),[Le,ut]=o.useState(!1),[st,Xt]=o.useState(!1),[ua,Oa]=o.useState(i),Xa=o.useRef(null),[qa]=o.useState(()=>tP(t)),os=o.useRef(t);os.current=t;const ya=o.useRef(!1),At=o.useRef(!1);o.useEffect(()=>{i!==ua&&(Oa(i),We(null),je(null),lt(void 0))},[i,ua]),o.useEffect(()=>{l&&!Pe&&We(l)},[l,Pe]),o.useEffect(()=>{c&&je(c)},[c]);const Fe=Tt?.success&&(Tt.imageUrl||Tt.imageBase64),Oe=!Fe&&(Le||!!d),rt=Re||!Pe&&!!d,$t=!!(Me||p);o.useEffect(()=>{const Te=Pe||l;Te&&a(at=>_T(at,Te))},[Pe,l,a]),o.useEffect(()=>{if(!i)return;if(l){ne(!1),ut(!1);return}if(Xa.current===i)return;Xa.current=i;let Te=!1;return ne(!0),ut(!0),lt(void 0),(async()=>{try{const at=await FI(i);if(Te)return;at.success&&at.data?(We(at.data),a(yt=>_T(yt,at.data))):lt(at.error||"Failed to fetch zoning")}catch(at){Te||lt(at instanceof Error?at.message:"Unknown error")}finally{Te||ne(!1)}try{const at=await hT(i);!Te&&at.success&&je(at)}catch{Te||console.warn("zoning screenshot failed")}finally{Te||ut(!1)}})(),()=>{Te=!0}},[i,l,a]),o.useEffect(()=>{At.current||!f||t.femaMapNumber?.value&&t.femaMapDate?.value||m==="provider_error"&&(At.current=!0,f())},[m,t.femaMapNumber?.value,t.femaMapDate?.value,f]),o.useEffect(()=>{if(ae||ya.current)return;if(Object.keys(oe).length===0){ya.current=!0;return}const Te=["neighborhoodName","pinNumber","legalDescription","taxYear","taxes","yearBuilt","hoaFees","hoaFeeFrequency","pud","zoningClassification","zoningDescription","zoningCompliance","highestBestUse"];let at=!1,yt={...os.current};for(const nt of Te){const Wt=oe[nt];if(!Wt)continue;const ts=yt[nt];if(!ts||ts.isEdited)continue;const Va=PT(ts).find(Mr=>Mr.source===Wt);Va&&Va.value!==null&&Va.value!==void 0&&Va.value!==""&&String(ts.value)!==String(Va.value)&&(yt={...yt,[nt]:{...ts,value:Va.value,source:Wt,isEdited:!1,isConfirmed:!1}},at=!0)}ya.current=!0,at&&a(yt)},[ae,oe,a]);const na=o.useMemo(()=>ny(t,S),[t,S]),zt=o.useCallback(Te=>na[Te],[na]),Ua=o.useCallback(Te=>{const at=se[Te.id],yt=x6(at);if(yt!==null)return yt;const nt=!!(at?.confirmed&&at.value!==null&&at.value!=="");if(Te.propertyDataKey){const Wt=zt(Te.propertyDataKey),ts=Wt?.alternatives,gs=Wt?.value!==null&&Wt?.value!==void 0&&Wt?.value!=="";if(nt&&v){const Mr=ts?.inspection??ts?.Inspection,xs=Mr!=null?String(Mr):null;if(xs!==null&&xs!==""&&xs!==at.value)return"mismatch"}if(Te.needsDecision)return nt?"matched":"needs_decision";if(nt)return"matched";
10if(Te.pendingInspection&&!gs)return"pending_inspection";const Va=b6(Wt);return Va==="mismatch"&&Wt&&Te.misMatchTolerancePct!==void 0&&d6(Wt,Te.misMatchTolerancePct)?"matched":Va}return nt?"matched":y6(Te,at)},[zt,se,v]),Ce=o.useCallback(Te=>{const at=se[Te.id],yt=at?.source==="Inspection"&&S;if(at&&(at.source==="User"||yt)&&at.value!==null&&at.value!=="")return at.value;if(Te.propertyDataKey){const nt=zt(Te.propertyDataKey);if(nt&&nt.value!==null&&nt.value!==void 0&&nt.value!=="")return String(nt.value)}return at?.value??null},[zt,se,S]),St=o.useCallback(Te=>{const at=se[Te.id],yt=at?.source==="Inspection"&&S;if(at&&(at.source==="User"||yt)&&at.value!==null&&at.value!=="")return at.source;if(Te.propertyDataKey){const nt=zt(Te.propertyDataKey);if(nt&&nt.value!==null&&nt.value!==void 0&&nt.value!==""&&nt.source)return String(nt.source)}return at?.source?at.source:Te.defaultValue!==void 0?"Default":"Derived"},[zt,se,S]),vt=o.useCallback(Te=>{if(!Te.propertyDataKey)return[];const at=zt(Te.propertyDataKey);return at?PT(at).filter(yt=>yt.value!==null&&yt.value!==void 0).map(yt=>({source:yt.source,value:String(yt.value)})):[]},[zt]),Ve=o.useCallback(Te=>{const at=Ce(Te);return dD({state:Ua(Te),hasValue:at!==null&&at!=="",source:St(Te),confirmed:!!se[Te.id]?.confirmed},{prefilledCountsAsDone:!0})},[Ua,Ce,St,se]),sa=o.useCallback(Te=>{fe(Te)},[]),tt=o.useRef(!1);o.useEffect(()=>{if(!tt.current){tt.current=!0;return}T?.(se)},[se]);const it=o.useCallback(Te=>{b?.(Te)},[b]),Je=o.useCallback(Te=>{const at=Ce(Te);if(!at)return;if(Te.propertyDataKey){const nt=zt(Te.propertyDataKey);nt&&a(Wt=>({...Wt,[Te.propertyDataKey]:{...nt,isConfirmed:!0}}))}const yt=St(Te)??"Derived";sa(nt=>({...nt,[Te.id]:{...nt[Te.id]||{source:yt,value:at},value:at,confirmed:!0}}))},[Ce,St,zt,a,sa]),ht=o.useRef({}),Kt=o.useCallback((Te,at,yt,nt="Manual edit")=>{const Wt=Ce(Te)??"",ts=St(Te),gs=yt||"User",Va=nt==="Manual edit"&&gs==="User"?ts?`User edit (was ${ts}${Wt?`: ${Wt}`:""})`:Wt?`User edit (was "${Wt}")`:"User edit (was system default)":nt,Mr={fieldId:Te.id,label:Te.label,oldValue:Wt,newValue:at,source:gs,reason:Va,timestamp:new Date().toISOString()};if(it(Mr),Te.propertyDataKey){const xs=zt(Te.propertyDataKey);xs&&a(Sn=>({...Sn,[Te.propertyDataKey]:{...xs,value:at,source:gs,isEdited:!0,isConfirmed:!0}}))}if(Te.id==="propertyType"){const xs=ht.current,Sn=os.current;if(xs.numUnits&&at!=="2-4 Unit"){const ds=Sn.numUnits;if(ds&&Xw(ds.value,ds.source,ds.isEdited,"2")){const Zt=xs.numUnits;a(Rs=>({...Rs,numUnits:{...Rs.numUnits,value:Zt.sfValue,source:Zt.sfSource,isEdited:Zt.sfIsEdited,isConfirmed:Zt.sfIsConfirmed}}))}delete xs.numUnits}if(xs.pud&&at!=="PUD"){const ds=Sn.pud;if(ds&&Xw(ds.value,ds.source,ds.isEdited,"Yes")){const Zt=xs.pud;a(Rs=>({...Rs,pud:{...Rs.pud,value:Zt.sfValue,source:Zt.sfSource,isEdited:Zt.sfIsEdited,isConfirmed:Zt.sfIsConfirmed}}))}delete xs.pud}if(at==="2-4 Unit"){const ds=Sn.numUnits,Zt=!ds?.value||String(ds.value)==="1"||String(ds.value)==="0";ds&&Zt&&!ds.isEdited&&(xs.numUnits={sfValue:ds.value,sfSource:ds.source??"Derived",sfIsEdited:!!ds.isEdited,sfIsConfirmed:!!ds.isConfirmed},a(Rs=>({...Rs,numUnits:{...Rs.numUnits,value:2,source:"Default",isEdited:!1,isConfirmed:!1}})))}else if(at==="PUD"){const ds=Sn.pud,Zt=!ds?.value||ds.value==="No";ds&&Zt&&!ds.isEdited&&(xs.pud={sfValue:ds.value,sfSource:ds.source??"Derived",sfIsEdited:!!ds.isEdited,sfIsConfirmed:!!ds.isConfirmed},a(Rs=>({...Rs,pud:{...Rs.pud,value:"Yes",source:"Default",isEdited:!1,isConfirmed:!1}})))}}sa(xs=>({...xs,[Te.id]:{value:at,source:gs,confirmed:!0,flaggedBad:!1}}))},[Ce,St,zt,it,a,sa,se]),Sa=o.useCallback(Te=>{const at=Ce(Te),yt=St(Te);at!==null&&at!==""&&it({fieldId:Te.id,label:Te.label,oldValue:at,newValue:"",source:yt??"Unknown",reason:"Flagged as wrong/missing by appraiser",timestamp:new Date().toISOString()}),sa(Wt=>({...Wt,[Te.id]:{...Wt[Te.id]||{value:null,source:"Derived",confirmed:!1},flaggedBad:!0}}));const nt=vt(Te);ye({fieldId:Te.id,label:Te.label,currentValue:at??"",sources:nt,forceOwn:!0})},[vt,Ce,St,it,sa]),Qt=o.useCallback(Te=>{if(Te==="strProductEnabled")return N==="str-vault"||N==="insight-str"||N==="str-compare"||N==="solar-compare";if(Te==="evalProductEnabled")return!!(N?.toLowerCase().includes("eval")||N==="modum-eval");if(Te==="salesContractEnabled")return x;const at=zf.find(yt=>
10yt.id===Te);return at&&at.propertyDataKey?zt(at.propertyDataKey)?.value??null:se[Te]?.value??null},[N,x,zt,se]),ea=o.useCallback(Te=>(Te.triggerFieldIds??[Te.triggerFieldId]).some(yt=>Te.triggerCondition(Qt(yt))),[Qt]),tr=o.useCallback(Te=>{const at=Te.triggerFieldIds??[Te.triggerFieldId];for(const yt of at){const nt=Qt(yt);if(!Te.triggerCondition(nt))continue;const Wt=zf.find(ts=>ts.id===yt);if(Wt){const ts=typeof nt=="boolean"?nt?"Yes":"No":String(nt??"");return{label:Wt.label,value:ts}}return{label:u6[yt]??yt,value:typeof nt=="boolean"?"enabled":String(nt??"")}}return null},[Qt]),ir=o.useCallback(Te=>{const at=A.sectionFieldAllowLists?.get(Te.id),yt=tg.filter(xs=>xs.parentSectionId!==Te.id||at&&!(xs.triggerFieldIds??[xs.triggerFieldId]).some(ds=>at.has(ds))?!1:ea(xs)),Wt=[...at?Te.fields.filter(xs=>at.has(xs.id)):Te.fields,...yt.flatMap(xs=>xs.fields)],ts={total:Wt.length,matched:0,mismatch:0,missing:0,needsDecision:0};for(const xs of Wt){const Sn=Ve(xs);Sn==="confirmed"?ts.matched++:Sn==="conflicts"?ts.mismatch++:Sn==="missing"&&ts.missing++}const gs=Wt.length>0&&ts.matched===Wt.length,Va=ts.mismatch>0||!A.suppressMissingGating&&ts.missing>0,Mr=ts.mismatch>0;return{stats:ts,isResolved:gs,hasAttention:Va,hasConflict:Mr,activeBlocks:yt}},[Ve,ea,E]),zs=o.useMemo(()=>{const Te=[];for(const at of M){const yt=A.sectionFieldAllowLists?.get(at.id),nt=yt?at.fields.filter(Wt=>yt.has(Wt.id)):at.fields;Te.push(...nt);for(const Wt of tg)Wt.parentSectionId===at.id&&(yt&&!(Wt.triggerFieldIds??[Wt.triggerFieldId]).some(gs=>yt.has(gs))||ea(Wt)&&Te.push(...Wt.fields))}return Te},[M,ea,E]),pr=o.useMemo(()=>{const Te={missing:0,conflicts:0,unconfirmed:0,confirmed:0};for(const at of zs)Te[Ve(at)]++;return Te},[zs,Ve]),$e=pr.missing+pr.conflicts+pr.unconfirmed+pr.confirmed,Ot=o.useCallback(()=>{for(const Te of zs)Ve(Te)==="unconfirmed"&&Je(Te)},[zs,Ve,Je]),_e=o.useMemo(()=>v?C6(t):null,[v,t]),ma=o.useCallback(Te=>{if(D==="all")return!0;const at=A.sectionFieldAllowLists?.get(Te.id),yt=at?Te.fields.filter(ts=>at.has(ts.id)):Te.fields,nt=tg.filter(ts=>ts.parentSectionId!==Te.id||at&&!(ts.triggerFieldIds??[ts.triggerFieldId]).some(Va=>at.has(Va))?!1:ea(ts)),Wt=[...yt,...nt.flatMap(ts=>ts.fields)];return D==="inspection"?Wt.some(ts=>{if(!ts.propertyDataKey)return!1;const gs=t[ts.propertyDataKey],Va=gs?.alternatives?.inspection??gs?.alternatives?.Inspection;return Va!=null&&Va!==""}):Wt.some(ts=>Ve(ts)===D)},[D,ea,t,Ve,E]),pt=Te=>{be(at=>{const yt=new Set(at);return yt.has(Te)?yt.delete(Te):yt.add(Te),yt})},re=Te=>{const{isResolved:at}=ir(Te);return!(at&&!ue.has(Te.id))},qe=o.useCallback((Te,at)=>{const yt=Ua(Te);if(D==="inspection"){if(!at){if(!Te.propertyDataKey)return null;const gs=t[Te.propertyDataKey],Va=gs?.alternatives?.inspection??gs?.alternatives?.Inspection;if(Va==null||Va==="")return null}}else if(D!=="all"&&Ve(Te)!==D)return null;if(Te.showWhen&&!Te.showWhen(gs=>{const Va=zf.find(Mr=>Mr.id===gs);return Va?Ce(Va):null}))return null;const nt=Ce(Te),Wt=St(Te),ts=vt(Te);return e.jsx(j6,{def:Te,state:yt,bucket:Ve(Te),value:nt,source:Wt,personalDefault:me[Te.id]??null,onConfirm:()=>Je(Te),onChange:(gs,Va)=>Kt(Te,gs,Va),onFlag:()=>Sa(Te),onMismatchClick:()=>ye({fieldId:Te.id,label:Te.label,currentValue:nt??"",sources:ts}),conflictSourceCount:ts.length,onTogglePersonalDefault:gs=>pe(Te.id,gs)},`${at??""}-${Te.id}`)},[D,t,Ua,Ve,Ce,St,vt,Je,Kt,Sa,me,pe,se]),Ze=o.useCallback((Te,at)=>{const yt=tr(Te);return e.jsxs("div",{className:"ml-2 mr-1 mb-2 rounded-lg border border-blue-200 bg-blue-50/30 overflow-hidden","data-testid":`block-${Te.id}`,children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 px-3 py-1.5 bg-blue-50/60 border-b border-blue-100",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-700 uppercase tracking-wide",children:Te.label}),yt&&e.jsxs("span",{className:"text-[10px] font-normal normal-case tracking-normal text-blue-500/80","data-testid":`block-reason-${Te.id}`,children:["Shown because ",yt.label," = ",yt.value]})]}),e.jsx("div",{children:at})]})},[tr]),It=o.useCallback(Te=>{if(!ma(Te))return null;const{stats:at,isResolved:yt}=ir(Te),nt=re(Te),Wt=at.mismatch>0?"bg-amber-400":!A.suppressMissingGating&&at.missing>0?"bg-red-400":at.needsDecision>0?"bg-slate-400":"bg-green-400";return e.jsxs("div",{id:`section-${Te.id}`,className:Q("bg-white border border-slate-200 rounded-lg overflow-hidden",Ie===Te.id&&"ring-1 ring-primary/30"),"data-testid":`section-${Te.id}`,children:[e.jsxs("div",{className:"flex items-center",children:[e.jsxs("button",{onClick:()=>{pt(Te.id),ce(Te.id)},className:"flex-1 min-w-0 flex items-center gap-2 px-3 py-2 hover:bg-slate-50/60 transition-colors","data-testid":`section-toggle-${Te.id}`,children:[e.jsx("div",{className:Q("w-2 h-2 rounded-full shrink-0",Wt)}),e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wide text-slate-600 flex-1 text-left",children:Te.label}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[at.mismatch>0&&e.jsxs("span",{className:"text-[10px] text-amber-600 font-semibold",children:[at.mismatch," conflict",at.mismatch!==1?"s":""]}),!A.suppressMissingGating&&at.missing>0&&e.jsxs("span",{className:"text-[10px] text-red-500 font-semibold",children:[at.missing," missing"]}),yt&&e.jsxs("span",{className:"text-[10px] text-green-600 flex items-center gap-0.5",children:[e.jsx(kr,{className:"w-3 h-3"})," ",at.total," resolved"]})]}),e.jsx(Rr,{className:Q("w-3.5 h-3.5 text-slate-400 transition-transform shrink-0",nt&&"rotate-180")}
10)]}),G&&R&&(Te.id==="subjectProperty"||Te.id==="site")&&e.jsx("div",{className:"pr-2 shrink-0",onClick:ts=>ts.stopPropagation(),children:e.jsx(RI,{orderId:R,sectionId:Te.id,label:Te.label})})]}),!nt&&yt&&e.jsx(T6,{label:Te.label,stats:at}),nt&&(()=>{const ts=A.sectionFieldAllowLists?.get(Te.id),gs=ts?Te.fields.filter(qs=>B(Te.id,qs.id)):Te.fields,Va=tg.filter(qs=>!(qs.parentSectionId!==Te.id||ts&&!(qs.triggerFieldIds??[qs.triggerFieldId]).some(Tn=>ts.has(Tn)))),Mr=qs=>qs.fields.some(Ks=>{const Tn=se[Ks.id]?.value;return Tn!=null&&Tn!==""}),xs=qs=>e.jsxs("div",{className:"ml-2 mr-1 mb-2 px-3 py-1.5 rounded-md border border-dashed border-slate-300 bg-slate-50 text-[10px] text-slate-500 italic flex items-center gap-1.5","data-testid":`block-hidden-${qs.id}`,children:[e.jsx(on,{className:"w-3 h-3 shrink-0"}),e.jsxs("span",{children:[qs.label," — hidden, your entries are saved and return when you re-enable it."]})]},`hidden-${qs.id}`),Sn=new Set,ds=qs=>h6(qs,Qt),Zt=qs=>{const Ks=ea(qs);return e.jsxs("div",{className:"xl:col-span-2",children:[e.jsx(f6,{active:Ks,blockId:qs.id,children:Ze(qs,Rs(qs.fields,qs.id))}),!Ks&&Mr(qs)&&xs(qs)]},`slot-${qs.id}`)};function Rs(qs,Ks){const Tn=[];for(const Bn of qs){Tn.push(qe(Bn,Ks));for(const Ka of Va)Sn.has(Ka.id)||ds(Ka)===Bn.id&&(Sn.add(Ka.id),Tn.push(Zt(Ka)))}return Tn}const Os=Rs(gs);for(const qs of Va)Sn.has(qs.id)||Os.push(Zt(qs));return e.jsx("div",{className:"border-t border-slate-100 xl:grid xl:grid-cols-2 xl:gap-x-6",children:Os})})()]},Te.id)},[ma,ir,re,Ie,qe,Ze,Qt,B,E,ea,se,G,R]),Ne=M.filter(Te=>ma(Te)),Ue=Te=>m6[Te]??iv[0].id,ct=iv.filter(Te=>M.some(at=>Ue(at.id)===Te.id)),xt=ct.some(Te=>Te.id===$)?$:ct[0]?.id??"property",qt=Ne.filter(Te=>Ue(Te.id)===xt).filter(Te=>!(G&&Te.id==="scope"&&Te.fields.length===0)),la=o.useMemo(()=>{const Te=new Map;for(const at of iv)Te.set(at.id,{missing:0,conflicts:0,unconfirmed:0,confirmed:0});for(const at of M){const yt=Ue(at.id),nt=A.sectionFieldAllowLists?.get(at.id),ts=[...nt?at.fields.filter(Va=>nt.has(Va.id)):at.fields];for(const Va of tg)Va.parentSectionId===at.id&&(nt&&!(Va.triggerFieldIds??[Va.triggerFieldId]).some(xs=>nt.has(xs))||ea(Va)&&ts.push(...Va.fields));const gs=Te.get(yt);for(const Va of ts)gs[Ve(Va)]++}return Te},[M,Ve,ea,E]),fs=o.useCallback((Te,at)=>{if(!H)return;const yt=zf.find(nt=>nt.id===H.fieldId);yt&&Kt(yt,Te,at,`Confirmed from ${at}`)},[H,Kt]),ps=o.useCallback((Te,at)=>{if(!H)return;const yt=zf.find(nt=>nt.id===H.fieldId);yt&&Kt(yt,Te,"User",at)},[H,Kt]);return e.jsxs("div",{className:"wizard-step2 animate-in fade-in duration-200 flex flex-col h-full","data-testid":"step-subject-site",children:[e.jsxs("div",{className:"shrink-0 border-b border-slate-200 bg-white/95 backdrop-blur sticky top-0 z-10",children:[v&&!Be&&_e&&e.jsxs("div",{className:"flex items-center justify-between gap-2 px-4 py-2 bg-blue-50 border-b border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-blue-800 flex-1 min-w-0",children:[e.jsx(on,{className:"w-3.5 h-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[e.jsxs("strong",{children:["Inspection added on ",new Date(v).toLocaleDateString()]}),_e.updated>0?` — ${_e.updated} field${_e.updated!==1?"s":""} updated${_e.mismatch>0?`, ${_e.mismatch} new decision${_e.mismatch!==1?"s":""} needed`:", all auto-confirmed"}.`:"."]}),_e.updated>0&&e.jsxs("button",{onClick:()=>_("inspection"),className:Q("shrink-0 text-[11px] font-semibold px-2 py-0.5 rounded border transition-all",D==="inspection"?"bg-blue-200 text-blue-800 border-blue-400":"bg-blue-100 text-blue-700 border-blue-300 hover:bg-blue-200"),"data-testid":"btn-filter-inspection",children:["Show ",_e.updated," affected"]})]}),e.jsx("button",{onClick:()=>{He(!0),D==="inspection"&&_("all")},className:"shrink-0 text-[11px] text-blue-600 hover:underline ml-2","data-testid":"btn-dismiss-inspection-banner",children:"Dismiss"})]}),A.stubBanner&&e.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 bg-amber-50 border-b border-amber-200","data-testid":"profile-stub-banner",children:[e.jsx(on,{className:"w-3.5 h-3.5 text-amber-600 shrink-0 mt-0.5"}),e.jsx("p",{className:"text-[11px] text-amber-800",children:A.stubBanner})]}),e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-slate-100 flex-wrap",children:[e.jsx("h2",{className:"text-[13px] font-semibold text-slate-700 mr-1",children:"Subject & Site"}),e.jsx(uD,{counts:pr,active:D==="inspection"?"all":D,onChange:Te=>_(Te),onReset:()=>_("all"),onConfirmAll:Ot,showUnconfirmed:!1,showConfirmed:!1,progress:{verified:pr.confirmed,total:$e},className:"flex-1"}),e.jsx("button",{onClick:()=>ge(!0),className:"shrink-0 text-[10px] text-slate-500 hover:text-slate-700 px-2 py-0.5 rounded border border-slate-200 hover:bg-slate-50","data-testid":"button-reset-all",children:"Reset all data"})]}),e.jsxs("div",{className:"px-4 py-1 border-b border-slate-100 space-y-1",children:[e.jsxs("div",{className:"text-[10px]","data-testid":"counter-rail-legend",children:[e.jsxs("button",{type:"button",onClick:()=>le(Te=>!Te),className:"flex items-center gap-1 text-slate-500 hover:text-slate-700 font-semibold","data-testid":"btn-toggle-counter-legend","aria-expanded":V,children:[e.jsx("span",{"aria-hidden":!0,
10children:V?"▾":"▸"}),"What do the views mean?"]}),V&&e.jsxs("div",{className:"mt-1 flex flex-col gap-1 px-2 py-1.5 bg-slate-50 border border-slate-200 rounded text-slate-600","data-testid":"counter-legend-body",children:[e.jsxs("div",{className:"flex items-center gap-1 text-slate-500",children:[e.jsx(j5,{className:"w-3 h-3"}),"Each view filters the fields below to that bucket — click it to focus, or ",e.jsx("span",{className:"font-semibold",children:"Reset"})," (or ",e.jsx("span",{className:"font-semibold",children:"All fields"}),") to clear. Every field falls in exactly one bucket."]}),e.jsxs("div",{className:"pl-3",children:[e.jsx("span",{className:"font-semibold text-red-600",children:"Missing"})," (no value yet) ·"," ",e.jsx("span",{className:"font-semibold text-amber-600",children:"Conflicts"})," (sources disagree — pick the right value) ·"," ",e.jsx("span",{className:"font-semibold text-emerald-700",children:"Confirmed"})," (matched across sources, or you confirmed/overrode it)."]}),e.jsxs("div",{children:["The ",e.jsx("span",{className:"font-semibold",children:"verified"})," readout on the right is just progress (",e.jsx("span",{className:"font-semibold text-emerald-700",children:"Confirmed"})," ÷ total) — it isn't a filter."]})]})]}),e.jsx(Z0,{})]}),e.jsx("div",{className:"flex flex-wrap items-end gap-1.5 px-4 pt-1.5 border-b-2 border-[#C5A572]",role:"tablist","data-testid":"subject-site-tabs",children:ct.map(Te=>{const at=la.get(Te.id)??{missing:0,conflicts:0,unconfirmed:0,confirmed:0},yt=at.missing+at.conflicts+at.unconfirmed+at.confirmed,nt=D==="all"||D==="inspection"?"all":D,Wt=nt==="all"?yt:at[nt];return e.jsxs("button",{type:"button",role:"tab","aria-selected":xt===Te.id,onClick:()=>z(Te.id),className:Q("relative px-4 py-2 text-[13px] font-semibold rounded-t-md border transition-colors flex items-center gap-1.5",xt===Te.id?"z-10 -mb-0.5 border-[#C5A572] border-t-2 border-b-2 border-b-white bg-[#C5A572]/15 text-[#293757] shadow-sm":"border-slate-300 bg-slate-100 text-slate-500 hover:bg-slate-50 hover:text-[#293757]"),"data-testid":`tab-subject-site-${Te.id}`,children:[Te.label,Wt>0&&e.jsx("span",{className:Q("text-[10px] font-bold px-1.5 py-0.5 rounded-full border leading-none",pD(nt)),"data-testid":`badge-subject-site-${Te.id}`,children:Wt})]},Te.id)})})]}),e.jsx("div",{className:"flex-1 overflow-hidden flex flex-col",children:e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-2 min-w-0","data-testid":"sections-container",children:[xt==="zoning"&&e.jsx("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden","data-testid":"zoning-visual-panel",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2",children:[e.jsxs("div",{className:"border-b md:border-b-0 md:border-r border-slate-200",children:[e.jsx(Iu,{title:"Zoning Map",rightAction:Fe?e.jsxs("button",{onClick:()=>Xt(!0),className:"flex items-center gap-1 text-[10px] text-slate-500 hover:text-slate-700","data-testid":"button-expand-map",children:[e.jsx(ub,{className:"w-3 h-3"}),"Expand"]}):void 0}),e.jsx("div",{className:"p-2",children:Oe?e.jsx("div",{className:"h-40 flex items-center justify-center bg-slate-50 rounded border border-slate-100",children:e.jsx(za,{className:"w-4 h-4 animate-spin text-slate-400"})}):Fe?e.jsx("div",{className:"rounded overflow-hidden border border-slate-100 cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>Xt(!0),children:e.jsx("img",{src:Tt.imageUrl||Tt.imageBase64,alt:"Zoning Map",className:"w-full h-auto","data-testid":"img-zoning-map-inline"})}):e.jsx("div",{className:"h-40 flex items-center justify-center bg-slate-50 rounded border border-slate-100 text-[10px] text-slate-400",children:"Map not available"})})]}),e.jsxs("div",{children:[e.jsx(Iu,{title:"Zoning Summary",rightAction:Pe?e.jsxs("button",{onClick:()=>{const Te=[`Zone: ${Pe.zoneCode}`,Pe.zoneName||"",Pe.zoneDescription||""].filter(Boolean),at=new Blob([Te.join(`
11`)],{type:"text/plain"}),yt=URL.createObjectURL(at),nt=document.createElement("a");nt.href=yt,nt.download="zoning.txt",nt.click(),URL.revokeObjectURL(yt)},className:"flex items-center gap-1 text-[10px] text-slate-500 hover:text-slate-700","data-testid":"button-download-zoning",children:[e.jsx(uN,{className:"w-3 h-3"}),"Export"]}):void 0}),e.jsx("div",{className:"p-2.5",children:rt?e.jsxs("div",{className:"flex items-center gap-2 py-2","data-testid":"zoning-summary-loading",children:[e.jsx(za,{className:"w-3.5 h-3.5 animate-spin text-slate-400"}),e.jsx("span",{className:"text-[10px] text-slate-500",children:"Looking up zoning…"})]}):Pe?e.jsxs("div",{className:"space-y-1.5",children:[i&&e.jsxs("p",{className:"text-[9px] text-slate-400 flex items-center gap-0.5",children:[e.jsx(Wl,{className:"w-2.5 h-2.5"}),i]}),e.jsx("span",{className:"inline-block text-[12px] font-bold px-2 py-0.5 bg-[#8E7A60] text-white rounded",children:Pe.zoneCode||"N/A"}),e.jsx("p",{className:"text-[11px] font-semibold text-slate-700",children:Pe.zoneName||Pe.zoneType}),Pe.zoneDescription&&e.jsx("p",{className:"text-[10px] text-slate-500",children:Pe.zoneDescription})]}):t.zoningClassification.value||t.zoningDescription.value?e.jsxs("div",{className:"space-y-1.5","data-testid":"zoning-summary-fallback",children:[i&&e.jsxs("p",{className:"text-[9px] text-slate-400 flex items-center gap-0.5",children:[e.jsx(Wl,{className:"w-2.5 h-2.5"}),i]}),t.zoningClassification.value&&e.jsx("span",{className:"inline-block text-[12px] font-bold px-2 py-0.5 bg-[#8E7A60] text-white rounded",children:t.zoningClassification.value}),t.zoningDescription.value&&e.jsx("p",{className:"text-[11px] font-semibold text-slate-700",children:t.zoningDescription.value})]}):e.jsxs("div",{className:"space-y-1.5 py-1",children:[e.jsx("p",{className:"text-[10px] text-slate-400","data-testid":"zoning-summary-empty",children:"Zoning summary unavailable — enter it manually below."}),u&&$t&&e.jsxs("button",{onClick:()=>u(),className:"flex items-center gap-1 text-[10px] text-slate-600 hover:text-slate-800","data-testid":"button-retry-zoning",children:[e.jsx(Kl,{className:"w-3 h-3"}),"Try again"]})]})})]})]})}),xt==="site"&&e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden","data-testid":"fema-status-panel",children:[e.jsx(Iu,{title:"FEMA Flood Lookup",rightAction:f?e.jsxs("button",{onClick:()=>f(),disabled:h,className:"flex items-center gap-0.5 text-[10px] text-slate-500 hover:text-slate-700 disabled:opacity-50","data-testid":"button-refresh-fema",children:[h?e.jsx(za,{className:"w-3 h-3 animate-spin"}):e.jsx(Kl,{className:"w-3 h-3"}),"Refresh"]}):void 0}),m==="provider_error"&&!t.femaMapNumber?.value&&e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 bg-amber-50","data-testid":"fema-panel-warning",children:[e.jsx(Ns,{className:"w-3 h-3 text-amber-500 shrink-0"}),e.jsx("p",{className:"text-[10px] text-amber-700",children:"FEMA service unavailable — enter the flood fields below manually."})]}),m==="not_found"&&e.jsx("p",{className:"px-3 py-1.5 text-[10px] text-slate-500","data-testid":"fema-panel-notfound",children:"No FIRM panel c
11overs this location."}),e.jsx("div",{className:"grid grid-cols-3 gap-2 px-3 py-2",children:[{label:"Flood Zone",val:t.femaFloodZone?.value,danger:typeof t.femaFloodZone?.value=="string"&&(t.femaFloodZone.value.startsWith("A")||t.femaFloodZone.value.startsWith("V")),pillKey:"femaFloodZone"},{label:"Map #",val:t.femaMapNumber?.value,danger:!1,pillKey:"femaMapNumber"},{label:"Map Date",val:t.femaMapDate?.value,danger:!1,pillKey:"femaMapDate"}].map(Te=>e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("span",{className:"text-[9px] uppercase tracking-wide text-slate-400",children:[Te.label,F&&e.jsx(Fs,{section:"propertyData",fieldName:Te.pillKey})]}),e.jsx("span",{className:Q("text-[12px] font-semibold",Te.danger?"text-red-600":"text-slate-700"),children:Te.val??"—"})]},Te.label))})]}),qt.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(kr,{className:"w-10 h-10 text-green-500 mb-3"}),e.jsx("h3",{className:"text-sm font-semibold text-slate-700",children:"All clear!"}),e.jsxs("p",{className:"text-[11px] text-slate-500 mt-1",children:[D==="conflicts"?"No conflicts":D==="inspection"?"No inspection-affected fields":D==="missing"?"No missing fields":D==="unconfirmed"?"No unconfirmed fields":D==="confirmed"?"No confirmed fields":"Nothing"," on this tab."," ",'Click "All fields" to review everything.']}),e.jsx("button",{onClick:()=>_("all"),className:"mt-2 text-[11px] text-primary hover:underline",children:"Show all fields"})]}),qt.map(Te=>It(Te)),y.length>0&&D==="all"&&xt===ct[ct.length-1]?.id&&e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden","data-testid":"override-log",children:[e.jsx(Iu,{title:`Override Log (${y.length})`}),e.jsx("div",{className:"divide-y divide-slate-100 max-h-40 overflow-y-auto",children:y.slice(0,20).map((Te,at)=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 text-[10px] text-slate-600",children:[e.jsx("span",{className:"font-semibold text-slate-700 w-28 truncate",children:Te.label}),e.jsx("span",{className:"text-slate-400 line-through truncate max-w-[80px]",children:Te.oldValue||"—"}),e.jsx("span",{className:"text-green-700 font-medium truncate max-w-[80px]",children:Te.newValue}),e.jsx(pd,{source:Te.source}),e.jsx("span",{className:"text-slate-400 ml-auto truncate max-w-[100px]",children:Te.reason}),e.jsx("span",{className:"text-slate-300 shrink-0",children:new Date(Te.timestamp).toLocaleTimeString()})]},at))})]})]})}),e.jsx(I6,{chooser:H,onClose:()=>{const Te=H;Te?.forceOwn&&sa(at=>{const yt=at[Te.fieldId];return yt?.flaggedBad?{...at,[Te.fieldId]:{...yt,flaggedBad:!1}}:at}),ye(null)},onUse:fs,onEnterOwn:ps,defaultShowOwn:!!H?.forceOwn,currentDefault:H?me[H.fieldId]??null:null,onSetDefault:H?Te=>pe(H.fieldId,Te):void 0}),e.jsx(xi,{open:de,onOpenChange:ge,children:e.jsxs(bi,{className:"sm:max-w-md",children:[e.jsxs($i,{children:[e.jsx(si,{children:"Reset Fields"}),e.jsx(pl,{children:"Reset all fields on this step back to imported values? Override log will be cleared."})]}),e.jsxs(eb,{className:"gap-2 sm:gap-0",children:[e.jsx(De,{variant:"outline",onClick:()=>ge(!1),children:"Cancel"}),e.jsx(De,{onClick:()=>{a(tP(qa));const Te={};fe(Te),T?.(Te),O?.(),ge(!1)},"data-testid":"btn-confirm-reset",children:"Yes, Reset"})]})]})}),st&&Fe&&e.jsx(xi,{open:st,onOpenChange:Xt,children:e.jsxs(bi,{className:"sm:max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx($i,{children:e.jsx(si,{children:"Zoning Map"})}),e.jsx("img",{src:Tt.imageUrl||Tt.imageBase64,alt:"Zoning Map",className:"w-full h-auto rounded","data-testid":"img-zoning-map-expanded"})]})})]})}function w6(t){if(!t||typeof t!="object")return null;const a=t;return a.success!==!0||typeof a.floodZone!="string"||a.floodZone.trim()===""||typeof a.isSpecialFloodHazardArea!="boolean"?null:a.isSpecialFloodHazardArea?"Yes":"No"}function P6(t){return!!t?.value&&(!!t.confirmed||t.source!=="FEMA")}const O6=[{sectionId:"atAGlance",blockKey:"at_a_glance_36",displayName:"At a Glance",indexKey:"AT_A_GLANCE_36"},{sectionId:"assignment",blockKey:"assignment_36",displayName:"Assignment",indexKey:"ASSIGNMENT_36"},{sectionId:"subjectProperty",blockKey:"subject_property_36",displayName:"Subject Property",indexKey:"SUBJECT_PROPERTY_36"},{sectionId:"site",blockKey:"site_36",displayName:"Site",indexKey:"SITE_36"},{sectionId:"improvements",blockKey:"improvements_36",displayName:"Improvements",indexKey:"IMPROVEMENTS_36"},{sectionId:"salesContract",blockKey:"sales_contract_36",displayName:"Sales Contract",indexKey:"SALES_CONTRACT_36"},{sectionId:"projectInformation",blockKey:"project_information_36",displayName:"Project Information",indexKey:"PROJECT_INFORMATION_36"},{sectionId:"listingSaleHistory",blockKey:"listing_sale_history_36",displayName:"Listing & Sale History",indexKey:"LISTING_SALE_HISTORY_36"},{sectionId:"market",blockKey:"market_36",displayName:"Market",indexKey:"MARKET_36"},{sectionId:"costApproach",blockKey:"cost_approach_36",displayName:"Cost Approach",indexKey:"COST_APPROACH_36"}],L6=[{kind:"destination",sectionId:"urarParties",sectionName:"Assignment",fieldName:I_.propertyParties,label:"Contacts Name",value:"",slug:"wizard-dest-contacts-name",ke
11ywords:"borrower seller owner of public record party name"},{kind:"destination",sectionId:"certifications",sectionName:"Assignment",fieldName:"AppraiserFullName",label:"Name",value:"",slug:"wizard-dest-appraiser-name"},{kind:"destination",sectionId:"certifications",sectionName:"Assignment",fieldName:"AppraiserFirstName",label:"First Name",value:"",slug:"wizard-dest-appraiser-first-name"},{kind:"destination",sectionId:"certifications",sectionName:"Assignment",fieldName:"AppraiserMiddleName",label:"Middle Name",value:"",slug:"wizard-dest-appraiser-middle-name"},{kind:"destination",sectionId:"certifications",sectionName:"Assignment",fieldName:"AppraiserLastName",label:"Last Name",value:"",slug:"wizard-dest-appraiser-last-name"},{kind:"destination",sectionId:"certifications",sectionName:"Assignment",fieldName:"AppraiserSuffixName",label:"Suffix",value:"",slug:"wizard-dest-appraiser-suffix"},{kind:"destination",sectionId:"certifications",sectionName:"Assignment",fieldName:"AppraiserCompanyName",label:"Company Name",value:"",slug:"wizard-dest-appraiser-company-name"}];function D6(t){return O6.map(a=>({sectionId:a.sectionId,blockKey:a.blockKey,displayName:a.displayName,stepIndex:t[a.indexKey]??-1}))}const k6={atAGlance:"atAGlance",reconciliation:"atAGlance",reportMetadata:"atAGlance",assignmentInfo:"assignment",certifications:"assignment",approaches:"assignment",urarParties:"assignment",subjectProperty:"subjectProperty",disasterMitigation:"subjectProperty",energyFeatures:"subjectProperty",functionalObsolescence:"subjectProperty",highestBestUse:"subjectProperty",vehicleStorage:"subjectProperty",amenities:"subjectProperty",propertyAmenities:"subjectProperty",site:"site",improvements:"improvements",outbuilding:"improvements",sketch:"improvements",salesContract:"salesContract",projectInformation:"projectInformation",listingSaleHistory:"listingSaleHistory",subjectListing:"listingSaleHistory",priorSaleTransferHistory:"listingSaleHistory",market:"market",costApproach:"costApproach"},M6=new Set(["OverallQualityRatingCode","OverallConditionRatingCode","ValuationCommentText"]),F6=new Set(["CommunityLandTrustName","CommunityLandTrustGroundLeaseExpirationDate","CommunityLandTrustResaleRestrictionDescription"]);function UT(t){return k6[t]??null}function ste(t,a,s){if(!t)return null;const r=`${a}.${s}`,n=Array.from(t.querySelectorAll("[data-field-path]")).find(i=>i.dataset.fieldPath===r);return n||(Array.from(t.querySelectorAll("[data-field-name]")).find(i=>i.dataset.fieldName===s)??null)}function _6(t,a){const s=new Map(a.filter(r=>r.stepIndex!==-1).map(r=>[r.sectionId,r]));return t.flatMap(r=>{const n=UT(r.sectionId);if(!n)return[];const i=s.get(n);return i?n==="site"&&r.kind==="destination"&&F6.has(r.fieldName)?[]:n==="improvements"&&r.kind==="destination"&&r.fieldName&&!r.fieldName.includes("-")&&!M6.has(r.fieldName)?[]:n==="atAGlance"&&r.kind==="destination"&&r.fieldName.startsWith("DefectItem")?[]:[{...r,sectionId:n,routeSectionId:r.sectionId===n?r.routeSectionId:r.sectionId,sectionName:i.displayName}]:[]})}function U6(t){if(typeof document>"u")return[];const a=new Map(t.filter(s=>s.stepIndex!==-1).map(s=>[s.sectionId,s]));return Array.from(document.querySelectorAll("[data-wizard-search-section]")).flatMap(s=>{const r=a.get(s.getAttribute("data-wizard-search-section")??"");if(!r)return[];const n=Array.from(s.querySelectorAll("[data-wizard-search-route-section]"));return n.length>0?n.map(i=>({root:i,sectionId:r.sectionId,sectionName:r.displayName,routeSectionId:i.getAttribute("data-wizard-search-route-section")??void 0})):[{root:s,sectionId:r.sectionId,sectionName:r.displayName}]})}const V6=["Airbnb","VRBO","Booking.com","Direct / Other"],$6=["Yes","No","Unknown"];function B6({data:t,setData:a,orderId:s,inspectionCaptured:r=!1}){const i=o.useMemo(()=>ny(t,r),[t,r]),l=y=>i[y]?.value,c=y=>S0({manualOverride:!!i[y]?.isEdited,smartFieldSource:i[y]?.source??null,hasDefault:i[y]?.value!==void 0&&i[y]?.value!==null&&i[y]?.value!==""});function d(y,b,j="User"){a(T=>({...T,[y]:{value:b,source:j,isEdited:j==="User",isConfirmed:!0}}))}const p=o.useRef(null),u=o.useRef(!1),[m,h]=pj(null),[f,v]=pj(null),[S,N]=pj(!1);o.useEffect(()=>{!s||u.current||(u.current=!0,N(!0),fetch(`/api/str/subject-prefill?orderId=${encodeURIComponent(s)}`,{credentials:"include"}).then(async y=>{const b=await y.json().catch(()=>({}));if(!y.ok||!b?.success)throw new Error(b?.error||`HTTP ${y.status}`);return b.data}).then(y=>{p.current=y,h(y);const b=(j,T,O)=>{if(T==null||T==="")return;const E=i[j];E?.isEdited||E?.value!=null&&E?.value!==""||d(j,T,O)};y.primaryPlatform.value&&b("strPlatform",y.primaryPlatform.value,y.primaryPlatform.source),y.adr.value!=null&&b("strAvgNightlyRate",String(Math.round(y.adr.value)),y.adr.source),y.occupancy.value!=null&&b("strOccupancyRate",String(Math.round(y.occupancy.value)),y.occupancy.source)}).catch(y=>v(y instanceof Error?y.message:String(y))).finally(()=>N(!1)))},[s]);const x=o.useRef(!1);return o.useEffect(()=>{if(x.current)return;const y=i.numUnits?.value,b=y!=null?parseInt(String(y),10):NaN,j=i.bedrooms?.value,T=j!=null?parseInt(String(j),10):NaN;if(!Number.isFinite(b)&&!Number.isFinite(T))return;x.current=!0;const O=U=>i[U]?.source||"PR";Number.isFinite(b)&&b>0&&!i.strTotalUnits?.isEdited&&(i.strTotalUnits?.value==null||i.strTotalUnits?.value==="")&&d("strTotalUnits",String(b),O("numUnits"));const E=!Number.isFinite(b)||b<=1;E&&Number.isFinite(T)&&T>0&&!i.strBedsPerUnit?.isEdited&&(i.strBedsPerUnit?.value==null||i.strBedsPerUnit?.value==="")&&d("strBedsPerUnit",String(T),O("bedrooms"));const R=i.bathrooms?.value,G=R!=null?parseFloat(String(R)):NaN;if(E&&Number.isFinite(G)&&G>0&&!i.strBathsPerUnit?.isEdited&&(i.strBathsPerUnit?.value==null||i.strBathsPerUnit?.value==="")&&d("strBathsPerUnit",String(G),O("bathrooms")),Number.isFinite(T)&&T>
110&&(!Number.isFinite(b)||b<=1)){const U=T===1?"strOneBedUnits":T===2?"strTwoBedUnits":"strThreePlusBedUnits";!i[U]?.isEdited&&(i[U]?.value==null||i[U]?.value==="")&&d(U,"1",O("bedrooms"))}},[i.numUnits?.value,i.bedrooms?.value]),e.jsxs("div",{className:"animate-in fade-in duration-200 flex flex-col h-full","data-testid":"step-str-subject",children:[e.jsx("div",{className:"shrink-0 border-b border-slate-200 bg-white/95 backdrop-blur sticky top-0 z-10",children:e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-slate-100 flex-wrap",children:[e.jsx("h2",{className:"text-[13px] font-semibold text-slate-700",children:"STR Subject Data"}),e.jsx("span",{className:"text-[10px] text-slate-400 bg-slate-100 rounded px-1.5 py-0.5 font-semibold",children:"Step 3"}),e.jsx("span",{className:"text-[10px] text-blue-600 bg-blue-50 border border-blue-200 rounded px-1.5 py-0.5 font-semibold",children:"STR add-on"}),S&&e.jsx("span",{className:"text-[10px] text-slate-500","data-testid":"str-prefill-loading",children:"Loading market data…"}),e.jsx("div",{className:"ml-auto",children:e.jsx(Z0,{})})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:[e.jsx(z6,{loading:S,error:f,regulations:m?.regulations??null}),e.jsxs(zb,{id:"str-basics",title:"STR Basics",children:[e.jsx($l,{label:"Primary Platform",source:c("strPlatform"),children:e.jsx("div",{className:"flex gap-1 flex-wrap",children:V6.map(y=>e.jsx("button",{onClick:()=>d("strPlatform",y),className:["px-2 py-0.5 text-[11px] rounded border transition-colors",l("strPlatform")===y?"bg-blue-600 text-white border-blue-700":"bg-white text-slate-600 border-slate-300 hover:bg-slate-50"].join(" "),"data-testid":`btn-str-platform-${y.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,children:y},y))})}),e.jsx($l,{label:"Avg Nightly Rate (ADR)",source:c("strAvgNightlyRate"),children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[11px] text-slate-500",children:"$"}),e.jsx(uS,{placeholder:"0",value:l("strAvgNightlyRate"),onChange:y=>d("strAvgNightlyRate",y),testId:"input-str-avg-nightly-rate",width:"w-32"}),m?.adr.value!=null&&e.jsxs("span",{className:"text-[10px] text-slate-400","data-testid":"hint-adr-market",children:["market p50 $",Math.round(m.adr.value)]})]})}),e.jsx($l,{label:"Occupancy Rate",source:c("strOccupancyRate"),children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{type:"number",placeholder:"0",min:0,max:100,className:"text-[11px] border border-slate-200 rounded px-2 py-1 w-20 focus:outline-none focus:ring-1 focus:ring-primary/40",value:l("strOccupancyRate")!==void 0&&l("strOccupancyRate")!==null?String(l("strOccupancyRate")):"",onCh
11ange:y=>d("strOccupancyRate",y.target.value),"data-testid":"input-str-occupancy-rate"}),e.jsx("span",{className:"text-[11px] text-slate-500",children:"%"}),m?.occupancy.value!=null&&e.jsxs("span",{className:"text-[10px] text-slate-400","data-testid":"hint-occupancy-market",children:["market p50 ",Math.round(m.occupancy.value),"%"]})]})}),e.jsx($l,{label:"HOA Restricts STR",source:c("strHoaRestriction"),children:e.jsx(uj,{value:l("strHoaRestriction"),onChange:y=>d("strHoaRestriction",y),testIdPrefix:"btn-str-hoa-restriction"})})]}),e.jsxs(zb,{id:"str-unit-mix",title:"Unit Mix",children:[e.jsx($l,{label:"Total Units / Rooms",source:c("strTotalUnits"),children:e.jsx(vh,{placeholder:"—",value:l("strTotalUnits"),onChange:y=>d("strTotalUnits",y),testId:"input-str-total-units",width:"w-20"})}),e.jsx($l,{label:"Studio Units",source:c("strStudioUnits"),children:e.jsx(vh,{placeholder:"0",value:l("strStudioUnits"),onChange:y=>d("strStudioUnits",y),testId:"input-str-studio-units",width:"w-20"})}),e.jsx($l,{label:"1-Bed Units",source:c("strOneBedUnits"),children:e.jsx(vh,{placeholder:"0",value:l("strOneBedUnits"),onChange:y=>d("strOneBedUnits",y),testId:"input-str-onebed-units",width:"w-20"})}),e.jsx($l,{label:"2-Bed Units",source:c("strTwoBedUnits"),children:e.jsx(vh,{placeholder:"0",value:l("strTwoBedUnits"),onChange:y=>d("strTwoBedUnits",y),testId:"input-str-twobed-units",width:"w-20"})}),e.jsx($l,{label:"3+ Bed Units",source:c("strThreePlusBedUnits"),children:e.jsx(vh,{placeholder:"0",value:l("strThreePlusBedUnits"),onChange:y=>d("strThreePlusBedUnits",y),testId:"input-str-threeplusbed-units",width:"w-20"})})]}),e.jsxs(zb,{id:"str-sleeps",title:"Sleeps & Per-Unit Config",children:[e.jsx($l,{label:"Typical Sleeps / Unit",source:c("strSleepsPerUnit"),children:e.jsx(vh,{placeholder:"—",value:l("strSleepsPerUnit"),onChange:y=>d("strSleepsPerUnit",y),testId:"input-str-sleeps-per-unit",width:"w-20"})}),e.jsx($l,{label:"Beds / Unit (typical)",source:c("strBedsPerUnit"),children:e.jsx(vh,{placeholder:"—",value:l("strBedsPerUnit"),onChange:y=>d("strBedsPerUnit",y),testId:"input-str-beds-per-unit",width:"w-20"})}),e.jsx($l,{label:"Baths / Unit (typical)",source:c("strBathsPerUnit"),children:e.jsx(uS,{placeholder:"—",value:l("strBathsPerUnit"),onChange:y=>d("strBathsPerUnit",y),testId:"input-str-baths-per-unit",width:"w-24"})})]}),e.jsxs(zb,{id:"str-parking",title:"Parking",children:[e.jsx($l,{label:"On-Site Parking",source:c("strHasParking"),children:e.jsx(uj,{value:l("strHasParking"),onChange:y=>d("strHasParking",y),testIdPrefix:"btn-str-has-parking"})}),e.jsx($l,{label:"Parking Type",source:c("strParkingType"),children:e.jsx(uS,{placeholder:"e.g. Driveway, Garage, Street",value:l("strParkingType"),onChange:y=>d("strParkingType",y),testId:"input-str-parking-type",width:"w-48"})}),e.jsx($l,{label:"# of Spaces",source:c("strParkingSpaces"),children:e.jsx(vh,{placeholder:"—",value:l("strParkingSpaces"),onChange:y=>d("strParkingSpaces",y),testId:"input-str-parking-spaces",width:"w-20"})})]}),e.jsxs(zb,{id:"str-management",title:"Management",children:[e.jsx($l,{label:"Professionally Managed",source:c("strProfessionallyManaged"),children:e.jsx(uj,{value:l("strProfessionallyManaged"),onChange:y=>d("strProfessionallyManaged",y),testIdPrefix:"btn-str-professionally-managed"})}),e.jsx($l,{label:"Management Company",source:c("strManagementCompany"),children:e.jsx(uS,{placeholder:"—",value:l("strManagementCompany"),onChange:y=>d("strManagementCompany",y),testId:"input-str-management-company",width:"w-52"})})]})]})]})}function z6({loading:t,error:a,regulations:s}){const r=s?.legalStatus?.trim()||(s?"Unknown":null),n=(()=>{const i=(r||"").toLowerCase();return i.includes("allow")||i.includes("legal")||i==="yes"?"bg-emerald-50 text-emerald-700 border-emerald-200":i.includes("restrict")||i.includes("permit")?"bg-amber-50 text-amber-700 border-amber-200":i.includes("ban")||i.includes("illegal")||i==="no"?"bg-rose-50 text-rose-700 border-rose-200":"bg-slate-100 text-slate-600 border-slate-200"})();return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden","data-testid":"section-str-regulatory-status",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-slate-50/60 border-b border-slate-100",children:[e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wide text-slate-600",children:"Regulatory 
11Status"}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-wide text-slate-400",children:"Read-only"}),e.jsx(pd,{source:"Mashvisor",className:"ml-1"})]}),e.jsxs("div",{className:"px-3 py-2 space-y-1",children:[t&&e.jsx("div",{className:"text-[11px] text-slate-500","data-testid":"str-regulations-loading",children:"Loading jurisdiction data…"}),!t&&a&&e.jsxs("div",{className:"text-[11px] text-rose-600","data-testid":"str-regulations-error",children:["Could not load regulatory data: ",a]}),!t&&!a&&!s&&e.jsx("div",{className:"text-[11px] text-slate-500","data-testid":"str-regulations-empty",children:"No jurisdiction data returned for this market."}),!t&&s&&e.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-1.5 items-center",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:"Legal status:"}),e.jsx("span",{className:`text-[11px] font-semibold px-2 py-0.5 rounded border ${n}`,"data-testid":"text-str-legal-status",children:r})]}),e.jsx(aP,{label:"Day limit",testId:"text-str-day-limit",value:s.dayLimit!=null?`${s.dayLimit} nights/yr`:"—"}),e.jsx(aP,{label:"Permit fee",testId:"text-str-permit-fee",value:s.permitFee!=null?`$${s.permitFee.toLocaleString()}`:"—"}),s.sourceUrl&&e.jsxs("a",{href:s.sourceUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[11px] text-blue-600 hover:underline inline-flex items-center gap-1","data-testid":"link-str-source-url",children:["Ordinance ",e.jsx(rf,{className:"w-3 h-3"})]})]}),!t&&s?.notes&&e.jsx("div",{className:"text-[10px] text-slate-500 pt-1","data-testid":"text-str-regulation-notes",children:s.notes})]})]})}function aP({label:t,value:a,testId:s}){return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:[t,":"]}),e.jsx("span",{className:"text-[11px] text-slate-700","data-testid":s,children:a})]})}function zb({id:t,title:a,children:s}){return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg overflow-hidden","data-testid":`section-${t}`,children:[e.jsx("div",{className:"flex items-center gap-2 px-3 py-2 bg-slate-50/60 border-b border-slate-100",children:e.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wide text-slate-600",children:a})}),s]})}function $l({label:t,source:a,children:s}){return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-[7px] border-b border-slate-100 last:border-0 hover:bg-slate-50/40 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-1.5 w-[160px] shrink-0",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:t}),a&&e.jsx(pd,{source:a})]}),e.jsx("div",{className:"flex-1 min-w-0",children:s})]})}function uS({placeholder:t,value:a,onChange:s,testId:r,width:n}){return e.jsx("input",{type:"text",placeholder:t,className:`text-[11px] border border-slate-200 rounded px-2 py-1 ${n} focus:outline-none focus:ring-1 focus:ring-primary/40`,value:a!=null?String(a):"",onChange:i=>s(i.target.value),"data-testid":r})}function vh({placeholder:t,value:a,onChange:s,testId:r,width:n}){return e.jsx("input",{type:"number",placeholder:t,min:0,className:`text-[11px] border border-slate-200 rounded px-2 py-1 ${n} focus:outline-none focus:ring-1 focus:ring-primary/40`,value:a!=null?String(a):"",onChange:i=>s(i.target.value),"data-testid":r})}function uj({value:t,onChange:a,testIdPrefix:s}){return e.jsx("div",{className:"flex gap-1",children:$6.map(r=>{const n=t===r;let i="bg-green-600 text-white border-green-700";return r==="Yes"?i="bg-blue-600 text-white border-blue-700":r==="Unknown"&&(i="bg-slate-500 text-white border-slate-600"),e.jsx("button",{onClick:()=>a(r),className:["px-2.5 py-0.5 text-[11px] font-semibold rounded border transition-colors",n?i:"bg-white text-slate-600 border-slate-300 hover:bg-slate-50"].join(" "),"data-testid":`${s}-${r.toLowerCase()}`,children:r},r)})})}function pj(t){return o.useState(t)}function v0(t){if(!t)return"Unknown";const a=[t.status,t.standardStatus,t.StandardStatus,t.mlsStatus,t.MlsStatus].find(s=>typeof s=="string"&&s.trim().length>0);return a?a.trim().toLowerCase()==="under contract"?"PEND":J0(a)??"Unknown":"Unknown"}function q6(t){return t.constructionMethod==="ManufacturedHousing"?"MANUFACTURED":t.projectType==="Cooperative"?"COOP":t.projectType==="Condominium"?"CONDO":t.unitCount&&t.unitCount>=2&&t.unitCount<=4?"SF_2_4_UNIT":"SF_DETACHED"}const Al=t=>{if(!(t==null||t===""))return{value:t,confidence:"high",source:"user_entry"}},ll=(...t)=>{for(const a of t){if(a==null)continue;const s=typeof a=="object"&&"value"in a?a.value:a;if(s==null)continue;const r=String(s).trim();if(r.length>0)return r}},Y6={"Subject Property|AddressLineText":"subject.Property Address","Subject Property|CityName":"subject.City","Subject Property|StateCode":"subject.State","Subject Property|PostalCode":"subject.Zip Code","Site|AddressLineText":"subject.Property Address","Site|CityName":"subject.City","Site|StateCode":"subject.State","Site|PostalCode":"subject.Zip Code","Site|CountyName":"subject.County","Site|NeighborhoodName":"subject.Neighborhood Name","Site|ParcelsLegalDescription":"subject.
11Legal Description","Site|LotSizeAreaMeasure":"site.Area","Subject Property|StructuralDesignType":"improvements.Design Style","Subject Property|ConstructionMethodType":"improvements.Type","Dwelling Exterior|PropertyStructureBuiltYear":"improvements.Year Built","Unit Interior|BedroomCount":"improvements.Bedrooms","Unit Interior|FullBathroomCount":"improvements.Bathrooms Full","Unit Interior|HalfBathroomCount":"improvements.Bathrooms Half","Reconciliation|OpinionValueAmount":"reconciliation.Opinion of Market Value","Reconciliation|EffectiveDate":"reconciliation.Effective Date of Appraisal","Appraiser Info|AppraiserLicenseStateCode":"signature.License State","Appraiser Info|AppraiserName":"signature.Appraiser Name","Report Identification|AppraiserFileIdentifier":"signature.File Number","Assignment Information|AppraiserFileIdentifier":"signature.File Number"};function G6(t,a){return Y6[`${t}|${a}`]??null}function H6(t){const a=t.sectionData.subject||{},s=t.sectionData.improvements||{},r=t.propertyData||{},n=t.orderData||{},i=t.reconciliationData||{},l=t.appraiserInfo||{},c=r.addressInfo||{},d=r.propMixData||{},p=ll(a.address,a.AddressLineText,c.streetAddress,n.propertyAddress?.value),u=ll(a.city,a.CityName,c.city,n.propertyCity?.value),m=ll(a.state,a.StateCode,c.state,n.propertyState?.value),h=ll(a.zipCode,a.PostalCode,c.zipCode,n.propertyZip?.value),f=ll(s.yearBuilt,d.yearBuilt),v=ll(s.bedrooms,d.bedrooms),S=ll(s.fullBaths,d.bathsFull),N=ll(s.halfBaths,d.bathsHalf),x=ll(s.gla,d.livingArea),y=Number(d.unitsCount||1),b=ll(d.propertyType,r.propertyType),j=ll(s.type)==="Manufactured"?"ManufacturedHousing":"SiteBuilt",T={propertyType:q6({unitCount:y,projectType:b?.toLowerCase().includes("cond")?"Condominium":b?.toLowerCase().includes("coop")?"Cooperative":void 0,constructionMethod:j}),propertyInProject:!!b?.toLowerCase().includes("cond"),constructionMethodType:j,hasGarage:Number(s.garageCars||0)>0,hasCarport:!1,isNewConstruction:!1,hasPoolOrSpa:!1,hasAccessoryUnit:!1,isRental:!1,isFHA:!1,isVA:!1},O=ll(i.finalOpinionOfValue),E=ll(i.effectiveDate);return{id:n.id||"urar-live",orderId:n.id||"urar-live",status:"in_progress",conditionalityState:T,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),flaggedFields:[],narratives:{},subjectProperty:{AddressLineText:Al(p),CityName:Al(u),StateCode:Al(m),PostalCode:Al(h),StructuralDesignType:Al(ll(s.design)),ConstructionMethodType:Al(j)},improvements:{PropertyStructureBuiltYear:Al(f),BedroomCount:Al(v),FullBathroomCount:Al(S),HalfBathroomCount:Al(N),TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure:Al(x)},reconciliationValue:{OpinionValueAmount:Al(O),EffectiveDate:Al(E)},reportIdentification:{AppraiserFileIdentifier:Al(ll(n.fileNumber,n.orderNumber))},appraiserInfo:{AppraiserName:Al(ll(l.name)),AppraiserLicenseStateCode:Al(ll(l.licenseState)),AppraiserLicenseIdentifier:Al(ll(l.licenseNumber))},costApproach:{OpinionOfSiteValueAmount:Al(ll(t.costApproachData?.opinionOfSiteValue))}}}function W6(t){return t.map((a,s)=>{const r=a.severity==="Fatal",n=G6(a.section,a.dataElement);return{id:`base-${a.messageId||s}`,source:"base",title:a.reportLabel||a.dataElement||a.messageId,severity:r?"hard-stop":"warning",blockingLevel:r?"blocking":"warning",description:`[${a.messageId}] ${a.message}`,targetField:n,category:a.subsection?`${a.section} › ${a.subsection}`:a.section}})}const K6=JSON.parse(`[{"uniqueId":"0100.0007","dataElement":"AddressLineText","messageId":"UAD1001","message":"Provide the address line for the subject property physical address.","ruleLogic":"If AddressLineText is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Physical Address","dataPointName":"AddressLineText","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"0100.0009","dataElement":"CityName","messageId":"UAD1002","message":"Provide the city name for the subject property physical address.","ruleLogic":"If CityName is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Physical Address","dataPointName":"CityName","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"0100.0010","dataElement":"CountyName","messageId":"UAD1003","message":"Provide the county name for the subject property physical address.","ruleLogic":"If CountyName is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"County","dataPointName":"CountyName","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"0100.0011","dataElement":"PostalCode","messageId":"UAD1004","message":"Provide the ZIP code for the subject property physical address.","ruleLogic":"If PostalCode is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Physical Address","dataPointName":"PostalCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"0100.0011","dataElement":"PostalCode","messageId":"UAD1005","message":"The ZIP code for the subject property physical address must be either 5 digits, or 5 digits, a hyphen, and 4 digits (Z
11IP+4).","ruleLogic":"If PostalCode is not in the required format (5 digits, or 5 digits, a hyphen, and 4 digits)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Physical Address (%PV%)","dataPointName":"PostalCode (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"0100.0012","dataElement":"StateCode","messageId":"UAD1006","message":"Provide the state code for the subject property physical address.","ruleLogic":"If StateCode is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Physical Address","dataPointName":"StateCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"0100.0012","dataElement":"StateCode","messageId":"UAD1007","message":"The state code for the subject property physical address must be a valid 2-character US State or Territory Code.","ruleLogic":"If StateCode is not a valid 2-character US State or Territory Code","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Physical Address (%PV%)","dataPointName":"StateCode (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"0100.0015","dataElement":"LatitudeIdentifier","messageId":"UAD1008","message":"Provide the latitude for subject property. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If LatitudeIdentifier is not provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LatitudeIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LOCATION_IDENTIFIER/GEOSPATIAL_INFORMATION/"},{"uniqueId":"0100.0016","dataElement":"LongitudeIdentifier","messageId":"UAD1009","message":"Provide the longitude for subject property. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If LongitudeIdentifier is not provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LongitudeIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LOCATION_IDENTIFIER/GEOSPATIAL_INFORMATION/"},{"uniqueId":"0100.0019","dataElement":"AccessoryDwellingUnitTotalCount","messageId":"UAD1010","message":"Provide the total number of ADUs, even if the value is 0.","ruleLogic":"If AccessoryDwellingUnitTotalCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Accessory Dwelling Units","dataPointName":"AccessoryDwellingUnitTotalCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0019","dataElement":"AccessoryDwellingUnitTotalCount","messageId":"UAD1011","message":"The number of 'Accessory Dwelling Units' does not equal the number of living units identified as an ADU.","ruleLogic":"If AccessoryDwellingUnitTotalCount <> the number of instances of PROPERTY_UNIT_DETAIL with AccessoryDwellingUnitIndicator = \\"true\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Accessory Dwelling Units (%PV%)","dataPointName":"AccessoryDwellingUnitTotalCount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0020","dataElement":"AttachmentType","messageId":"UAD1012","message":"Provide the 'Attachment Type' for the property.","ruleLogic":"If AttachmentType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Attachment Type","dataPointName":"AttachmentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0021","dataElement":"DwellingCount","messageId":"UAD1013","message":"Provide the total number of dwellings.","ruleLogic":"If DwellingCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Dwellings Containing Units","dataPointName":"DwellingCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0021","dataElement":"DwellingCount","messageId":"UAD1014","message":"The total number of dwellings must be at least 1.","ruleLogic":"If DwellingCount < 1","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Dwellings Containing Units (%PV%)","dataPointName":"DwellingCount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/","minValue":1},{"uniqueId":"0100.0021","dataElement":"DwellingCount","messageId":"UAD1015","message":"The total number of dwellings exceeds the total number of living units, excluding any ADUs.","ruleLogic":"If DwellingCount >
11 LivingUnitExcludingADUCount","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Dwellings Containing Units (%PV%)","dataPointName":"DwellingCount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0021","dataElement":"DwellingCount","messageId":"UAD1016","message":"The 'Dwellings Containing Units' does not equal the number of structures identified as a dwelling.","ruleLogic":"If DwellingCount does not equal the number of instances of IMPROVEMENT_DETAIL with ImprovementType = \\"Dwelling\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Dwellings Containing Units (%PV%)","dataPointName":"DwellingCount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0022","dataElement":"LivingUnitExcludingADUCount","messageId":"UAD1017","message":"Provide the total number of living units, excluding any ADUs.","ruleLogic":"If LivingUnitExcludingADUCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Units Excluding ADUs","dataPointName":"LivingUnitExcludingADUCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0022","dataElement":"LivingUnitExcludingADUCount","messageId":"UAD1018","message":"The total number of living units, excluding any ADUs, must be at least 1.","ruleLogic":"If LivingUnitExcludingADUCount < 1","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Units Excluding ADUs (%PV%)","dataPointName":"LivingUnitExcludingADUCount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/","minValue":1},{"uniqueId":"0100.0022","dataElement":"LivingUnitExcludingADUCount","messageId":"UAD1019","message":"The 'Units Excluding ADUs' does not equal the number of living units delivered in the UAD XML.","ruleLogic":"If LivingUnitExcludingADUCount does not equal the number of instances of PROPERTY_UNIT_DETAIL with AccessoryDwellingUnitIndicator = \\"false\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Units Excluding ADUs (%PV%)","dataPointName":"LivingUnitExcludingADUCount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0024","dataElement":"PropertyEstateType","messageId":"UAD1021","message":"Provide 'Property Rights Appraised'.","ruleLogic":"If (PropertyInProjectIndicator = \\"false\\" or ProjectLegalStructureType = \\"Condominium\\"), and PropertyEstateType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Ownership Rights","reportLabel":"Property Rights Appraised","dataPointName":"PropertyEstateType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0053","dataElement":"PropertyEstateTypeOtherDescription","messageId":"UAD1022","message":"Provide a description when 'Property Rights Appraised' = 'Other'.","ruleLogic":"If PropertyEstateType = \\"Other\\" and PropertyEstateTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Ownership Rights","reportLabel":"Property Rights Appraised","dataPointName":"PropertyEstateTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0026","dataElement":"PUDIndicator","messageId":"UAD1023","message":"Indicate whether the property is located within a PUD.","ruleLogic":"If PUDIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Planned Unit Development (PUD)","dataPointName":"PUDIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0028","dataElement":"PropertyGroundLeaseAnnualAmount","messageId":"UAD1024","message":"Provide 'Ground Rent Annual Amount'.","ruleLogic":"If PropertyEstateType = \\"Leasehold\\" and LandOwnedInCommonIndicator = \\"false\\", and PropertyGroundLeaseAnnualAmount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Ownership Rights","reportLabel":"Ground Rent Annual Amount","dataPointName":"PropertyGroundLeaseAnnualAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_GROUND_RENT/"},{"uniqueId":"0100.0029","dataElement":"PropertyGroundLeaseExpirationDate","messageId":"UAD1025","message":"Provide the property ground lease expiration date.","ruleLogic":"If PropertyEstateType = \\"Leasehold\\" and LandOwnedInCommonIndicator = \\"false\\", and PropertyGroundLeaseExpirationDate is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Ownership Rights","reportLabel":"Expires","dataPointName":"PropertyGroundLeaseExpirationDate","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_GROUND_RENT/"},{"uniqueId":"0100.0030","dataElement":"PropertyGroundLeaseRenewableIndicator","messageId":"UAD1026","message":"Indicate whether the property ground lease is renewable.","ruleLogic":"If PropertyEstateType = \\"Leasehold\\" and LandOwnedInCommonIndicator = \\"false\\", and PropertyGroundLeaseRenewableIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Ownership Rights","reportLabel":"Renewable","dataPointName":"PropertyGroundLeaseRenewableIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_GROUND_RENT/"},{"uniqueId":"0100.0033","dataElement":"SpecialTaxAssessmentsIndicator","messageId":"UAD1027","message":"Indicate whether the property has any special tax assessments.","ruleLogic":"If SpecialTaxAssessmentsIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Special Tax Assessments","dataPointName":"SpecialTaxAssessmentsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_TAXES/PROPERTY_TAX/PROPERTY_TAX_DETAIL/"},{"uniqueId":"0100.0034","dataElement":"AllPropertyRightsAppraisedIndicator","messageId":"UAD1028","message":"Indicate whether all ownership rights of the property are included as part of the valuation.","ruleLogic":"If LandOwnedInCommonIndicator = \\"false\\" and AllPropertyRightsAppraisedIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Ownership Rights","reportLabel":"All Rights Included in Appraisal","dataPointName":"AllPropertyRightsAppraisedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"0100.0035","dataElement":"AppraisedIndicator","messageId":"UAD1029","message":"Deliver this indicator as false for each ownership right that is not included in the appraisal. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If AppraisedIndicator is not \\"false\\" in a given instance of REAL_PROPERTY_INTEREST","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"AppraisedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/REAL_PROPERTY_INTERESTS/REAL_PROPERTY_INTEREST/","relatedValues":"PropertyPartialInterestType (%RV1%)"},{"uniqueId":"0100.0036","dataElement":"PropertyPartialInterestType","messageId":"UAD1030","message":"Provide 'Rights Not Included'.","ruleLogic":"If AllPropertyRightsAppraisedIndicator = \\"false\\" and (at least one instance of REAL_PROPERTY_INTEREST is not provided or PropertyPartialInterestType is not provided in a given instance of REAL_PROPERTY_INTEREST)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Ownership Rights","reportLabel":"Rights Not Included","dataPointName":"PropertyPartialInterestType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/REAL_PROPERTY_INTERESTS/REAL_PROPERTY_INTEREST/"},{"uniqueId":"0100.0037","dataElement":"PropertyPartialInterestTypeOtherDescription","messageId":"UAD1031","message":"Provide a description when 'Rights Not Included' = 'Other'.","ruleLogic":"If PropertyPartialInterestType = \\"Other\\" and PropertyPartialInterestTypeOtherDescription is not provided in a given instance of REAL_PROPERTY_INTEREST","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Ownership Rights","reportLabel":"Rights Not Included","dataPointName":"PropertyPartialInterestTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/REAL_PROPERTY_INTERESTS/REAL_PROPERTY_INTEREST/"},{"uniqueId":"0100.0043","dataElement":"@ValuationUseType","messageId":"UAD1032","message":"The subject property has not been identified in the UAD XML. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If an instance of PROPERTY is not provided with @ValuationUseType = \\"SubjectProperty\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@ValuationUseType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/"},{"uniqueId":"0100.0043","dataElement":"@ValuationUseType","messageId":"UAD1033","message":"More than one property has been identified as the subject property. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If more than one instance of PROPERTY has @ValuationUseType = \\"SubjectProperty\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@ValuationUseType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/"},{"uniqueId":"","dataElement":"@ValuationUseType","messageId":"UAD1034","message":"Provide 'ValuationUseType' for each property included in the appraisal. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType is not provided for one or more instances of PROPERTY","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@ValuationUseType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/","relatedValues":"AddressLineText (%RV1%)"},{"uniqueId":"0100.0046","dataElement":"HomeownerResponsibleForExteriorMaintenanceIndicator","messageId":"UAD1035","message":"Provide 'Homeowner Responsible for all E
11xterior Maintenance of Dwelling(s)'.","ruleLogic":"If HomeownerResponsibleForExteriorMaintenanceIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Homeowner Responsible for all Exterior Maintenance of Dwelling(s)","dataPointName":"HomeownerResponsibleForExteriorMaintenanceIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0047","dataElement":"LandOwnedInCommonIndicator","messageId":"UAD1036","message":"Indicate whether the site is owned in common.","ruleLogic":"If LandOwnedInCommonIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Subject Site Owned in Common","dataPointName":"LandOwnedInCommonIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_DETAIL/"},{"uniqueId":"","dataElement":"ValuationAnalysisCategoryType","messageId":"UAD1037","message":"Each ValuationAnalysisCategoryType can only be delivered once. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is more than one instance of VALUATION_COMMENTARY with the same ValuationAnalysisCategoryType enumeration","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ValuationAnalysisCategoryType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/"},{"uniqueId":"0100.0049","dataElement":"ValuationAnalysisCategoryType","messageId":"UAD1038","message":"Provide ValuationAnalysisCategoryType = 'PropertySpecialTaxAssessments' when there are special tax assessments. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If SpecialTaxAssessmentsIndicator = \\"true\\", and there is no instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"PropertySpecialTaxAssessments\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ValuationAnalysisCategoryType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/"},{"uniqueId":"0100.0050","dataElement":"ValuationCommentText","messageId":"UAD1039","message":"Provide 'Description of Special Tax Assessments and Impact to Value / Marketability'.","ruleLogic":"If SpecialTaxAssessmentsIndicator = \\"true\\" and ValuationCommentText is not provided in the instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"PropertySpecialTaxAssessments\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Description of Special Tax Assessments and Impact to Value / Marketability","dataPointName":"ValuationCommentText","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/","relatedValues":"ValuationAnalysisCategoryType (PropertySpecialTaxAssessments)"},{"uniqueId":"0100.0054","dataElement":"NativeAmericanLandsIndicator","messageId":"UAD1040","message":"Indicate whether the property is located on Native American lands.","ruleLogic":"If NativeAmericanLandsIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Property on Native American Lands","dataPointName":"NativeAmericanLandsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0059","dataElement":"AccessoryDwellingUnitTotalCount","messageId":"UAD1041","message":"Provide the total number of ADUs in the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and AccessoryDwellingUnitTotalCount is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"AccessoryDwellingUnitTotalCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0065","dataElement":"PropertyInProjectIndicator","messageId":"UAD1042","message":"Indicate whether the property is located in a project.","ruleLogic":"If PropertyInProjectIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Condominium; Cooperative; Condop","dataPointName":"PropertyInProjectIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0100.0067","dataElement":"ParcelsLegalDescription","messageId":"UAD1043","message":"Provide the legal description or an image of the legal description.","ruleLogic":"If ImageCategoryType = \\"LegalDescription\\" is not provided in any instance of IMAGE, and ParcelsLegalDescription is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Legal Description","reportLabel":"{No Label}","dataPointName":"ParcelsLegalDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PARCEL_SUMMARY/PARCEL_SUMMARY_DETAIL/"},{"uniqueId":"0100.0068","dataElement":"ImprovementType","messageId":"UAD1044","message":"Indicate whether the structure is a 'Dwelling' or 'Outbuilding'.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and ImprovementType is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Rental Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImprovementType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"0200.0015","dataElement":"PropertyAmenityExistsIndicator","messageId":"UAD1045","message":"Indicate whether the property has any amenities.","ruleLogic":"If PropertyAmenityExistsIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property Amenities","reportSubsection":"{No Subsection}","reportLabel":"{No Label}","dataPointName":"PropertyAmenityExistsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0200.0053","dataElement":"SubjectPropertyAmenitiesDefectsExistIndicator","messageId":"UAD1046","message":"Indicate whether the subject property amenities have any defects, damages, or deficiencies.","ruleLogic":"If PropertyAmenityExistsIndicator = \\"true\\" and SubjectPropertyAmenitiesDefectsExistIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property Amenities","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"{No Label}","dataPointName":"SubjectPropertyAmenitiesDefectsExistIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0300.0009","dataElement":"ImprovementType","messageId":"UAD1047","message":"Indicate whether the structure is a 'Dwelling' or 'Outbuilding'.","ruleLogic":"If ImprovementType is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"ImprovementType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"0300.0009","dataElement":"ImprovementType","messageId":"UAD1048","message":"At least one structure on the property must be identified as a 'Dwelling'.","ruleLogic":"If ImprovementType is not \\"Dwelling\\" in at least one instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"{No Label}","dataPointName":"ImprovementType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/","minValue":1},{"uniqueId":"0300.0010","dataElement":"NewConstructionIndicator","messageId":"UAD1049","message":"Indicate whether the property is new construction.","ruleLogic":"If NewConstructionIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"New Construction","dataPointName":"NewConstructionIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0300.0011","dataElement":"PropertyStructureBuiltYear","messageId":"UAD1050","message":"Provide 'Year Built' for each dwelling.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and PropertyStructureBuiltYear is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Year Built","dataPointName":"PropertyStructureBuiltYear","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"0300.0010","dataElement":"NewConstructionIndicator","messageId":"UAD1051","message":"The property can only be considered as new construction when 'Year Built' for the dwelling(s) is within 1 year of the 'Effective Date of Appraisal'.","ruleLogic":"If NewConstructionIndicator = \\"true\\", and PropertyStructureBuiltYear is not the same year, or within 1 year of the AppraisalReportEffectiveDate, for one or more instances of IMPROVEMENT_DETAIL with ImprovementType = \\"Dwelling\\".","severity":"Warning","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"New Construction","dataPointName":"NewConstructionIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0300.0011","dataElement":"PropertyStructureBuiltYear","messageId":"UAD1052","message":"The 'Year Built' is prior to 1800. Please check for accuracy.","ruleLogic":"If PropertyStructureBuiltYear < 1800 in a given instance of IMPROVEMENT_DETAIL with ImprovementType = \\"Dwelling\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Year Built (%PV%)","dataPointName":"PropertyStructureBuiltYear (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/","minValue":1800},{"uniqueId":"0300.0011","dataElement":"PropertyStructureBuiltYear","messageId":"UAD1053","message":"The 'Year Built' for a dwelling cannot be after 'Effective Date of Appraisal'.","ruleLogic":"If ((ExteriorConditionRatingCode = \\"C1\\" and PropertyStructureBuiltYear > year of (AppraisalReportEffectiveDate) + 2 years ) or (ExteriorConditionRatingCode <> \\"C1\\" and PropertyStructureBuiltYear > year of (AppraisalReportEffectiveDate)) in a given instance of IMPROVEMENT_DETAIL with ImprovementType = \\"Dwelling\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Year Built (%PV%)","dataPointName":"PropertyStructureBuiltYear (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"0300.0012","dataElement":"PropertyStructureBuiltYearEstimatedIndicator","messageId":"UAD1054","message":"For each dwelling indicate whether the 'Year Built' was estimated.","ruleLogic":"If ImprovementType = \\"Dwelling\\", and PropertyStructureBuiltYearEstimatedIndicator is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Year Built","dataPointName":"PropertyStructureBuiltYearEstimatedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"0300.0023","dataElement":"HeatingSystemExistsIndicator","messageId":"UAD1055","message":"Indicate whether the structure has a permanent heating system.","ruleLogic":"If ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\", and LivingUnitCount = 0, and HeatingSystemExistsIndicator is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Outbuilding","reportSubsection":"Detail","reportLabel":"Heating","dataPointName":"HeatingSystemExistsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/","relatedValues":"OutbuildingType (%RV1%)"},{"uniqueId":"0300.0025","dataElement":"OutbuildingType","messageId":"UAD1056","message":"Provide the intended functional design for each outbuilding (e.g., barn, standalone ADU, pool house).","ruleLogic":"If ImprovementType = \\"Outbuilding\\" and OutbuildingType is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Outbuilding","reportSubsection":"{No Subsection}","reportLabel":"{No Label}","dataPointName":"OutbuildingType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"0300.0026","dataElement":"OutbuildingTypeOtherDescription","messageId":"UAD1057","message":"Provide a description when 'Outbuilding Type' = 'Other'.","ruleLogic":"If OutbuildingType = \\"Other\\" and OutbuildingTypeOtherDescription is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Outbuilding","reportSubsection":"{No Subsection}","reportLabel":"{No Label}","dataPointName":"OutbuildingTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"0300.0028","dataElement":"UtilityType","messageId":"UAD1058","message":"The type of utility(s) that exist in the outbuilding must be included. Select 'None' if there are no utilities.","ruleLogic":"If ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\", and (at least one instance of OUTBUILDING_UTILITY is not provided or UtilityType is not provided in a given instance of OUTBUILDING_UTILITY)","severity":"Warning","propertyAffected":"Subject","reportSection":"Outbuilding","reportSubsection":"Detail","reportLabel":"Utilities","dataPointName":"UtilityType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/OUTBUILDING/OUTBUILDING_UTILITIES/OUTBUILDING_UTILITY/","relatedValues":"OutbuildingType (%RV1%)"},{"uniqueId":"0300.0029","dataElement":"UtilityTypeOtherDescription","messageId":"UAD1059","message":"Provide a description when utility type = 'Other'.","ruleLogic":"If ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and UtilityType = \\"Other\\" and UtilityTypeOtherDescription is not provided in a given instance of OUTBUILDING_UTILITY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Outbuilding","reportSubsection":"Detail","reportLabel":"Utilities","dataPointName":"UtilityTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/OUTBUILDING/OUTBUILDING_UTILITIES/OUTBUILDING_UTILITY/","relatedValues":"OutbuildingType (%RV1%)"},{"uniqueId":"0300.0032","dataElement":"StructuralDesignType","messageId":"UAD1060","message":"Provide 'Structure Design' (e.g., Low-rise, Mid-rise, High-rise, Rowhouse / Townhouse, Semi-Detached) for each dwelling.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and AttachmentType = \\"Attached\\", and StructuralDesignType is not provided in ARCHITECTURAL_DESIGN in a given instance of IMPROVEMENT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Structure Design","dataPointName":"StructuralDesignType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/ARCHITECTURAL_DESIGN/"},{"uniqueId":"0300.0033","dataElement":"StructuralDesignTypeOtherDescription","messageId":"UAD1061","message":"Provide a description when 'Structure Design' = 'Other'.","ruleLogic":"I
11f StructuralDesignType = \\"Other\\" and StructuralDesignTypeOtherDescription is not provided in a given instance of ARCHITECTURAL_DESIGN","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Structure Design","dataPointName":"StructuralDesignTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/ARCHITECTURAL_DESIGN/"},{"uniqueId":"0300.0034","dataElement":"ConstructionMethodType","messageId":"UAD1062","message":"Provide 'Construction Method' (e.g., Site Built, Manufactured, Modular) for each dwelling.","ruleLogic":"If ((ImprovementType = \\"Dwelling\\" and AttachmentType = \\"Detached\\") or (ImprovementType = \\"Dwelling\\" and AttachmentType = \\"Attached\\" and StructuralDesignType = \\"RowhouseTownhouse\\" or \\"SemiDetached\\" or \\"Other\\")), and (at least one instance of CONSTRUCTION_METHOD is not provided or ConstructionMethodType is not provided in a given instance of CONSTRUCTION_METHOD)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Construction Method","dataPointName":"ConstructionMethodType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/CONSTRUCTION_METHODS/CONSTRUCTION_METHOD/"},{"uniqueId":"0300.0035","dataElement":"ConstructionMethodTypeOtherDescription","messageId":"UAD1063","message":"Provide a description when 'Construction Method' = 'Other'.","ruleLogic":"If ConstructionMethodType = \\"Other\\" and ConstructionMethodTypeOtherDescription is not provided in a given instance of CONSTRUCTION_METHOD","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Construction Method","dataPointName":"ConstructionMethodTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/CONSTRUCTION_METHODS/CONSTRUCTION_METHOD/"},{"uniqueId":"0300.0041","dataElement":"EstimatedRemainingEconomicLifeYearsCount","messageId":"UAD1064","message":"Provide the estimated number of years of the dwelling's remaining useful life.","ruleLogic":"If CostApproachIndicator = \\"true\\" and ImprovementType = \\"Dwelling\\" and EstimatedRemainingEconomicLifeYearsCount is not provided in a given instance of STRUCTURE_ANALYSIS_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Cost Approach","reportSubsection":"Depreciated Cost - Dwelling","reportLabel":"Remaining Economic Life","dataPointName":"EstimatedRemainingEconomicLifeYearsCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_ANALYSES/STRUCTURE_ANALYSIS/STRUCTURE_ANALYSIS_DETAIL/"},{"uniqueId":"0300.0055","dataElement":"ImprovementComponentType","messageId":"UAD1065","message":"The exterior feature type must be included. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and ImprovementComponentType is not provided in a given instance of STRUCTURE_COMPONENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"ImprovementComponentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/STRUCTURE_COMPONENT_DETAIL/"},{"uniqueId":"0300.0056","dataElement":"ImprovementComponentTypeOtherDescription","messageId":"UAD1066","message":"Provide a description when 'Feature Type' = 'Other'.","ruleLogic":"If ImprovementComponentType = \\"Other\\" and ImprovementComponentTypeOtherDescription is not provided in a given instance of STRUCTURE_COMPONENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"ImprovementComponentTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/STRUCTURE_COMPONENT_DETAIL/"},{"uniqueId":"0300.0055","dataElement":"ImprovementComponentType","messageId":"UAD1067","message":"Provide the foundation details (e.g., style, material) for the structure.","ruleLogic":"If ImprovementType = \\"Dwelling\\" AND HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and there is no instance of STRUCTURE_COMPONENT_DETAIL with ImprovementComponentType = \\"Foundation\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"ImprovementComponentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/STRUCTURE_COMPONENT_DETAIL/"},{"uniqueId":"0300.0044","dataElement":"FoundationMaterialType","messageId":"UAD1068","message":"Provide the materials used for the foundation.","ruleLogic":"If ImprovementType = \\"Dwelling\\" AND HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and ImprovementComponentType = \\"Foundation\\" and (at least one instance of FOUNDATION_MATERIAL is not provided or FoundationMaterialType is not provided in a given instance of FOUNDATION_MATERIAL)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"FoundationMaterialType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/FOUNDATIONS/FOUNDATION/FOUNDATION_MATERIALS/FOUNDATION_MATERIAL/"},{"uniqueId":"0300.0045","dataElement":"FoundationMaterialTypeOtherDescription","messageId":"UAD1069","message":"Provide a description when foundation material = 'Other'.","ruleLogic":"If FoundationMaterialType = \\"Other\\" and FoundationMaterialTypeOtherDescription is not provided in a given instance of FOUNDATION_MATERIAL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"FoundationMaterialTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/FOUNDATIONS/FOUNDATION/FOUNDATION_MATERIALS/FOUNDATION_MATERIAL/"},{"uniqueId":"0300.0046","dataElement":"FoundationType","messageId":"UAD1070","message":"Provide the type of foundation.","ruleLogic":"If ImprovementType = \\"Dwelling\\" AND HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and ImprovementComponentType = \\"Foundation\\" and (at least one instance of FOUNDATION_STYLE is not provided or FoundationType is not provided in a given instance of FOUNDATION_STYLE)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"FoundationType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/FOUNDATIONS/FOUNDATION/FOUNDATION_STYLES/FOUNDATION_STYLE/"},{"uniqueId":"0300.0047","dataElement":"FoundationTypeOtherDescription","messageId":"UAD1071","message":"Provide a description when foundation type = 'Other'.","ruleLogic":"If FoundationType = \\"Other\\" and FoundationTypeOtherDescription is not provided in a given instance of FOUNDATION_STYLE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"FoundationTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/FOUNDATIONS/FOUNDATION/FOUNDATION_STYLES/FOUNDATION_STYLE/"},{"uniqueId":"0300.0055","dataElement":"ImprovementComponentType","messageId":"UAD1072","message":"Provide the roof details (e.g., estimated age, material) for the structure.","ruleLogic":"If ImprovementType = \\"Dwelling\\" AND HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and there is no instance of STRUCTURE_COMPONENT_DETAIL with ImprovementComponentType = \\"Roof\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"ImprovementComponentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/STRUCTURE_COMPONENT_DETAIL/"},{"uniqueId":"0300.0048","dataElement":"RoofEstimatedAgeRangeType","messageId":"UAD1073","message":"Provide the estimated age of the roof.","ruleLogic":"If ImprovementComponentType = \\"Roof\\" and RoofEstimatedAgeRangeType is not provided in ROOF_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"RoofEstimatedAgeRangeType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/ROOF/ROOF_DETAIL/"},{"uniqueId":"0300.0049","dataElement":"RoofObservableIndicator","messageId":"UAD1074","message":"Indicate whether the roof is observable.","ruleLogic":"If ImprovementComponentType = \\"Roof\\" and RoofObservableIndicator is not provided in ROOF_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"RoofObservableIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/ROOF/ROOF_DETAIL/"},{"uniqueId":"0300.0050","dataElement":"RoofMaterialType","messageId":"UAD1075","message":"Provide the roof material.","ruleLogic":"If ImprovementType = \\"Dwelling\\" AND HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and ImprovementComponentType = \\"Roof\\" and (at least one instance of ROOF_MATERIAL is not provided or RoofMaterialType is not provided in a given instance of ROOF_MATERIAL)","severity":"Warning","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"RoofMaterialType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/ROOF/ROOF_MATERIALS/ROOF_MATERIAL/"},{"uniqueId":"0300.0051","dataElement":"RoofMaterialTypeOtherDescription","messageId":"UAD1076","message":"Provide a description when roof material = 'Other'.","ruleLogic":"If RoofMaterialType = \\"Other\\" and RoofMaterialTypeOtherDescription is not provided in a given instance of ROOF_MATERIAL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"RoofMaterialTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/ROOF/ROOF_MATERIALS/ROOF_MATERIAL/"},{"uniqueId":"0300.0052","dataElement":"ImprovementComponentTypeAdditionalDescription","messageId":"UAD1077","message":"Provide additional description for the exterior feature being referenced.","ruleLogic":"If ImprovementType = \\"Dwelling\\", and HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\", and ImprovementComponentType = \\"Windows\\" or \\"Other\\", and ImprovementComponentTypeAdditionalDescription is not provided in a given instance of STRUCTURE_COMPONENT_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"ImprovementComponentTypeAdditionalDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/STRUCTURE_COMPONENT_DETAIL/","relatedValues":"ImprovementComponentType (%RV1%)"},{"uniqueId":"0300.0054","dataElement":"ImprovementComponentConditionStatusType","messageId":"UAD1078","message":"Provide the 'Condition Status'.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" and ImprovementComponentType <> \\"Roof\\"), or (ImprovementType = \\"Dwelling\\" and ImprovementComponentType = \\"Roof\\" and RoofObservableIndicator = \\"true\\"), and ImprovementComponentConditionStatusType is not provided in a given instance of STRUCTURE_COMPONENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Condition Status","dataPointName":"ImprovementComponentConditionStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/STRUCTURE_COMPONENT_DETAIL/","relatedValues":"ImprovementComponentType (%RV1%)"},{"uniqueId":"0300.0055","dataElement":"ImprovementComponentType","messageId":"UAD1079","message":"Provide the exterior walls and trim details (e.g., material) for the structure.","ruleLogic":"If ImprovementType = \\"Dwelling\\" AND HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and there is no instance of STRUCTURE_COMPONENT_DETAIL with ImprovementComponentType = \\"'ExteriorWallsAndTrim\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"ImprovementComponentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/STRUCTURE_COMPONENT_DETAIL/"},{"uniqueId":"0300.0098","dataElement":"WallMaterialType","messageId":"UAD1080","message":"Provide the exterior wall material type.","ruleLogic":"If ImprovementType = \\"Dwelling\\" AND HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and ImprovementComponentType = \\"ExteriorWallsAndTrim\\" and (at least one instance of EXTERIOR_WALL is not provided or WallMaterialType is not provided in a given instance of EXTERIOR_WALL)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"WallMaterialType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/EXTERIOR_WALLS/EXTERIOR_WALL/"},{"uniqueId":"0300.0099","dataElement":"WallMaterialTypeOtherDescription","messageId":"UAD1081","message":"Provide a description when exterior wall material = 'Other'.","ruleLogic":"If WallMaterialType = \\"Other\\" and WallMaterialTypeOtherDescription is not provided in a given instance of EXTERIOR_WALL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"WallMaterialTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_COMPONENTS/STRUCTURE_COMPONENT/EXTERIOR_WALLS/EXTERIOR_WALL/"},{"uniqueId":"0300.0059","dataElement":"RowhouseTownhouseEndUnitIndicator","messageId":"UAD1082","message":"Indicate whether the rowhouse / townhouse is an end unit.","ruleLogic":"If StructuralDesignType = \\"RowhouseTownhouse\\" and RowhouseTownhouseEndUnitIndicator is not provided in a given instance of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Townhouse End Unit","dataPointName":"RowhouseTownhouseEndUnitIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0300.0060","dataElement":"StructureAreaMeasure","messageId":"UAD1083","message":"Provide the 'Gross Building Area' of the outbuilding.","ruleLogic":"If ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator =
11 \\"true\\", and StructureAreaMeasure is not provided in a given instance of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Outbuilding","reportSubsection":"{No Subsection}","reportLabel":"Gross Building Area","dataPointName":"StructureAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/","relatedValues":"OutbuildingType (%RV1%)"},{"uniqueId":"0300.0063","dataElement":"LivingUnitCount","messageId":"UAD1084","message":"Provide the number of living units in the structure.","ruleLogic":"If ImprovementType = \\"Dwelling\\" or \\r\\n(ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\"), and LivingUnitCount is not provided in a given instance of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"LivingUnitCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0300.0063","dataElement":"LivingUnitCount","messageId":"UAD1085","message":"The number of living units cannot be 0 for any dwelling.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and LivingUnitCount = 0 in a given instance of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Subject Property Units in Structure","dataPointName":"LivingUnitCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/","minValue":1},{"uniqueId":"0300.0063","dataElement":"LivingUnitCount","messageId":"UAD1086","message":"The number of living units in the structure does not equal the number of units delivered in the UAD XML for the structure. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"For each IMPROVEMENT, if LivingUnitCount <> the number of instances of PROPERTY_UNIT","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"LivingUnitCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0300.0064","dataElement":"StoriesCount","messageId":"UAD1087","message":"Provide the number of 'Floors in Building'.","ruleLogic":"If StructuralDesignType = \\"Highrise\\" or \\"Midrise\\", and StoriesCount is not provided in a given instance of STRUCTURE_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Floors in Building","dataPointName":"StoriesCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0300.0074","dataElement":"FactoryBuiltCertificationExaminedIndicator","messageId":"UAD1088","message":"Indicate whether the factory-built certification has been examined for an on-frame modular or modular home.","ruleLogic":"If ImprovementType = \\"Dwelling\\", and ConstructionMethodType = \\"Modular\\" or \\"OnFrameModular\\", and FactoryBuiltCertificationExaminedIndicator is not provided in a given instance of STRUCTURE_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Factory Built Certification","dataPointName":"FactoryBuiltCertificationExaminedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0300.0088","dataElement":"HeatingSystemType","messageId":"UAD1089","message":"Provide the heating system type. Select 'None' if there is no heating system.","ruleLogic":"If ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and LivingUnitCount > 0), and (at least one instance of HEATING_SYSTEM is not provided or HeatingSystemType is not provided in a given instance of HEATING_SYSTEM)","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"System","dataPointName":"HeatingSystemType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/SYSTEM/HEATING_SYSTEMS/HEATING_SYSTEM/"},{"uniqueId":"0300.0089","dataElement":"HeatingSystemTypeOtherDescription","messageId":"UAD1090","message":"Provide a description when heating system type = 'Other'.","ruleLogic":"If HeatingSystemType = \\"Other\\" and HeatingSystemTypeOtherDescription is not provided in a given instance of HEATING_SYSTEM","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"System","dataPointName":"HeatingSystemTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/SYSTEM/HEATING_SYSTEMS/HEATING_SYSTEM/"},{"uniqueId":"0300.0101","dataElement":"StructureIdentifier","messageId":"UAD1091","message":"When 'Units Excluding ADUs' is more than 1, the structure identifier must be provided for each dwelling.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and LivingUnitExcludingADUCount > 1, and StructureIdentifier is not provided in a given instance of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"{No Label}","dataPointName":"StructureIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0300.0101","dataElement":"StructureIdentifier","messageId":"UAD1092","message":"The structure identifier must be unique.","ruleLogic":"If StructureIdentifier is not unique across all instances of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"{No Label}","dataPointName":"StructureIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0300.0065","dataElement":"StructureIdentifier","messageId":"UAD1093","message":"The structure identifier must be unique.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and StructureIdentifier is not unique across all instances of IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL for a given comp","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s); Exterior Quality and Condition; Interior Quality and Condition","reportLabel":"Structure ID | Unit ID","dataPointName":"StructureIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0300.0111","dataElement":"OutbuildingDefectsExistIndicator","messageId":"UAD1094","message":"Indicate whether the outbuilding has any defects, damages, or deficiencies.","ruleLogic":"If ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and OutbuildingDefectsExistIndicator is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Outbuilding","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"{No Label}","dataPointName":"OutbuildingDefectsExistIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/","relatedValues":"OutbuildingType (%RV1%)"},{"uniqueId":"0300.0112","dataElement":"StructureExcludingVehicleStorageAndADUFinishedAreaMeasure","messageId":"UAD1095","message":"Provide the finished area of the outbuilding, even if the value is 0.","ruleLogic":"If ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and StructureExcludingVehicleStorageAndADUFinishedAreaMeasure is not provided in a given instance of STRUCTURE_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Outbuilding","reportSubsection":"Detail","reportLabel":"Total Area","dataPointName":"StructureExcludingVehicleStorageAndADUFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/","relatedValues":"OutbuildingType (%RV1%)"},{"uniqueId":"0300.0113","dataElement":"StructureExcludingVehicleStorageAndADUUnfinishedAreaMeasure","messageId":"UAD1096","message":"Provide the unfinished area of the outbuilding, even if the value is 0.","ruleLogic":"If ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and StructureExcludingVehicleStorageAndADUUnfinishedAreaMeasure is not provided in a given instance of STRUCTURE_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Outbuilding","reportSubsection":"Detail","reportLabel":"Total Area","dataPointName":"StructureExcludingVehicleStorageAndADUUnfinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/","relatedValues":"OutbuildingType (%RV1%)"},{"uniqueId":"0300.0114","dataElement":"NonContinuousFinishedAreaIndicator","messageId":"UAD1097","message":"Indicate whether the dwelling has any non-continuous finished area (e.g., a finished office above, below, or behind an attached garage that cannot be accessed from within any living unit).","ruleLogic":"If ImprovementType = \\"Dwelling\\" and LivingUnitExcludingADUCount = 1, and NonContinuousFinishedAreaIndicator is not provided in in a given instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Noncontinuous Finished Area","dataPointName":"NonContinuousFinishedAreaIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"0300.0116","dataElement":"CoreHeatingSystemBelowGradeIndicator","messageId":"UAD1098","message":"Indicate whether the core heating system for dwelling is located below grade.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and HeatingSystemType <> \\"None\\", and CoreHeatingSystemBelowGradeIndicator is not provided in SYSTEM_DETAIL for a given instance of IMPROVEMENT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Mechanical System Details","reportLabel":"Core Heating System Below Grade","dataPointName":"CoreHeatingSystemBelowGradeIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/SYSTEM/SYSTEM_DETAIL/"},{"uniqueId":"0300.0117","dataElement":"FrontDoorApproximateElevationRangeType","messageId":"UAD1099","message":"Provide the approximate elevation range from grade level to the bottom of the front entrance door of the dwelling.","ruleLogic":"If FrontDoorApproximateElevationRangeType is not provided in STRUCTURE_DETAIL for a given instance of IMRPOVEMENT with ImprovementType = \\"Dwelling\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"{No Subsection}","reportLabel":"Front Door Elevation","dataPointName":"FrontDoorApproximateElevationRangeType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0500.0005","dataElement":"ManufacturedHomeFinancingProgramEligibilityType","messageId":"UAD1100","message":"The manufactured home certification program name (e.g., Fannie Mae MH Advantage, Freddie Mac CHOICEHome) must be included when the manufactured home certification program identifier has been delivered.","ruleLogic":"If ManufacturedHomeFinancingProgramEligibilityIdentifier is provided and ManufacturedHomeFinancingProgramEligibilityType is not provided in a given instance of MANUFACTURED_HOME_FINANCING_PROGRAM","severity":"Warning","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"Manufactured Home Certification Program","reportLabel":"Certification","dataPointName":"ManufacturedHomeFinancingProgramEligibilityType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_FINANCING_PROGRAMS/MANUFACTURED_HOME_FINANCING_PROGRAM/","relatedValues":"ManufacturedHomeFinancingProgramEligibilityIdentifier (%RV1%)"},{"uniqueId":"0500.0004","dataElement":"ManufacturedHomeFinancingProgramEligibilityIdentifier","messageId":"UAD1101","message":"The manufactured home certification program identifier must be included when the manufactured home certification program name (e.g., Fannie Mae MH Advantage, Freddie Mac CHOICEHome) has been delivered.","ruleLogic":"If ManufacturedHomeFinancingProgramEligibilityType is provided and ManufacturedHomeFinancingProgramEligibilityIdentifier is not provided in a given instance of MANUFACTURED_HOME_FINANCING_PROGRAM","severity":"Warning","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"Manufactured Home Certification Program","reportLabel":"Identifier","dataPointName":"ManufacturedHomeFinancingProgramEligibilityIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_FINANCING_PROGRAMS/MANUFACTURED_HOME_FINANCING_PROGRAM/","relatedValues":"ManufacturedHomeFinancingProgramEligibilityType (%RV1%)"},{"uniqueId":"0500.0006","dataElement":"ManufacturedHomeFinancingProgramEligibilityTypeOtherDescription","messageId":"UAD1102","message":"Provide a description when 'Manufactured Home Certification Program' = 'Other'.","ruleLogic":"If ManufacturedHomeFinancingProgramEligibilityType = \\"Other\\" and ManufacturedHomeFinancingProgramEligibilityTypeOtherDescription is not provided in a given instance of MANUFACTURED_HOME_FINANCING_PROGRAM","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"Manufactured Home Certification Program","reportLabel":"Certification","dataPointName":"ManufacturedHomeFinancingProgramEligibilityTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_FINANCING_PROGRAMS/MANUFACTURED_HOME_FINANCING_PROGRAM/"},{"uniqueId":"0500.0007","dataElement":"ManufacturedHomeAttachedToFoundationIndicator","messageId":"UAD1103","message":"Indicate whether the manufactured home is attached to a permanent foundation.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingType = \\"ManufacturedHome\\"), and ManufacturedHomeAttachedToFoundationIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"Attached to Permanent Foundation","dataPointName":"ManufacturedHomeAttachedToFoundationIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0500.0008","dataElement":"ManufacturedHomeHitchWheelsAxlesRemovedIndicator","messageId":"UAD1104","message":"Indicate whether the towing hitch, wheels and axles have been removed from the frame of the manufactured home.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingType = \\"ManufacturedHome\\" and OutbuildingRealPropertyIndicator = \\"true\\" and LivingUnitCount > 0), and ManufacturedHomeHitchWheelsAxlesRemovedIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Towing Hitch, Wheels, Axles Removed","dataPointName":"ManufacturedHomeHitchWheelsAxlesRemovedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0500.0009","dataElement":"ManufacturedHomeHUDCertificateLabelI
11ndicator","messageId":"UAD1105","message":"Indicate whether the HUD certification label is present for each section of the manufactured home.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingType = \\"ManufacturedHome\\" and OutbuildingRealPropertyIndicator = \\"true\\" and LivingUnitCount > 0), and ManufacturedHomeHUDCertificateLabelIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"HUD Certification Label","reportLabel":"Label Present for All Sections","dataPointName":"ManufacturedHomeHUDCertificateLabelIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0500.0010","dataElement":"ManufacturedHomeHUDDataPlateAttachedIndicator","messageId":"UAD1106","message":"Indicate whether the HUD data plate is attached to the manufactured home.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingType = \\"ManufacturedHome\\" and OutbuildingRealPropertyIndicator = \\"true\\" and LivingUnitCount > 0), and ManufacturedHomeHUDDataPlateAttachedIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"HUD Data Plate","reportLabel":"HUD Data Plate Attached","dataPointName":"ManufacturedHomeHUDDataPlateAttachedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0011","dataElement":"ManufacturedHomeInstalledDate","messageId":"UAD1107","message":"Provide the year (YYYY format) in which the manufactured home was installed.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\", and ManufacturedHomeInstalledDate is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Year Installed","dataPointName":"ManufacturedHomeInstalledDate","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0013","dataElement":"ManufacturedHomeInvoiceReasonableIndicator","messageId":"UAD1108","message":"Indicate whether the content of the manufacturer's or retailer's invoice appears reasonable.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethod = \\"Manufactured\\" and (ManufacturedHomeRetailerInvoiceReviewedIndicator = \\"true\\" or ManufacturedHomeInvoiceReviewedIndicator = \\"true\\") and ManufacturedHomeInvoiceReasonableIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"Invoice Information","reportLabel":"Invoice(s) Appear Reasonable","dataPointName":"ManufacturedHomeInvoiceReasonableIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0014","dataElement":"ManufacturedHomeInvoiceReviewedIndicator","messageId":"UAD1109","message":"Indicate whether the Appraiser has reviewed and analyzed the manufactured home manufacturer's invoice.","ruleLogic":"If ImprovementType = \\"Dwelling\\", and ConstructionMethodType = \\"Manufactured\\", and NewConstructionIndicator = \\"true\\", and ManufacturedHomeInvoiceReviewedIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"Invoice Information","reportLabel":"Manufacturer's Invoice Reviewed","dataPointName":"ManufacturedHomeInvoiceReviewedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0016","dataElement":"ManufacturedHomeManufactureDate","messageId":"UAD1110","message":"Provide the date the manufactured home was built as noted on the HUD data plate.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethod = \\"Manufactured\\" and ManufacturedHomeHUDDataPlateAttachedIndicator = \\"true\\", and ManufacturedHomeManufactureDate is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"HUD Data Plate","reportLabel":"Date of Manufacture","dataPointName":"ManufacturedHomeManufactureDate","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0016","dataElement":"ManufacturedHomeManufactureDate","messageId":"UAD1111","message":"The 'Date of Manufacture' is prior to 1976. Please check for accuracy.","ruleLogic":"If ManufacturedHomeManufactureDate < 1976 in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"HUD Data Plate","reportLabel":"Date of Manufacture (%PV%)","dataPointName":"ManufacturedHomeManufactureDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/","minValue":1976},{"uniqueId":"0500.0020","dataElement":"ManufacturedHomeModificationIndicator","messageId":"UAD1113","message":"Indicate whether any modifications, attachments or additions (e.g., deck, porch, garage) have been made to the manufactured home.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingType = \\"ManufacturedHome\\" and OutbuildingRealPropertyIndicator = \\"true\\" and LivingUnitCount > 0), and ManufacturedHomeModificationIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Have there been any modifications, attachments or additions that rely on or have altered the original structure for support?","dataPointName":"ManufacturedHomeModificationIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0500.0021","dataElement":"ManufacturedHomeMovedAfterOriginalInstallationIndicator","messageId":"UAD1114","message":"Indicate whether the manufactured home has been moved to a different location than the one on which it was originally installed.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\", and ManufacturedHomeMovedAfterOriginalInstallationIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Moved Since Original Installation","dataPointName":"ManufacturedHomeMovedAfterOriginalInstallationIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0022","dataElement":"ManufacturedHomePurchasedFromRetailerIndicator","messageId":"UAD1115","message":"Indicate whether the manufactured home was purchased from a retailer.","ruleLogic":"If ImprovementType = \\"Dwelling\\", and ConstructionMethodType = \\"Manufactured\\", and NewConstructionIndicator = \\"true\\", and ManufacturedHomePurchasedFromRetailerIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"Invoice Information","reportLabel":"Purchased from Retailer","dataPointName":"ManufacturedHomePurchasedFromRetailerIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0023","dataElement":"ManufacturedHomeRetailerInvoiceReviewedIndicator","messageId":"UAD1116","message":"Indicate whether the Appraiser has reviewed and analyzed the manufactured home retailer's invoice.","ruleLogic":"If ImprovementType = \\"Dwelling\\", and ConstructionMethod = \\"Manufactured\\", and ManufacturedHomePurchasedFromRetailerIndicator = \\"true\\", and ManufacturedHomeRetailerInvoiceReviewedIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"Invoice Information","reportLabel":"Retailer's Invoice Reviewed","dataPointName":"ManufacturedHomeRetailerInvoiceReviewedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0028","dataElement":"RoofLoadZoneCode","messageId":"UAD1117","message":"Provide the 'HUD Roof Load Zone'.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethod = \\"Manufactured\\" and ManufacturedHomeHUDDataPlateAttachedIndicator = \\"true\\", and RoofLoadZoneCode is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"HUD Data Plate","reportLabel":"HUD Roof Load Zone","dataPointName":"RoofLoadZoneCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0030","dataElement":"SkirtingExistsIndicator","messageId":"UAD1118","message":"Indicate whether skirting exists for the manufactured home.","ruleLogic":"If ImprovementType = \\"Dwelling\\", and ConstructionMethodType = \\"Manufactured\\", and SkirtingExistsIndicator is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Skirting","dataPointName":"SkirtingExistsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0031","dataElement":"ThermalZoneCode","messageId":"UAD1119","message":"Provide the 'HUD Thermal Zone'.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethod = \\"Manufactured\\" and ManufacturedHomeHUDDataPlateAttachedIndicator = \\"true\\", and ThermalZoneCode is not provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"HUD Data Plate","reportLabel":"HUD Thermal Zone","dataPointName":"ThermalZoneCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0033","dataElement":"WindZoneCode","messageId":"UAD1120","message":"Provide the 'HUD W
11ind Zone'.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethod = \\"Manufactured\\" and ManufacturedHomeHUDDataPlateAttachedIndicator = \\"true\\", and WindZoneCode is not provided in a given instance of MANUFACTURED_HOME_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"HUD Data Plate","reportLabel":"HUD Wind Zone","dataPointName":"WindZoneCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0500.0035","dataElement":"ManufacturedHomeModificationType","messageId":"UAD1121","message":"Provide the type of attachment, modification or addition (e.g., deck, porch, garage) made to the manufactured home.","ruleLogic":"If ((ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\" and ManufacturedHomeModificationIndicator = \\"true\\") \\r\\nor (ImprovementType = \\"Outbuilding\\" and OutbuildingType = \\"ManufacturedHome\\" and OutbuildingRealPropertyIndicator = \\"true\\" and LivingUnitCount > 0 and ManufacturedHomeModificationIndicator = \\"true\\")) and (at least one instance of MANUFACTURED_HOME_MODIFICATION is not provided or ManufacturedHomeModificationType is not provided in a given instance of MANUFACTURED_HOME_MODIFICATION)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Modification, Attachment, or Addition","dataPointName":"ManufacturedHomeModificationType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_MODIFICATIONS/MANUFACTURED_HOME_MODIFICATION/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0500.0036","dataElement":"ManufacturedHomeModificationTypeOtherDescription","messageId":"UAD1122","message":"Provide a description when 'Modification, Attachment, or Addition' = 'Other'.","ruleLogic":"If ManufacturedHomeModificationType = \\"Other\\" and ManufacturedHomeModificationTypeOtherDescription is not provided in a given instance of MANUFACTURED_HOME_MODIFICATION","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Modification, Attachment, or Addition","dataPointName":"ManufacturedHomeModificationTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_MODIFICATIONS/MANUFACTURED_HOME_MODIFICATION/"},{"uniqueId":"0500.0039","dataElement":"SkirtingMaterialType","messageId":"UAD1123","message":"Provide the skirting material type for the manufactured home.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\" and SkirtingExistsIndicator = \\"true\\", and (at least one instance of SKIRTING_MATERIAL is not provided or SkirtingMaterialType is not provided in a given instance of SKIRTING_MATERIAL)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Skirting","dataPointName":"SkirtingMaterialType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/SKIRTING_MATERIALS/SKIRTING_MATERIAL/"},{"uniqueId":"0500.0040","dataElement":"SkirtingMaterialTypeOtherDescription","messageId":"UAD1124","message":"Provide a description when skirting material = 'Other'.","ruleLogic":"If SkirtingMaterialType = \\"Other\\" and SkirtingMaterialTypeOtherDescription is not provided in a given instance of SKIRTING_MATERIAL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Skirting","dataPointName":"SkirtingMaterialTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/SKIRTING_MATERIALS/SKIRTING_MATERIAL/"},{"uniqueId":"0500.0041","dataElement":"ManufacturedHomeInstalledDateEstimatedIndicator","messageId":"UAD1125","message":"Indicate whether the manufactured home installed date was estimated.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\" and ManufacturedHomeInstalledDateEstimatedIndicator is not provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Year Installed","dataPointName":"ManufacturedHomeInstalledDateEstimatedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/","relatedValues":"ManufacturedHomeInstalledDate (%RV1%)"},{"uniqueId":"0500.0044","dataElement":"ManufacturedHomeWidthType","messageId":"UAD1126","message":"Provide the 'Manufactured Home Width' (i.e., Single Wide, Multi Wide).","ruleLogic":"If ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\" and ManufacturedHomeWidthType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"{No Subsection}","reportLabel":"Manufactured Home Width","dataPointName":"ManufacturedHomeWidthType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"0600.0005","dataElement":"SalesConcessionAmountKnownIndicator","messageId":"UAD1127","message":"Indicate whether the total amount of sales concessions is known.","ruleLogic":"If SalesConcessionIndicator = \\"true\\" and SalesConcessionAmountKnownIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"Financial Sales Concessions","reportLabel":"Total Sales Concessions","dataPointName":"SalesConcessionAmountKnownIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"0600.0006","dataElement":"SalesConcessionIndicator","messageId":"UAD1128","message":"Indicate the presence of sales concessions in the sales contract.","ruleLogic":"If SalesContractReviewedIndicator = \\"true\\" and SalesConcessionIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"Financial Sales Concessions","reportLabel":"Known Sales Concessions","dataPointName":"SalesConcessionIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"}
11,{"uniqueId":"0600.0008","dataElement":"SalesContractAmount","messageId":"UAD1129","message":"Provide the 'Contract Price'.","ruleLogic":"If SalesContractReviewedIndicator = \\"true\\" and SalesContractAmount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"{No Subsection}","reportLabel":"Contract Price","dataPointName":"SalesContractAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"0600.0009","dataElement":"SalesContractDate","messageId":"UAD1130","message":"Provide the date the sales contract was fully executed.","ruleLogic":"If SalesContractReviewedIndicator = \\"true\\" and SalesContractDate is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"{No Subsection}","reportLabel":"Contract Date","dataPointName":"SalesContractDate","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"0600.0009","dataElement":"SalesContractDate","messageId":"UAD1131","message":"The 'Contract Date' cannot be after the 'Effective Date of Appraisal'.","ruleLogic":"If SalesContractDate > AppraisalReportEffectiveDate","severity":"Warning","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"{No Subsection}","reportLabel":"Contract Date (%PV%)","dataPointName":"SalesContractDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/","relatedValues":"AppraisalReportEffectiveDate (%RV1%)"},{"uniqueId":"0600.0010","dataElement":"SalesContractReviewedIndicator","messageId":"UAD1132","message":"Indicate whether the Appraiser has reviewed and analyzed the sales contract.","ruleLogic":"If SalesContractExistsIndicator = \\"true\\" and SalesContractReviewedIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"{No Subsection}","reportLabel":"Was sales contract information analyzed?","dataPointName":"SalesContractReviewedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"0600.0011","dataElement":"TotalSalesConcessionAmount","messageId":"UAD1133","message":"Provide the 'Total Sales Concessions' amount.","ruleLogic":"If SalesConcessionAmountKnownIndicator = \\"true\\" and TotalSalesConcessionAmount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"Financial Sales Concessions","reportLabel":"Total Sales Concessions","dataPointName":"TotalSalesConcessionAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"0600.0016","dataElement":"SalesContractExistsIndicator","messageId":"UAD1134","message":"Indicate whether there is a sales contract associated with the property.","ruleLogic":"If SalesContractExistsIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"{No Subsection}","reportLabel":"Is there a sales contract?","dataPointName":"SalesContractExistsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"0600.0017","dataElement":"SaleType","messageId":"UAD1135","message":"Provide the 'Transfer Terms'.","ruleLogic":"If SalesContractReviewedIndicator = \\"true\\" and SaleType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"{No Subsection}","reportLabel":"Transfer Terms","dataPointName":"SaleType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"0600.0018","dataElement":"SaleTypeOtherDescription","messageId":"UAD1136","message":"Provide a description when 'Transfer Terms' = 'Other'.","ruleLogic":"If SaleType = \\"Other\\" and SaleTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"{No Subsection}","reportLabel":"Transfer Terms","dataPointName":"SaleTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"0700.0005","dataElement":"AccessibilityFeatureType","messageId":"UAD1138","message":"Provide the type of accessibility feature. Select 'None' if there are no accessibility features.","ruleLogic":"If ((ImprovementType = \\"Dwelling\\" ) or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and\\r\\nIf (at least one instance of ACCESSIBILITY_FEATURE is not provided or AccessibilityFeatureType is not provided in a given instance of ACCESSIBILITY_FEATURE)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Accessibility Features for Individuals with Disabilities","reportLabel":"Feature","dataPointName":"AccessibilityFeatureType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/ACCESSIBILITY_FEATURES/ACCESSIBILITY_FEATURE/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0027","dataElement":"BelowGradeExteriorAccessType","messageId":"UAD1139","message":"Provide the primary exterior access method (e.g., walk-out, walk-up) for the below grade area.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" and (AccessType = \\"ExteriorAccessOnly\\" or \\"InteriorAndExteriorAccess\\")) or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\" and (AccessType = \\"ExteriorAccessOnly\\" or \\"InteriorAndExteriorAccess\\")), and BelowGradeExteriorAccessType is not provided in a given instance of LEVEL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Grade Level Detail","dataPointName":"BelowGradeExteriorAccessType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/LEVELS/LEVEL/","relatedValues":"LevelType (%RV1%)"},{"uniqueId":"0700.0028","dataElement":"BelowGradeExteriorAccessTypeOtherDescription","messageId":"UAD1140","message":"Provide a description when 'Grade Level' = 'Other'.","ruleLogic":"If BelowGradeExteriorAccessType = \\"Other\\" and BelowGradeExteriorAccessTypeOtherDescription is not provided in a given instance of LEVEL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Grade Level Detail","dataPointName":"BelowGradeExteriorAccessTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/LEVELS/LEVEL/"},{"uniqueId":"0700.0029","dataElement":"GradeLevelType","messageId":"UAD1141","message":"Provide the Grade Level Type (i.e., Above Grade, Fully Below Grade, Partially Below Grade) for the level.","ruleLogic":"If (ImprovementType = \\"Dwelling\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\"), and GradeLevelType is not provided in a given instance of LEVEL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Grade Level Detail","dataPointName":"GradeLevelType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/LEVELS/LEVEL/","relatedValues":"LevelType (%RV1%)"},{"uniqueId":"0700.0030","dataElement":"LevelType","messageId":"UAD1142","message":"Provide the level type (e.g., Level 1, Level 2, Level B1).","ruleLogic":"If (ImprovementType = \\"Dwelling\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\"), and (at least one instance of LEVEL is not provided or LevelType is not provided in a given instance of LEVEL)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Level in Unit","dataPointName":"LevelType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/LEVELS/LEVEL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0035","dataElement":"RoomType","messageId":"UAD1143","message":"Provide at least one instance of 'Kitchen' for each living unit.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and (at least one instance of ROOM_DETAIL with RoomType = \\"Kitchen\\" is not provided)","severity":"Warning","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}; Quality and Condition","reportLabel":"Room Summary; Room","dataPointName":"RoomType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/ROOMS/ROOM/ROOM_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0087","dataElement":"RoomTypeOtherDescription","messageId":"UAD1144","message":"Provide a description when room type = 'Other'.","ruleLogic":"If RoomType = \\"Other\\" and RoomTypeOtherDescription is not provided in a given instance of ROOM_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}; Quality and Condition","reportLabel":"Room Summary; Room","dataPointName":"RoomTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/ROOMS/ROOM/ROOM_DETAIL/","relatedValues":"ImprovementType (%RV1%); LevelType (%RV2%)"},{"uniqueId":"0700.0033","dataElement":"RoomConditionStatusType","messageId":"UAD1145","message":"Provide the 'Condition Status' for the room.","ruleLogic":"If (ImprovementType = \\"Dwelling\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\") and (RoomType = \\"FullBathroom\\" or \\"HalfBathroom\\" or \\"Kitchen\\"), and RoomConditionStatusType is not provided in a given instance of ROOM_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Condition Status","dataPointName":"RoomConditionStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/ROOMS/ROOM/ROOM_DETAIL/","relatedValues":"ImprovementType (%RV1%); LevelType (%RV2%); RoomType (%RV3%)"},{"uniqueId":"0700.0036","dataElement":"RoomUpdateStatusType","messageId":"UAD1146","message":"Provide the 'Upd
11ate Status' for the room.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")) and RoomType = (\\"FullBathroom\\" or \\"HalfBathroom\\" or \\"Kitchen\\"), and RoomUpdateStatusType is not provided in a given instance of ROOM_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Update Status","dataPointName":"RoomUpdateStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/ROOMS/ROOM/ROOM_DETAIL/","relatedValues":"ImprovementType (%RV1%); LevelType (%RV2%); RoomType (%RV3%)"},{"uniqueId":"0700.0034","dataElement":"RoomUpdatedTimeframeType","messageId":"UAD1147","message":"Provide the timeframe in which the room was updated.","ruleLogic":"If RoomType = \\"FullBathroom\\" or \\"HalfBathroom\\" or \\"Kitchen\\", and RoomUpdateStatusType = \\"FullyUpdated\\" or \\"PartiallyUpdated\\", and RoomUpdatedTimeframeType is not provided in a given instance of ROOM_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Time Frame","dataPointName":"RoomUpdatedTimeframeType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/ROOMS/ROOM/ROOM_DETAIL/","relatedValues":"RoomType (%RV1%)"},{"uniqueId":"0700.0046","dataElement":"ImprovementComponentType","messageId":"UAD1148","message":"The interior feature type must be included.","ruleLogic":"If (ImprovementType = \\"Dwelling\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\"), and ImprovementComponentType is not provided in a given instance of INTERIOR_COMPONENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"ImprovementComponentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/INTERIOR_COMPONENT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0046","dataElement":"ImprovementComponentType","messageId":"UAD1149","message":"Provide the flooring details (e.g., material, condition) for the living unit.","ruleLogic":"If (ImprovementType = \\"Dwelling\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\"), and ImprovementComponentType = \\"Flooring\\" is not provided in INTERIOR_COMPONENT_DETAIL for a given instance of PROPERTY_UNIT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"ImprovementComponentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/INTERIOR_COMPONENT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0041","dataElement":"FlooringType","messageId":"UAD1150","message":"Provide the flooring material(s).","ruleLogic":"If ImprovementComponentType = \\"Flooring\\" and (at least one instance of FLOOR_COVERING is not provided or FlooringType is not provided in a given instance of FLOOR_COVERING)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"FlooringType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/FLOOR_COVERINGS/FLOOR_COVERING/"},{"uniqueId":"0700.0042","dataElement":"FlooringTypeOtherDescription","messageId":"UAD1151","message":"Provide a description when flooring material = 'Other'.","ruleLogic":"If FlooringType = \\"Other\\" and FlooringTypeOtherDescription is not provided in a given instance of FLOOR_COVERING","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"FlooringTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/FLOOR_COVERINGS/FLOOR_COVERING/"},{"uniqueId":"0700.0046","dataElement":"ImprovementComponentType","messageId":"UAD1152","message":"Provide the walls and ceiling details (e.g., style, height) for the living unit.","ruleLogic":"If (ImprovementType = \\"Dwelling\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\"), and ImprovementComponentType = \\"WallsAndCeiling\\" is not provided in INTERIOR_COMPONENT_DETAIL in a given instance of PROPERTY_UNIT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"ImprovementComponentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/INTERIOR_COMPONENT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0047","dataElement":"ImprovementComponentTypeOtherDescription","messageId":"UAD1153","message":"Provide a description when 'Feature Type' = 'Other'.","ruleLogic":"If ImprovementComponentType = \\"Other\\" and ImprovementComponentTypeOtherDescription is not provided in a given instance of INTERIOR_COMPONENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Feature","dataPointName":"ImprovementComponentTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/INTERIOR_COMPONENT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0050","dataElement":"ApproximateCeilingHeightType","messageId":"UAD1154","message":"Provide the approximate ceiling height(s) for the living unit.","ruleLogic":"If ImprovementComponentType = \\"WallsAndCeiling\\" and (at least one instance of CEILING_HEIGHT is not provided or ApproximateCeilingHeightType is not provided in a given instance of CEILING_HEIGHT)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"ApproximateCeilingHeightType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/WALLS_AND_CEILING/CEILING_HEIGHTS/CEILING_HEIGHT/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0043","dataElement":"ImprovementComponentTypeAdditionalDescription","messageId":"UAD1155","message":"Provide additional description for the interior feature being referenced.","ruleLogic":"If ImprovementComponentType = \\"Other\\" and ImprovementComponentTypeAdditionalDescription is not provided in a given instance of INTERIOR_COMPONENT_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Detail","dataPointName":"ImprovementComponentTypeAdditionalDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/INTERIOR_COMPONENT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0045","dataElement":"ImprovementComponentConditionStatusType","messageId":"UAD1156","message":"Provide the 'Condition Status'.","ruleLogic":"If ImprovementComponentType = \\"WallsAndCeiling\\" or \\"Other\\", and ImprovementComponentConditionStatusType is not provided in a given instance of INTERIOR_COMPONENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Condition Status","dataPointName":"ImprovementComponentConditionStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/INTERIOR_COMPONENT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0058","dataElement":"CornerUnitIndicator","messageId":"UAD1157","message":"Indicate whether the subject property is a corner unit.","ruleLogic":"If StructuralDesignType = \\"Lowrise\\" or \\"Highrise\\" or \\"Midrise\\", and CornerUnitIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Corner Unit","dataPointName":"CornerUnitIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/"},{"uniqueId":"0700.0060","dataElement":"FloorIdentifier","messageId":"UAD1158","message":"Provide the 'Floor Number'.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and AttachmentType = \\"Attached\\" and StructuralDesignType = (\\"Lowrise\\" or \\"Highrise\\" or \\"Midrise\\"), and FloorIdentifier is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Floor Number","dataPointName":"FloorIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/"},{"uniqueId":"0700.0065","dataElement":"UnitIncludedInRentScheduleIndicator","messageId":"UAD1159","message":"Indicate whether the living unit is included in the rent schedule.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" and RentScheduleIndicator = \\"true\\") or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\" and RentScheduleIndicator = \\"true\\") , and UnitIncludedInRentScheduleIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"UnitIncludedInRentScheduleIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0066","dataElement":"InteriorConditionRatingCode","messageId":"UAD1160","message":"Provide the interior condition rating.","ruleLogic":"If (ImprovementType = \\"Dwelling\\") \\r\\nor (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\"), and InteriorConditionRatingCode is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Interior Condition Rating","dataPointName":"InteriorConditionRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0067","dataElement":"InteriorQualityRatingCode","messageId":"UAD1161","message":"Provide the interior quality rating.","ruleLogic":"If (ImprovementType = \\"Dwelling\\") \\r\\nOR (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\"), and InteriorQualityRatingCode is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Interior Quality Rating","dataPointName":"InteriorQualityRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0072","dataElement":"UtilitiesMeteredSeparatelyIndicator","messageId":"UAD1162","message":"Indicate whether the living unit utilities are metered separately.","ruleLogic":"If (LivingUnitExcludingADUCount > 1 or AccessoryDwellingUnitTotalCount > 0), and UtilitiesMeteredSeparatelyIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Utilities Separately Metered","dataPointName":"UtilitiesMeteredSeparatelyIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0088","dataElement":"AccessoryDwellingUnitTypicalToMarketIndicator","messageId":"UAD1163","message":"Indicate whether ADUs are typical to the market.","ruleLogic":"If AccessoryDwellingUnitIndicator = \\"true\\" and AccessoryDwellingUnitTypicalToMarketIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Typical for Market","dataPointName":"AccessoryDwellingUnitTypicalToMarketIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0089","dataElement":"AccessoryDwellingUnitIndicator","messageId":"UAD1164","message":"Indicate whether the living unit is an ADU.","ruleLogic":"if AccessoryDwellingUnitIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL when STRUCTURE_DETAIL/LivingUnitCount > 0","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"ADU","dataPointName":"AccessoryDwellingUnitIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0090","dataElement":"SeparatePostalAddressIndicator","messageId":"UAD1165","message":"Indicate whether the ADU has a separate postal address.","ruleLogic":"If AccessoryDwellingUnitIndicator = \\"true\\" and SeparatePostalAddressIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Separate Postal Address","dataPointName":"SeparatePostalAddressIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0091","dataElement":"AccessType","messageId":"UAD1166","message":"Provide ingress/egress to the ADU (i.e., Interior Access Only, Exterior Access Only, Interior and Exterior Access).","ruleLogic":"If AccessoryDwellingUnitIndicator = \\"true\\" and AccessType is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Ingress/Egress","dataPointName":"AccessType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0098","dataElement":"AccessoryDwellingUnitLegallyRentableIndicator","messageId":"UAD1167","message":"Indicate whether the ADU is legally rentable.","ruleLogic":"If AccessoryDwellingUnitIndicator = \\"true\\" and AccessoryDwellingUnitLegallyRentableIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","repo
11rtSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Legally Rentable","dataPointName":"AccessoryDwellingUnitLegallyRentableIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0100","dataElement":"AllowableLiveWorkSpaceIndicator","messageId":"UAD1168","message":"Indicate whether the living unit has any Live/Work space.","ruleLogic":"If LandOwnedInCommonIndicator = \\"true\\" and AllowableLiveWorkSpaceIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Live/Work Space","dataPointName":"AllowableLiveWorkSpaceIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0104","dataElement":"ImprovementComponentConditionStatusType","messageId":"UAD1169","message":"Provide the 'Condition Status' for each floor covering.","ruleLogic":"If ImprovementComponentType = \\"Flooring\\" and ImprovementComponentConditionStatusType is not provided in FLOOR_COVERING in a given instance of PROPERTY_UNIT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Condition Status","dataPointName":"ImprovementComponentConditionStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/FLOOR_COVERINGS/FLOOR_COVERING/"},{"uniqueId":"0700.0114","dataElement":"UnitIdentifier","messageId":"UAD1170","message":"Unit Identifier must be provided when multiple living units are identified in the appraisal.","ruleLogic":"If (LivingUnitExcludingADUCount > 1 or AccessoryDwellingUnitTotalCount > 0), and UnitIdentifier is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"{No Label}","dataPointName":"UnitIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0114","dataElement":"UnitIdentifier","messageId":"UAD1171","message":"The unit identifier must be unique.","ruleLogic":"If UnitIdentifier is not unique across all instances of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"{No Label}","dataPointName":"UnitIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/"},{"uniqueId":"1800.0159","dataElement":"UnitIdentifier","messageId":"UAD1172","message":"The unit identifier must be unique.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and UnitIdentifier is not unique across all instances of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s); Interior Quality and Condition","reportLabel":"Structure ID | Unit ID","dataPointName":"UnitIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/"},{"uniqueId":"0700.0117","dataElement":"OverallBathroomsUpdateStatusType","messageId":"UAD1173","message":"Provide the 'Overall Update Status for Bathrooms'.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and OverallBathroomsUpdateStatusType is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Overall Update Status for Bathrooms","dataPointName":"OverallBathroomsUpdateStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0118","dataElement":"BedroomCount","messageId":"UAD1174","message":"Provide the number of bedrooms in the living unit, even if the value is 0.","ruleLogic":"If ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\"), and BedroomCount is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Total Bedrooms","dataPointName":"BedroomCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0119","dataElement":"FullBathroomCount","messageId":"UAD1175","message":"Provide the number of full bathrooms in the living unit, even if the value is 0.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and FullBathroomCount is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Total Bathrooms - Full","dataPointName":"FullBathroomCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0120","dataElement":"HalfBathroomCount","messageId":"UAD1176","message":"Provide the number of half bathrooms in the living unit, even if the value is 0.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and HalfBathroomCount is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Total Bathrooms - Half","dataPointName":"HalfBathroomCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0121","dataElement":"LevelType","messageId":"UAD1177","message":"Provide the level type (e.g., Level 1, Level 2, Level B1).","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and LevelType is not provided in a given instance ROOM_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Room","dataPointName":"LevelType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/ROOMS/ROOM/ROOM_DETAIL/","relatedValues":"ImprovementType (%RV1%); RoomType (%RV2%)"},{"uniqueId":"0700.0122","dataElement":"OverallFlooringUpdateStatusType","messageId":"UAD1178","message":"Provide the 'Overall Update Status for Flooring'.","ruleLogic":"If ImprovementComponentType = \\"Flooring\\" and OverallFlooringUpdateStatusType is not provided in a given instance of INTERIOR_COMPONENT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Quality and Condition","reportLabel":"Overall Update Status for Flooring","dataPointName":"OverallFlooringUpdateStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/INTERIOR_COMPONENT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0125","dataElement":"DataSourceType","messageId":"UAD1179","message":"Provide at least one data source reference for the appraisal.","ruleLogic":"If at least one DataSourceType is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"DataSourceType","xpath":"../VALUATION_ANALYSIS/DATA_SOURCES/DATA_SOURCE/"},{"uniqueId":"0700.0126","dataElement":"DataSourceTypeOtherDescription","messageId":"UAD1181","message":"Provide a description when data source type = 'Other'.","ruleLogic":"If DataSourceType = \\"Other\\" and DataSourceTypeOtherDescription is not provided in a given instance of DATA_SOURCE","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"DataSourceTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/DATA_SOURCES/DATA_SOURCE/"},{"uniqueId":"0700.0130","dataElement":"UnitMixedUsageIndicator","messageId":"UAD1182","message":"Indicate whether the living unit has any non-residential uses.","ruleLogic":"If LandOwnedInCommonIndicator = \\"true\\" and UnitMixedUsageIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Non-Residential Use in Unit","dataPointName":"UnitMixedUsageIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0131","dataElement":"@xlink:arcrole","messageId":"UAD1183","message":"Provide at least one data source for each living unit associated with the subject property. In the UAD XML, a minimum of one RELATIONSHIP must be included that links DATA_SOURCE to PROPERTY_UNIT_AREA. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DATA_SOURCE_IsDataSourceFor_PROPERTY_UNIT_AREA\\" that links DATA_SOURCE to each PROPERTY_UNIT_AREA where @ValuationUseType = \\"SubjectProperty\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"0700.0137","dataElement":"LevelFinishedAreaMeasure","messageId":"UAD1184","message":"Provide the finished area of each level in the living unit.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and LevelFinishedAreaMeasure is not provided in a given instance of LEVEL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Area","dataPointName":"LevelFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/LEVELS/LEVEL/","relatedValues":"ImprovementType (%RV1%); LevelType (%RV2%)"},{"uniqueId":"0700.0138","dataElement":"LevelUnfinishedAreaMeasure","messageId":"UAD1185","message":"Provide the unfinished area of each level in the living unit.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and LevelUnfinishedAreaMeasure is not provided in a given instance of LEVEL","severity":"Warning","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Area","dataPointName":"LevelUnfinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/LEVELS/LEVEL/","relatedValues":"ImprovementType (%RV1%); LevelType (%RV2%)"},{"uniqueId":"0700.0140","dataElement":"UnitStandardAboveGradeFinis
11hedAreaMeasure","messageId":"UAD1186","message":"Provide the 'Finished Above Grade' Area, even if the value is 0.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and UnitStandardAboveGradeFinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Finished Above Grade","dataPointName":"UnitStandardAboveGradeFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0141","dataElement":"UnitNonStandardAboveGradeFinishedAreaMeasure","messageId":"UAD1187","message":"Provide the 'Finished Above Grade (Nonstandard)' Area, even if the value is 0.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and UnitNonStandardAboveGradeFinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Finished Above Grade (Nonstandard)","dataPointName":"UnitNonStandardAboveGradeFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0142","dataElement":"UnitAboveGradeUnfinishedAreaMeasure","messageId":"UAD1188","message":"Provide the 'Unfinished Above Grade' Area, even if the value is 0.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and UnitAboveGradeUnfinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Warning","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Unfinished Above Grade","dataPointName":"UnitAboveGradeUnfinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0143","dataElement":"UnitStandardBelowGradeFinishedAreaMeasure","messageId":"UAD1189","message":"Provide the 'Finished Below Grade' Area, even if the value is 0.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and UnitStandardBelowGradeFinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Finished Below Grade","dataPointName":"UnitStandardBelowGradeFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0700.0144","dataElement":"UnitBelowGradeUnfinishedAreaMeasure","messageId":"UAD1190","message":"Provide the 'Unfinished Below Grade' Area, even if the value is 0.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and UnitBelowGradeUnfinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Unfinished Below Grade","dataPointName":"UnitBelowGradeUnfinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"0800.0005","dataElement":"PriorSalesOrTransfersIndicator","messageId":"UAD1191","message":"Indicate whether the subject property has a prior sale or transfer.","ruleLogic":"If PriorSalesOrTransfersIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Prior Sale and Transfer History","reportSubsection":"Subject Transfer History","reportLabel":"Prior Sales or Transfers","dataPointName":"PriorSalesOrTransfersIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"0800.0018","dataElement":"OwnershipTransferTransactionType","messageId":"UAD1192","message":"Provide the ownership transfer transaction type (i.e., sale, deed transfer only).","ruleLogic":"If PriorSalesOrTransfersIndicator = \\"true\\" and (at least one instance of SALES_HISTORY is not provided or OwnershipTransferTransactionType is not provided in a given instance of SALES_HISTORY)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Prior Sale and Transfer History","reportSubsection":"Subject Transfer History","reportLabel":"Transfer Terms","dataPointName":"OwnershipTransferTransactionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/"},{"uniqueId":"0800.0013","dataElement":"SaleType","messageId":"UAD1193","message":"Provide the 'Transfer Terms'.","ruleLogic":"If PriorSalesOrTransfersIndicator = \\"true\\" and OwnershipTransferTransactionType = \\"Sale\\", and SaleType is not provided in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Prior Sale and Transfer History","reportSubsection":"Subject Transfer History","reportLabel":"Transfer Terms","dataPointName":"SaleType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/"},{"uniqueId":"0800.0014","dataElement":"SaleTypeOtherDescription","messageId":"UAD1194","message":"Provide a description when 'Transfer Terms' = 'Other'.","ruleLogic":"If SaleType = \\"Other\\" and SaleTypeOtherDescription is not provided in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Prior Sale and Transfer History","reportSubsection":"Subject Transfer History","reportLabel":"Transfer Terms","dataPointName":"SaleTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/"},{"uniqueId":"0800.0011","dataElement":"OwnershipTransferDate","messageId":"UAD1195","message":"Provide the ownership transfer date.","ruleLogic":"IF PriorSalesOrTransfersIndicator = \\"true\\" and OwnershipTransferDate is not provided in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Prior Sale and Transfer History","reportSubsection":"Subject Transfer History","reportLabel":"Date","dataPointName":"OwnershipTransferDate","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","relatedValues":"OwnershipTransferTransactionType (%RV1%)"},{"uniqueId":"0800.0011","dataElement":"OwnershipTransferDate","messageId":"UAD1196","message":"The prior sale or transfer date for the subject property must include year, month and day.","ruleLogic":"If OwnershipTransferDate does not include year, month and day (YYYY-MM-DD format) in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Prior Sale and Transfer History","reportSubsection":"Subject Transfer History","reportLabel":"Date (%PV%)","dataPointName":"OwnershipTransferDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","relatedValues":"OwnershipTransferTransactionType (%RV1%)","dateFormat":"CCYY-MM-DD"},{"uniqueId":"0800.0012","dataElement":"OwnershipTransferTransactionAmount","messageId":"UAD1197","message":"The amount related to the transfer of ownership of real property (typically the sale price) must be greater than or equal to $0.","ruleLogic":"If OwnershipTransferTransactionAmount < 0 in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Prior Sale and Transfer History","reportSubsection":"Subject Transfer History","reportLabel":"Amount (%PV%)","dataPointName":"OwnershipTransferTransactionAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","relatedValues":"OwnershipTransferTransactionType (%RV1%)","minValue":0},{"uniqueId":"0800.0010","dataElement":"OwnershipTransferAmountNotAvailableReasonTypeOtherDescription","messageId":"UAD1198","message":"Provide a description when 'Ownership Transfer Amount Not Available Reason Type' = 'Other'.","ruleLogic":"If OwnershipTransferAmountNotAvailableReasonType = \\"Other\\" and OwnershipTransferAmountNotAvailableReasonTypeOtherDescription is not provided in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Prior Sale and Transfer History","reportSubsection":"Subject Transfer History","reportLabel":"Amount","dataPointName":"OwnershipTransferAmountNotAvailableReasonTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/"},{"uniqueId":"0800.0031","dataElement":"@xlink:arcrole","messageId":"UAD1199","message":"Provide at least one data source when the sales comparable does not have any prior sales or transfer history. In the UAD XML, a minimum of one RELATIONSHIP must be included that links DATA_SOURCE to PriorSalesOrTransfersIndicator. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PriorSalesOrTransfersIndicator = \\"false\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DATA_SOURCE_IsDataSourceFor_PriorSalesOrTransfersIndicator\\" that links DATA_SOURCE to PriorSalesOrTransfersIndicator","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"0800.0034","dataElement":"@xlink:arcrole","messageId":"UAD1200","message":"Provide at least one data source when the subject property does not have any prior sales or transfer history. In the UAD XML, a minimum of one RELATIONSHIP must be included that links DATA_SOURCE to PriorSalesOrTransfersIndicator. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and PriorSalesOrTransfersIndicator = \\"false\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DATA_SOURCE_IsDataSourceFor_PriorSalesOrTransfersIndicator\\" that links DATA_SOURCE to PriorSalesOrTransfersIndicator","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"0800.0039","dataElement":"@xlink:arcrole","messageId":"UAD1201","message":"Provide at least one data source when the sales comparable has a prior sale or transfer history. In the UAD XML, a minimum of one RELATIONSHIP must be included that links DATA_SOURCE to SALES_HISTORY for each prior sale or transfer. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PriorSalesOrTransfersIndicator = \\"true\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DATA_SOURCE_IsDataSourceFor_SALES_HISTORY\\" that links DATA_SOURCE to SALES_HISTORY","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"0800.0042","dataElement":"@xlink:arcrole","messageId":"UAD1202","message":"Provide at least one data source when the subject property has a prior sale or transfer history. In the UAD XML, a minimum of one RELATIONSHIP must be included that links DATA_SOURCE to SALES_HISTORY for each prior sale or transfer. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and PriorSalesOrTransfersIndicator = \\"true\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DATA_SOURCE_IsDataSourceFor_SALES_HISTORY\\" that links DATA_SOURCE to SALES_HISTORY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"0900.0004","dataElement":"ListedWithinPreviousYearIndicator","messageId":"UAD1203","message":"Indicate whether the property has been listed within the previous twelve (12) months.","ruleLogic":"If ListedWithinPreviousYearIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Listing Information","reportSubsection":"{No Subsection}","reportLabel":"Current or Relevant","dataPointName":"ListedWithinPreviousYearIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATION_SUMMARY/"},{"uniqueId":"0900.0007","dataElement":"DaysOnMarketCount","messageId":"UAD1204","message":"Provide the total number of days the property has been on the market.","ruleLogic":"If ListedWithinPreviousYearIndicator = \\"true\\" and DaysOnMarketCount is not provided in a given instance of LISTING_INFORMATION_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Listing Information","reportSubsection":"{No Subsection}","reportLabel":"DOM","dataPointName":"DaysOnMarketCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/","relatedValues":"ListingStatusType (%RV1%); ListingType (%RV2%)"},{"uniqueId":"0900.0008","dataElement":"FinalListPriceAmount","messageId":"UAD1205","message":"Provide the 'Current or Final List Price'.","ruleLogic":"If ListedWithinPreviousYearIndicator = \\"true\\" and FinalListPriceAmount is not provided in a given instance of LISTING_INFORMATION_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Listing Information","reportSubsection":"{No Subsection}","reportLabel":"Current or Final List Price","dataPointName":"FinalListPriceAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/","relatedValues":"ListingStatusType (%RV1%); ListingType (%RV2%)"},{"uniqueId":"0900.0012","dataElement":"ListingStartDate","messageId":"UAD1206","message":"The listing start date cannot be after the listing end date.","ruleLogic":"If ListingStartDate > ListingEndDate in a given instance of LISTING_INFORMATION_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Listing Information","reportSubsection":"{No Subsection}","reportLabel":"Start Date (%PV%)","dataPointName":"ListingStartDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/","relatedValues":"ListingEndDate (%RV1%)"},{"uniqueId":"0900.0013","dataElement":"ListingStatusType","messageId":"UAD1207","message":"Provide the 'Listing Status'.","ruleLogic":"If ListedWithinPreviousYearIndicator = \\"true\\" and ( at least one instance of LISTING_INFORMATION_DETAIL is not provided or ListingStatusType is not provided in a given instance of LISTING_INFORMATION_DETAIL)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Listing Information","reportSubsection":"{No Subsection}","reportLabel":"Listing Status","dataPointName":"ListingStatusType","xpath":"../VALUATION
11_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/"},{"uniqueId":"0900.0016","dataElement":"ListingTypeOtherDescription","messageId":"UAD1208","message":"Provide a description when 'Listing Type' = 'Other'.","ruleLogic":"If ListingType = \\"Other\\" and ListingTypeOtherDescription is not provided in a given instance of LISTING_INFORMATION_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Listing Information","reportSubsection":"{No Subsection}","reportLabel":"Listing Type","dataPointName":"ListingTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/","relatedValues":"ListingStatusType (%RV1%)"},{"uniqueId":"0900.0033","dataElement":"@xlink:arcrole","messageId":"UAD1209","message":"Provide at least one data source when the subject property is not listed within the previous year. In the UAD XML, a minimum of one RELATIONSHIP must be included that links DATA_SOURCE to LISTING_INFORMATION_SUMMARY. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and ListedWithinPreviousYearIndicator = \\"false\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DATA_SOURCE_IsDataSourceFor_LISTING_INFORMATION_SUMMARY\\" that links DATA_SOURCE to LISTING_INFORMATION_SUMMARY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"1000.0027","dataElement":"CostApproachIndicator","messageId":"UAD1210","message":"Indicate whether the cost approach valuation method has been utilized.","ruleLogic":"If CostApproachIndicator is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"CostApproachIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0028","dataElement":"GovernmentAgencyAppraisalIndicator","messageId":"UAD1211","message":"Indicate whether the appraisal has been prepared for a government agency.","ruleLogic":"If GovernmentAgencyAppraisalIndicator is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"GovernmentAgencyAppraisalIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0029","dataElement":"GovernmentAgencyAppraisalType","messageId":"UAD1212","message":"Provide the federal agency (i.e., VA, USDA, FHA) for which the appraisal has been prepared.","ruleLogic":"If GovernmentAgencyAppraisalIndicator = \\"true\\" and GovernmentAgencyAppraisalType is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Government Agency","dataPointName":"GovernmentAgencyAppraisalType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0030","dataElement":"IncomeApproachIndicator","messageId":"UAD1213","message":"Indicate whether the income approach valuation method has been utilized.","ruleLogic":"If IncomeApproachIndicator is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"IncomeApproachIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0030","dataElement":"IncomeApproachIndicator","messageId":"UAD1214","message":"Income approach is included in the appraisal, however no GRM comparables have been provided.","ruleLogic":"If IncomeApproachIndicator = \\"true\\" and there are no instances of PROPERTY with @ValuationUseType = \\"GrossRentMultiplierComparable\\"","severity":"Fatal","propertyAffected":"Gross Rent Multiplier Comparable","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"IncomeApproachIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0031","dataElement":"RentScheduleIndicator","messageId":"UAD1215","message":"When 'Income Approach Developed by Appraiser' is Yes, 'Rent Schedule Developed by Appraiser' must also be Yes.","ruleLogic":"If IncomeApproachIndicator is \\"true\\" and RentScheduleIndicator is \\"false\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"RentScheduleIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0031","dataElement":"RentScheduleIndicator","messageId":"UAD1216","message":"Indicate whether the rent schedule was included in the appraisal.","ruleLogic":"If RentScheduleIndicator is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"RentScheduleIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0031","dataElement":"RentScheduleIndicator","messageId":"UAD1217","message":"Rent Schedule is included in the appraisal, however, no rental comparables have been provided.","ruleLogic":"If RentScheduleIndicator = \\"true\\" and there are no instances of PROPERTY with @ValuationUseType = \\"RentalComparable\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"RentScheduleIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0032","dataElement":"SalesComparisonApproachIndicator","messageId":"UAD1218","message":"Indicate whether the sales comparison approach valuation method has been utilized.","ruleLogic":"If SalesComparisonApproachIndicator is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"SalesComparisonApproachIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0034","dataElement":"ValuationAssignmentType","messageId":"UAD1219","message":"Provide the 'Assignment Reason'.","ruleLogic":"If ValuationAssignmentType is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Assignment Reason","dataPointName":"ValuationAssignmentType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0035","dataElement":"ValuationAssignmentTypeOtherDescription","messageId":"UAD1220","message":"Provide a description when 'Assignment Reason' = 'Other'.","ruleLogic":"If ValuationAssignmentType = \\"Other\\" and ValuationAssignmentTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Assignment Reason","dataPointName":"ValuationAssignmentTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1000.0119","dataElement":"InspectionDate","messageId":"UAD1221","message":"Provide the date the property inspection was performed.","ruleLogic":"If PropertyDataReportIndicator = \\"true\\" and InspectionDate is not provided in SERVICE container with ServiceType = \\"Inspection\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Property Data Report - Inspection Date","dataPointName":"InspectionDate","xpath":"../SERVICE/INSPECTION_SERVICE/INSPECTION_SERVICE_RESPONSE/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/INSPECTION_DETAIL/","relatedValues":"PartyRoleType (Property Data Collector)"},{"uniqueId":"1000.0158","dataElement":"PropertyValuationMethodType","messageId":"UAD1222","message":"Provide the 'Property Valuation Method'.","ruleLogic":"If PropertyValuationMethodType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Property Valuation Method","dataPointName":"PropertyValuationMethodType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_VALUATIONS/PROPERTY_VALUATION/PROPERTY_VALUATION_DETAIL/"},{"uniqueId":"1000.0198","dataElement":"ServiceType","messageId":"UAD1223","message":"'ServiceType' = 'Valuation' must be delivered once. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is no instance or more than one instance of SERVICE_DETAIL with ServiceType = \\"Valuation\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ServiceType","xpath":"../SERVICE/SERVICE_DETAIL/","minValue":1,"maxValue":1},{"uniqueId":"1000.0197","dataElement":"ServiceType","messageId":"UAD1224","message":"'ServiceType' = 'Inspection' must be delivered no more than once. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is more than one instance of SERVICE_DETAIL with ServiceType = \\"Inspection\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ServiceType","xpath":"../SERVICE/SERVICE_DETAIL/","minValue":0,"maxValue":1},{"uniqueId":"1100.0015","dataElement":"PropertyOrdinalNumber","messageId":"UAD1225","message":"A numeric identifier ('Comparable #') must be assigned for each land comparable. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"LandComparable\\" and PropertyOrdinalNumber is not provided","severity":"Fatal","propertyAffected":"Land Comparable","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"#","dataPointName":"PropertyOrdinalNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/","relatedValues":"AddressLineText (%RV1%); ParcelIdentifier (%RV2%)"},{"uniqueId":"1100.0015","dataElement":"PropertyOrdinalNumber","messageId":"UAD1226","message":"Comparable # must be unique. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If PropertyOrdinalNumber is not unique across all instances of PROPERTY with @ValuationUseType = \\"LandComparable\\"","severity":"Fatal","propertyAffected":"Land Comparable","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"#","dataPointName":"PropertyOrdinalNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1100.0026","dataElement":"DepreciatedCostDwellingsTotalAmount","messageId":"UAD1227","message":"The 'Depreciated Cost of Dwellings' must be provided.","ruleLogic":"If CostApproachIndicator = \\"true\\" and DepreciatedCostDwellingsTotalAmount is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"Indicated Value by Cost Approach","reportLabel":"Depreciated Cost of Dwellings","dataPointName":"DepreciatedCostDwellingsTotalAmount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/COST_APPROACH_DETAIL/"},{"uniqueId":"1100.0027","dataElement":"DepreciatedCostOutbuildingsTotalAmount","messageId":"UAD1228","message":"The 'Depreciated Cost of Outbuildings' must be provided.","ruleLogic":"If CostApproachIndicator = \\"true\\" and DepreciatedCostOutbuildingsTotalAmount is not provided when there are one or more instances of IMPROVEMENT_DETAIL with ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"Indicated Value by Cost Approach","reportLabel":"Depreciated Cost of Outbuildings","dataPointName":"DepreciatedCostOutbuildingsTotalAmount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/COST_APPROACH_DETAIL/"},{"uniqueId":"1100.0030","dataElement":"SiteEstimatedValueAmount","messageId":"UAD1229","message":"Provide the 'Opinion of Site Value'.","ruleLogic":"If CostApproachIndicator = \\"true\\", or \\r\\n(CostApproachIndicator = \\"false\\" and SiteValueIndicator = \\"true\\") and SiteEstimatedValueAmount is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"Opinion of Site Value","dataPointName":"SiteEstimatedValueAmount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/COST_APPROACH_DETAIL/"},{"uniqueId":"1100.0032","dataElement":"SiteOtherImprovementsAsIsAmount","messageId":"UAD1230","message":"Provide the 'As Is Value of Site Improvements'.","ruleLogic":"If CostApproachIndicator = \\"true\\" and SiteOtherImprovementsAsIsAmount is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"Indicated Value by Cost Approach","reportLabel":"As Is Value of Site Improvements","dataPointName":"SiteOtherImprovementsAsIsAmount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/COST_APPROACH_DETAIL/"},{"uniqueId":"1100.0033","dataElement":"SiteValuationMethodType","messageId":"UAD1231","message":"Provide the 'Primary Site Valuation Method'.","ruleLogic":"If CostApproachIndicator = \\"true\\", or \\r\\n(CostApproachIndicator = \\"false\\" and SiteValueIndicator = \\"true\\") and SiteValuationMethodType is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"Primary Site Valuation Method","dataPointName":"SiteValuationMethodType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/COST_APPROACH_DETAIL/"},{"uniqueId":"1100.0034","dataElement":"SiteValuationMethodTypeOtherDescription","messageId":"UAD1232","message":"Provide a description when 'Primary Site Valuation Method' = 'Other'.","ruleLogic":"If SiteValuationMethodType = \\"Other\\" and SiteValuationMethodTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"Primary Site Valuation Method","dataPointName":"SiteValuationMethodTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/COST_APPROACH_DETAIL/"},{"uniqueId":"","dataElement":"DepreciationTotalAmount","messageId":"UAD1233","message":"The 'Total Depreciation' displays as a negative number on the appraisal. However, it must be delivered as a positive number in the UAD XML. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If CostApproachIndicator = \\"true\\" and DepreciationTotalAmount < 0 in a given instance of IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION","severity":"Warning","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"{No Subsection}","reportLabel":"Total Depreciation (%PV%)","dataPointName":"DepreciationTotalAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/IMPROVEMENT_COST_AND_DEPRECIATED_VALUES/IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION/","minValue":0},{"uniqueId":"","dataElement":"DepreciationExternalAmount","messageId":"UAD1234","message":"The 'External Depreciation' displays as a negative number on the appraisal. However, it must be delivered as a positive number
11 in the UAD XML. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If CostApproachIndicator = \\"true\\" and DepreciationExternalAmount < 0 in a given instance of IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION","severity":"Warning","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"{No Subsection}","reportLabel":"External Depreciation (%PV%)","dataPointName":"DepreciationExternalAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/IMPROVEMENT_COST_AND_DEPRECIATED_VALUES/IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION/","minValue":0},{"uniqueId":"","dataElement":"DepreciationFunctionalAmount","messageId":"UAD1235","message":"The 'Functional Depreciation' displays as a negative number on the appraisal. However, it must be delivered as a positive number in the UAD XML. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If CostApproachIndicator = \\"true\\" and DepreciationFunctionalAmount < 0 in a given instance of IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION","severity":"Warning","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"{No Subsection}","reportLabel":"Functional Depreciation (%PV%)","dataPointName":"DepreciationFunctionalAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/IMPROVEMENT_COST_AND_DEPRECIATED_VALUES/IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION/","minValue":0},{"uniqueId":"","dataElement":"DepreciationPhysicalAmount","messageId":"UAD1236","message":"The 'Physical Depreciation' displays as a negative number on the appraisal. However, it must be delivered as a positive number in the UAD XML. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If CostApproachIndicator = \\"true\\" and DepreciationPhysicalAmount < 0 in a given instance of IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION","severity":"Warning","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"{No Subsection}","reportLabel":"Physical Depreciation (%PV%)","dataPointName":"DepreciationPhysicalAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/IMPROVEMENT_COST_AND_DEPRECIATED_VALUES/IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION/","minValue":0},{"uniqueId":"","dataElement":"DepreciationTotalAmount","messageId":"UAD1237","message":"Provide depreciation amount as summary, represented by 'Total Depreciation' or break out the three forms of depreciation ('Physical Depreciation', 'Functional Depreciation' and 'External Depreciation'), but not both.","ruleLogic":"If DepreciationTotalAmount is provided, and (any of DepreciationExternalAmount, DepreciationFunctionalAmount, and DepreciationPhysicalAmount are also provided) in a given instance of IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION","severity":"Fatal","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"{No Subsection}","reportLabel":"Total Depreciation (%PV%)","dataPointName":"DepreciationTotalAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/IMPROVEMENT_COST_AND_DEPRECIATED_VALUES/IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION/","relatedValues":"DepreciationExternalAmount (%RV1%); DepreciationFunctionalAmount (%RV2%); DepreciationPhysicalAmount (%RV3%)"},{"uniqueId":"1100.0033","dataElement":"SiteValuationMethodType","messageId":"UAD1238","message":"Primary Site Valuation Method' is provided as 'Sales Comparison', however, no land comparables have been provided.","ruleLogic":"If SiteValuationMethodType = \\"SalesComparison\\" and there are no instances of PROPERTY with @ValuationUseType = \\"LandComparable\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"Primary Site Valuation Method (%PV%)","dataPointName":"SiteValuationMethodType (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/COST_APPROACH_DETAIL/"},{"uniqueId":"1100.0065","dataElement":"DataSourceEffectiveDate","messageId":"UAD1239","message":"Provide the 'Effective Date' for the Cost Data Source.","ruleLogic":"If CostApproachIndicator = \\"true\\", and (DataSourceType = \\"BuilderOrDeveloper\\" or \\"CostService\\" or \\"CostSurvey\\" or \\"Other\\"), and DataSourceEffectiveDate is not provided in the instance of DATA_SOURCE that is related to cost approach","severity":"Fatal","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"General Description","reportLabel":"Effective Date","dataPointName":"DataSourceEffectiveDate","xpath":"../VALUATION_ANALYSIS/DATA_SOURCES/DATA_SOURCE/","relatedValues":"DataSourceType (%RV1%)"},{"uniqueId":"1100.0066","dataElement":"DataSourceName","messageId":"UAD1240","message":"Provide the cost data provider name (e.g., Craftsman Cost Guide, Marshall and Swift).","ruleLogic":"If CostApproachIndicator = \\"true\\", and DataSourceType = \\"CostService\\", and DataSourceName is not provided in a given instance of DATA_SOURCE","severity":"Fatal","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"General Description","reportLabel":"Cost Data Source","dataPointName":"DataSourceName","xpath":"../VALUATION_ANALYSIS/DATA_SOURCES/DATA_SOURCE/","relatedValues":"DataSourceType (%RV1%)"},{"uniqueId":"1100.0067","dataElement":"DataSourceQualityRatingCode","messageId":"UAD1241","message":"Provide the cost service quality rating (e.g., excellent, very good) determined for the property.","ruleLogic":"If CostApproachIndicator = \\"true\\" and DataSourceQualityRatingCode is not provided in the instance of DATA_SOURCE with DataSourceType = \\"CostService\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"General Description","reportLabel":"Quality Rating","dataPointName":"DataSourceQualityRatingCode","xpath":"../VALUATION_ANALYSIS/DATA_SOURCES/DATA_SOURCE/","relatedValues":"DataSourceType (%RV1%)"},{"uniqueId":"1200.0003","dataElement":"GrossRentMultiplierFactorNumber","messageId":"UAD1242","message":"Provide the 'Gross Rent Multiplier'.","ruleLogic":"If IncomeApproachIndicator = \\"true\\" and GrossRentMultiplierFactorNumber is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Income Approach","reportSubsection":"Indicated Value by Income Approach","reportLabel":"Gross Rent Multiplier","dataPointName":"GrossRentMultiplierFactorNumber","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/INCOME_APPROACH/INCOME_APPROACH_DETAIL/"},{"uniqueId":"1200.0004","dataElement":"ValueIndicatedByIncomeApproachAmount","messageId":"UAD1243","message":"Provide the value of the subject property as determined by the Income Approach method of property valuation.","ruleLogic":"If IncomeApproachIndicator = \\"true\\" and ValueIndicatedByIncomeApproachAmount is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Income Approach","reportSubsection":"Indicated Value by Income Approach","reportLabel":"Indicated Value by Income Approach","dataPointName":"ValueIndicatedByIncomeApproachAmount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/INCOME_APPROACH/INCOME_APPROACH_DETAIL/"},{"uniqueId":"1200.0015","dataElement":"ComparableWeightType","messageId":"UAD1244","message":"Provide the 'Comparable Weight' for the GRM comparable.","ruleLogic":"If @ValuationUseType = \\"GrossRentMultiplierComparable\\" and ComparableWeightType is not provided","severity":"Warning","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"Comparable Weight","dataPointName":"ComparableWeightType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1200.0016","dataElement":"GrossMonthlyRentMultiplierNumber","messageId":"UAD1245","message":"Provide the 'Gross Rent Multiplier'.","ruleLogic":"If @ValuationUseType = \\"GrossRentMultiplierComparable\\" and GrossMonthlyRentMultiplierNumber is not provided","severity":"Warning","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"Gross Rent Multiplier","dataPointName":"GrossMonthlyRentMultiplierNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1200.0028","dataElement":"PropertyOrdinalNumber","messageId":"UAD1246","message":"A numeric identifier ('Comparable #') must be assigned for each GRM comparable. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"GrossRentMultiplierComparable\\" and PropertyOrdinalNumber is not provided","severity":"Fatal","propertyAffected":"Gross Rent Multiplier Comparable","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"Comparable #","dataPointName":"PropertyOrdinalNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/","relatedValues":"AddressLineText (%RV1%)"},{"uniqueId":"1200.0028","dataElement":"PropertyOrdinalNumber","messageId":"UAD1247","message":"Comparable # must be unique. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"if PropertyOrdinalNumber is not unique across all instances of PROPERTY with @ValuationUseType = \\"GrossRentMultiplierComparable\\"","severity":"Fatal","propertyAffected":"Gross Rent Multiplier Comparable","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"Comparable #","dataPointName":"PropertyOrdinalNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1200.0029","dataElement":"LivingUnitExcludingADUCount","messageId":"UAD1248","message":"The total number of living units, excluding any ADUs, must be at least 1.","ruleLogic":"If @ValuationUseType = \\"GrossRentMultiplierComparable\\" and LivingUnitExcludingADUCount < 1","severity":"Fatal","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"Units Excluding ADUs (%PV%)","dataPointName":"LivingUnitExcludingADUCount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/","minValue":1},{"uniqueId":"1200.0030","dataElement":"TotalMonthlyActualRentAmount","messageId":"UAD1249","message":"Provide 'Gross Monthly Rent'.","ruleLogic":"If @ValuationUseType = \\"GrossRentMultiplierComparable\\" and TotalMonthlyActualRentAmount is not provided","severity":"Fatal","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"Gross Monthly Rent","dataPointName":"TotalMonthlyActualRentAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/RENTAL_INFORMATION_SUMMARY/RENTAL_INFORMATION_SUMMARY_DETAIL/"},{"uniqueId":"1200.0032","dataElement":"AdditionalComparisonLineItemIdentifier","messageId":"UAD1250","message":"One or more additional row labels are not identical for one or more properties. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"For each combination of ComparableAdjustmentType = \\"GrossRentMultiplierAdditionalNonAdjustableComparisonItem\\" and AdditionalComparisonLineItemIdentifier, if there are not matching occurrences of COMPARABLE_ADJUSTMENT across all instances of PROPERTY with @ValuationUseType = \\"GrossRentMultiplierComparable\\", and the instance of PROPERTY with @ValuationUseType = \\"SubjectProperty\\". See UAD1455 for an example of this concept.","severity":"Warning","propertyAffected":"Gross Rent Multiplier Comparable; Subject","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"{No Label}","dataPointName":"AdditionalComparisonLineItemIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_ADJUSTMENTS/COMPARABLE_ADJUSTMENT/"},{"uniqueId":"1200.0034","dataElement":"OwnershipTransferTransactionAmount","messageId":"UAD1251","message":"Provide the 'Sale Price' for the GRM comparable.","ruleLogic":"If @ValuationUseType = \\"GrossRentMultiplierComparable\\" and OwnershipTransferTransactionType = \\"Sale\\" and OwnershipTransferTransactionAmount is not provided","severity":"Fatal","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"Sale Price","dataPointName":"OwnershipTransferTransactionAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/"},{"uniqueId":"1300.0001","dataElement":"ValueIndicatedByCostApproachAmount","messageId":"UAD1252","message":"Provide the value of the subject property as determined by the C
11ost Approach method of property valuation.","ruleLogic":"If CostApproachIndicator = \\"true\\" and ValueIndicatedByCostApproachAmount is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"Indicated Value by Cost Approach","reportLabel":"Indicated Value by Cost Approach","dataPointName":"ValueIndicatedByCostApproachAmount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/COST_APPROACH_DETAIL/"},{"uniqueId":"1300.0006","dataElement":"ValueIndicatedBySalesComparisonAmount","messageId":"UAD1253","message":"Provide the value of the subject property as determined by the Sales Comparison Approach method of property valuation.","ruleLogic":"If SalesComparisonApproachIndicator = \\"true\\" and ValueIndicatedBySalesComparisonAmount is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Sales Comparison Approach","reportSubsection":"Summary","reportLabel":"Indicated Value","dataPointName":"ValueIndicatedBySalesComparisonAmount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/SALES_COMPARISON_APPROACH/SALES_COMPARISON_APPROACH_DETAIL/"},{"uniqueId":"1300.0010","dataElement":"PropertyValuationConditionalConclusionType","messageId":"UAD1255","message":"Provide the type of market value condition.","ruleLogic":"If at least one instance of VALUATION_CONDITION is not provided or PropertyValuationConditionalConclusionType is not provided in a given instance of VALUATION_CONDITION","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Market Value Condition","dataPointName":"PropertyValuationConditionalConclusionType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_CONDITIONS/VALUATION_CONDITION/"},{"uniqueId":"1300.0010","dataElement":"PropertyValuationConditionalConclusionType","messageId":"UAD1256","message":"When the appraisal is made 'As Is', no other type of market value condition can be delivered.","ruleLogic":"If PropertyValuationConditionalConclusionType = \\"AsIs\\" and there are one or more additional instances of VALUATION_CONDITION","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Market Value Condition","dataPointName":"PropertyValuationConditionalConclusionType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_CONDITIONS/VALUATION_CONDITION/"},{"uniqueId":"1300.0012","dataElement":"AppraisalReportEffectiveDate","messageId":"UAD1257","message":"Provide the 'Effective Date of Appraisal'.","ruleLogic":"If AppraisalReportEffectiveDate is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Effective Date of Appraisal","dataPointName":"AppraisalReportEffectiveDate","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/"},{"uniqueId":"1300.0012","dataElement":"AppraisalReportEffectiveDate","messageId":"UAD1258","message":"The 'Effective Date of Appraisal' cannot be a future date.","ruleLogic":"If AppraisalReportEffectiveDate is in the future","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Effective Date of Appraisal (%PV%)","dataPointName":"AppraisalReportEffectiveDate (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"1300.0012","dataElement":"AppraisalReportEffectiveDate","messageId":"UAD1259","message":"The 'Effective Date of Appraisal' cannot be more than a year old.","ruleLogic":"If AppraisalReportEffectiveDate is more than 367 days before the current date","severity":"Warning","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Effective Date of Appraisal (%PV%)","dataPointName":"AppraisalReportEffectiveDate (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"1300.0012","dataElement":"AppraisalReportEffectiveDate","messageId":"UAD1260","message":"The 'Effective Date of Appraisal' must include year, month and day.","ruleLogic":"If AppraisalReportEffectiveDate does not include year, month and day in YYYY-MM-DD format","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Effective Date of Appraisal (%PV%)","dataPointName":"AppraisalReportEffectiveDate (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"1300.0016","dataElement":"MarketingOrExposureTimeType","messageId":"UAD1261","message":"Provide MarketingOrExposureTimeType as 'ReasonableExposureTime'. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If MarketingOrExposureTimeType is not provided or is not = 'ReasonableExposureTime' in VALUATION_RECONCILIATION_SUMMARY_DETAIL","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MarketingOrExposureTimeType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/"},{"uniqueId":"1300.0017","dataElement":"OpinionOfValueAmount","messageId":"UAD1262","message":"Provide 'Opinion Of Market Value'.","ruleLogic":"If OpinionOfValueAmount is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Opinion of Market Value","dataPointName":"OpinionOfValueAmount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/"},{"uniqueId":"1300.0017","dataElement":"OpinionOfValueAmount","messageId":"UAD1263","message":"'Opinion Of Market Value' must be at least one dollar, and cannot be negative.","ruleLogic":"If OpinionOfValueAmount < 1","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Opinion of Market Value (%PV%)","dataPointName":"OpinionOfValueAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/","minValue":1},{"uniqueId":"1300.0017","dataElement":"OpinionOfValueAmount","messageId":"UAD1264","message":"'Opinion Of Market Value' must be less than a billion dollars.","ruleLogic":"If OpinionOfValueAmount > 1,000,000,000","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Opinion of Market Value (%PV%)","dataPointName":"OpinionOfValueAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/","maxValue":1000000000},{"uniqueId":"1300.0019","dataElement":"AdditionalClientRequestedConditionsIndicator","messageId":"UAD1265","message":"Indicate whether the client has requested additional value conditions.","ruleLogic":"If AdditionalClientRequestedConditionsIndicator is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"AdditionalClientRequestedConditionsIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_DETAIL/"},{"uniqueId":"1300.0021","dataElement":"ValuationReconciliationSummaryCommentDescription","messageId":"UAD1266","message":"Provide commentary for the reconciliation of market value.","ruleLogic":"If ValuationReconciliationSummaryCommentDescription is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Reconciliation of Market Value","reportLabel":"{No Label}","dataPointName":"ValuationReconciliationSummaryCommentDescription","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_DETAIL/"},{"uniqueId":"1300.0034","dataElement":"PropertyAsIsConditionRatingCode","messageId":"UAD1267","message":"Provide the 'As Is Overall Condition Rating' for the subject property.","ruleLogic":"If NewConstructionIndicator = \\"false\\" and (PropertyValuationConditionalConclusionType = \\"SubjectToCompletionPerPlans\\" or \\"SubjectToRepair\\") and PropertyAsIsConditionRatingCode is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"As Is Overall Condition Rating","dataPointName":"PropertyAsIsConditionRatingCode","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/"},{"uniqueId":"","dataElement":"INSPECTION_DETAIL","messageId":"UAD1268","message":"The exterior inspection method, interior inspection method, and inspection date must be delivered no more than once for each Appraiser and/or Supervisory Appraiser. In the UAD XML, only one instance of INSPECTION_DETAIL must be included for each Appraiser and/or Supervisory Appraiser. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If PartyRoleType = \\"Appraiser\\" or \\"AppraiserSupervisor\\" and (no instance of INSPECTION_DETAIL is provided for each role or more than one instance of INSPECTION_DETAIL is provided for each role)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Subject Property Ins
11pection","dataPointName":"INSPECTION_DETAIL","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/INSPECTION_DETAIL/"},{"uniqueId":"1400.0383","dataElement":"ObjectURL","messageId":"UAD1270","message":"Provide the location and file name of the appraisal (e.g., \\\\\\\\SF1Appraisal_v1.pdf). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ObjectURL is not provided in FOREIGN_OBJECT","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ObjectURL","xpath":"MESSAGE/DOCUMENT_SETS/DOCUMENT_SET/DOCUMENTS/DOCUMENT/VIEWS/VIEW/VIEW_FILES/VIEW_FILE/FOREIGN_OBJECT/"},{"uniqueId":"1400.0384","dataElement":"MIMETypeIdentifier","messageId":"UAD1272","message":"The MIMETypeIdentifier for the appraisal must be included as 'application/pdf' in the UAD XML. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If MIMETypeIdentifier in FOREIGN_OBJECT is not provided or not provided as \\"application/pdf\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MIMETypeIdentifier","xpath":"MESSAGE/DOCUMENT_SETS/DOCUMENT_SET/DOCUMENTS/DOCUMENT/VIEWS/VIEW/VIEW_FILES/VIEW_FILE/FOREIGN_OBJECT/"},{"uniqueId":"1400.0408","dataElement":"@MISMOReferenceModelIdentifier","messageId":"UAD1273","message":"Provide the MISMO Reference Model version. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @MISMOReferenceModelIdentifier is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@MISMOReferenceModelIdentifier","xpath":"MESSAGE/"},{"uniqueId":"1400.0619","dataElement":"ImageCategoryType","messageId":"UAD1274","message":"The required subject property photos must be included.","ruleLogic":"If instances of IMAGE with ImageCategoryType = DwellingFront, PropertyAccess, and PropertyPhoto are not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"ImageCategoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/"},{"uniqueId":"1400.0628","dataElement":"ImageCategoryType","messageId":"UAD1275","message":"Provide a photo of each sales comparable used in the valuation.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and there is no instance of IMAGE with ImageCategoryType = \\"PropertyPhoto\\"","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageCategoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/"},{"uniqueId":"1400.0634","dataElement":"ImageFileLocationIdentifier","messageId":"UAD1276","message":"Provide the file name and location of the image within the .zip file (e.g.,\\\\\\\\Images\\\\SF1_Comp2.png). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ImageFileLocationIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageFileLocationIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/","relatedValues":"ImageCategoryType (%RV1%)"},{"uniqueId":"1400.1013","dataElement":"ImageCategoryType","messageId":"UAD1278","message":"Provide a photo of the water frontage.","ruleLogic":"If PrivateAccessIndicator = \\"true\\" for any instance of BODY_OF_WATER where the SiteInfluenceType = \\"BodyOfWater\\" and there is no instance of IMAGE with ImageCategoryType = \\"WaterFrontage\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Exhibits","reportLabel":"{No Label}","dataPointName":"ImageCategoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/"},{"uniqueId":"","dataElement":"IMAGE","messageId":"UAD1279","message":"The mandatory room photos (i.e., kitchen, full-bathroom, half-bathroom) must be included.","ruleLogic":"If there is no instance of IMAGE in a given instance of ROOM with RoomType = \\"Kitchen\\" or \\"HalfBathroom\\" or \\"FullBathroom\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"IMAGE","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/ROOMS/ROOM/IMAGES/IMAGE/","relatedValues":"RoomType (%RV1%)"},{"uniqueId":"1400.0870","dataElement":"ImageCategoryType","messageId":"UAD1280","message":"Provide a photo of each GRM comparable used in the valuation.","ruleLogic":"If @ValuationUseType = \\"GrossRentMultiplierComparable\\" and there is no instance of IMAGE with ImageCategoryType = \\"PropertyPhoto\\"","severity":"Warning","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageCategoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/"},{"uniqueId":"1400.0876","dataElement":"ImageFileLocationIdentifier","messageId":"UAD1281","message":"Provide the file name and location of the image within the .zip f
11ile (e.g.,\\\\\\\\Images\\\\SF1_Comp2.png). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"GrossRentMultiplierComparable\\" and ImageFileLocationIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageFileLocationIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/","relatedValues":"ImageCategoryType (%RV1%)"},{"uniqueId":"1400.0905","dataElement":"MIMETypeIdentifier","messageId":"UAD1282","message":"Provide the format of the image file. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType=\\"GrossRentMultiplierComparable\\" and MIMETypeIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MIMETypeIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/","relatedValues":"ImageCategoryType (%RV1%)"},{"uniqueId":"1400.0915","dataElement":"ImageCategoryType","messageId":"UAD1283","message":"Provide the sales comparable map.","ruleLogic":"If SalesComparisonApproachIndicator = \\"true\\" and there is no instance of IMAGE with ImageCategoryType = \\"SalesComparableMap\\" in @ValuationUseType = \\"SubjectProperty\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageCategoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/"},{"uniqueId":"1400.0967","dataElement":"ImageCategoryType","messageId":"UAD1284","message":"Provide an image of the manufactured home HUD certification label.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and ManufacturedHomeHUDCertificateLabelIndicator = \\"true\\", and there is no instance of IMAGE with ImageCategoryType = \\"ManufacturedHomeHUDCertificationLabel\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"Manufactured Home Exhibits","reportLabel":"{No Label}","dataPointName":"ImageCategoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/"},{"uniqueId":"1400.0975","dataElement":"ImageCategoryType","messageId":"UAD1285","message":"Provide an image of the manufactured home HUD data plate.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and ManufacturedHomeHUDDataPlateAttachedIndicator = \\"true\\", and there is no instance of IMAGE with ImageCategoryType = \\"ManufacturedHomeHUDDataPlate\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"Manufactured Home Exhibits","reportLabel":"{No Label}","dataPointName":"ImageCategoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/"},{"uniqueId":"1500.0002","dataElement":"RestrictionType","messageId":"UAD1287","message":"Provide the type of property restriction.","ruleLogic":"If EncumbranceType = \\"ConditionsCovenantsRestrictions\\" and (at least one instance of CONDITION_COVENANT_RESTRICTION is not provided or RestrictionType is not provided in a given instance of CONDITION_COVENANT_RESTRICTION)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"RestrictionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/CONDITION_COVENANT_RESTRICTIONS/CONDITION_COVENANT_RESTRICTION/"},{"uniqueId":"1500.0003","dataElement":"RestrictionTypeOtherDescription","messageId":"UAD1288","message":"Provide a description when property restriction = 'Other'.","ruleLogic":"If RestrictionType = \\"Other\\" and RestrictionTypeOtherDescription is not provided in a given instance of CONDITION_COVENANT_RESTRICTION","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"RestrictionTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/CONDITION_COVENANT_RESTRICTIONS/CONDITION_COVENANT_RESTRICTION/"},{"uniqueId":"1500.0004","dataElement":"EasementType","messageId":"UAD1289","message":"Provide the easement type.","ruleLogic":"If EncumbranceType = \\"Easement\\" and (at least one instance of EASEMENT is not provided or EasementType is not provided in a given instance of EASEMENT)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"EasementType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/EASEMENTS/EASEMENT/"},{"uniqueId":"1500.0005","dataElement":"EasementTypeOtherDescription","messageId":"UAD1290","message":"Provide a description when easement = 'Other'.","ruleLogic":"If EasementType = \\"Other\\" and EasementTypeOtherDescription is not provided in a given instance of EASEMENT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"EasementTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/EASEMENTS/EASEMENT/"},{"uniqueId":"1500.0008","dataElement":"EncroachmentDirectionType","messageId":"UAD1291","message":"Provide the direction of the encroachment (i.e., bordering property encroaching on subject property, subject property encroaching on bordering property).","ruleLogic":"If EncroachmentDirectionType is not provided in a given instance of ENCROACHMENT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"EncroachmentDirectionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/ENCROACHMENTS/ENCROACHMENT/","relatedValues":"EncroachmentType (%RV1%)"},{"uniqueId":"1500.0009","dataElement":"EncroachmentType","messageId":"UAD1292","message":"Provide the encroachment type.","ruleLogic":"If EncumbranceType = \\"Encroachment\\" and (at least one instance of ENCROACHMENT is not provided or EncroachmentType is not provided in a given instance of ENCROACHMENT)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"EncroachmentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/ENCROACHMENTS/ENCROACHMENT/"},{"uniqueId":"1500.0010","dataElement":"EncroachmentTypeOtherDescription","messageId":"UAD1293","message":"Provide a description when encroachment = 'Other'.","ruleLogic":"If EncroachmentType = \\"Other\\" and EncroachmentTypeOtherDescription is not provided in a given instance of ENCROACHMENT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"EncroachmentTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/ENCROACHMENTS/ENCROACHMENT/"},{"uniqueId":"1500.0015","dataElement":"DistanceFromPropertyLinearMeasure","messageId":"UAD1294","message":"Provide the approximate distance from the property to the apparent environmental condition.","ruleLogic":"If EnvironmentalConditionType <> \\"None\\", and EnvironmentalConditionProximityType = \\"Bordering\\" or \\"Offsite\\", and DistanceFromPropertyLinearMeasure is not provided in a given instance of ENVIRONMENTAL_CONDITION","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Proximity","dataPointName":"DistanceFromPropertyLinearMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENVIRONMENTAL_CONDITIONS/ENVIRONMENTAL_CONDITION/","relatedValues":"EnvironmentalConditionType (%RV1%)"},{"uniqueId":"1500.0016","dataElement":"EnvironmentalConditionType","messageId":"UAD1296","message":"Provide the type of apparent environmental condition. Select 'None' if there are no apparent environmental conditions.","ruleLogic":"If at least one instance of ENVIRONMENTAL_CONDITION is not provided or EnvironmentalConditionType is not provided in a given instance of ENVIRONMENTAL_CONDITION","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Detail","dataPointName":"EnvironmentalConditionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENVIRONMENTAL_CONDITIONS/ENVIRONMENTAL_CONDITION/"},{"uniqueId":"1500.0017","dataElement":"EnvironmentalConditionTypeOtherDescription","messageId":"UAD1297","message":"Provide a description when apparent environmental condition = 'Other'.","ruleLogic":"If EnvironmentalConditionType = \\"Other\\" and EnvironmentalConditionTypeOtherDescription is not provided in a given instance of ENVIRONMENTAL_CONDITION","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Detail","dataPointName":"EnvironmentalConditionTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENVIRONMENTAL_CONDITIONS/ENVIRONMENTAL_CONDITION/"},{"uniqueId":"1500.0018","dataElement":"EnvironmentalConditionProximityType","messageId":"UAD1298","message":"Provide the proximity type (i.e., Bordering, Offsite, Onsite) for the apparent environmental condition.","ruleLogic":"If EnvironmentalConditionType <> \\"None\\" and EnvironmentalConditionProximityType is not provided in a given instance of ENVIRONMENTAL_CONDITION","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Proximity","dataPointName":"EnvironmentalConditionProximityType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENVIRONMENTAL_CONDITIONS/ENVIRONMENTAL_CONDITION/","relatedValues":"EnvironmentalConditionType (%RV1%)"},{"uniqueId":"1500.0020","dataElement":"ParcelSeparatorType","messageId":"UAD1299","message":"Provide the 'Elements Dividing Parcels'.","ruleLogic":"If ParcelsContiguousIndicator = \\"false\\" and (at least one instance of NON_CONTIGUOUS_PARCEL_SEPARATOR is not provided or ParcelSeparatorType is not provided in a given instance of NON_CONTIGUOUS_PARCEL_SEPARATOR)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Elements Dividing Parcels","dataPointName":"ParcelSeparatorType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PARCEL_SUMMARY/NON_CONTIGUOUS_PARCEL_SEPARATORS/NON_CONTIGUOUS_PARCEL_SEPARATOR/"},{"uniqueId":"1500.0021","dataElement":"ParcelSeparatorTypeOtherDescription","messageId":"UAD1300","message":"Provide a description when 'Elements Dividing Parcels' = 'Other'.","ruleLogic":"If ParcelSeparatorType = \\"Other\\" and ParcelSeparatorTypeOtherDescription is not provided in a given instance of NON_CONTIGUOUS_PARCEL_SEPARATOR","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Elements Dividing Parcels","dataPointName":"ParcelSeparatorTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PARCEL_SUMMARY/NON_CONTIGUOUS_PARCEL_SEPARATORS/NON_CONTIGUOUS_PARCEL_SEPARATOR/"},{"uniqueId":"1500.0022","dataElement":"ParcelAreaMeasure","messageId":"UAD1301","message":"Provide the size of each parcel.","ruleLogic":"If LandOwnedInCommonIndicator = \\"false\\", and (ParcelDescriptionClassificationType = \\"VacantLand\\" or \\"LandWithDwelling\\" or \\"LandWithImprovement\\"), and ParcelAreaMeasure is not provided in a given instance of PARCEL_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Parcel Size","dataPointName":"ParcelAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PARCELS/PARCEL/PARCEL_DETAIL/","relatedValues":"ParcelDescriptionClassificationType (%RV1%)"},{"uniqueId":"1500.0023","dataElement":"ParcelDescriptionClassificationType","messageId":"UAD1302","message":"Provide the 'APN Description'.","ruleLogic":"If PropertyInProjectIndicator = \\"false\\" or (PropertyInProjectIndicator = \\"true\\" and ProjectLegalStructureType = \\"Condominium\\"), and (PARCEL_DETAIL is not provided or ParcelDescriptionClassificationType is not provided in a given instance of PARCEL)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"APN Description","dataPointName":"ParcelDescriptionClassificationType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PARCELS/PARCEL/PARCEL_DETAIL/"},{"uniqueId":"1500.0024","dataElement":"ParcelDescriptionClassificationTypeOtherDescription","messageId":"UAD1303","message":"Provide a description when 'APN Description' = 'Other'.","ruleLogic":"If ParcelDescriptionClassificationType = \\"Other\\" and ParcelDescriptionClassificationTypeOtherDescription is not provided in a given instance of PARCEL_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"APN Description","dataPointName":"ParcelDescriptionClassificationTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PARCELS/PARCEL/PARCEL_DETAIL/"},{"uniqueId":"1500.0026","dataElement":"ParcelIdentificationType","messageId":"UAD1304","message":"Provide ParcelIdentificationType = 'AssessorUnformattedIdentifier' for each parcel. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If PropertyInProjectIndicator = \\"false\\" or (PropertyInProjectIndicator = \\"true\\" and ProjectLegalStructureType = \\"Condominium\\"), and at least one instance of PARCEL container with ParcelIdentificationType = \\"AssessorUnformattedIdentifier\\" is not provided or a given instance of PARCEL container does not include ParcelIdentificationType = \\"AssessorUnformattedIdentifier\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ParcelIdentificationType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PARCELS/PARCEL/PARCEL_IDENTIFICATIONS/PARCEL_IDENTIFICATION/","relatedValues":"ParcelIdentifier (%RV1%)"},{"uniqueId":"1500.0027","dataElement":"ParcelIdentifier","messageId":"UAD1305","message":"Provide the 'Assessor Parcel Number (APN)'.","ruleLogic":"If ParcelIdentificationType = \\"AssessorUnformattedIdentifier\\" and ParcelIdentifier is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Assessor Parcel Number (APN)","dataPointName":"ParcelIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PARCELS/PARCEL/PARCEL_IDENTIFICATIONS/PARCEL_IDENTIFICATION/","relatedValues":"ParcelIdentificationType (%RV1%)"},{"uniqueId":"1500.0031","dataElement":"CommunityLandTrustIndicator","messageId":"UAD1306","message":"Indicate whether the subject property is located in a community land trust.","ruleLogic":"If PropertyEstateType = \\"Leasehold\\" or \\"Other\\", and CommunityLandTrustIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"Ownership Rights","reportLabel":"Community Land Trust","dataPointName":"CommunityLandTrustIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1500.0032","dataElement":"NonResidentialModificationIndicator","messageId":"UAD1307","message":"Indicate whether the property has been modified to allow for non-residential uses.","ruleLogic":"If LandOwnedInCommonIndicator = \\
11"false\\", and PropertyMixedUsageIndicator = \\"true\\", and NonResidentialModificationIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Non-Residential Modification","dataPointName":"NonResidentialModificationIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_USE_SUMMARY/"},{"uniqueId":"1500.0034","dataElement":"PropertyMixedUsageIndicator","messageId":"UAD1308","message":"Indicate whether the property has any non-residential uses.","ruleLogic":"If LandOwnedInCommonIndicator = \\"false\\" and PropertyMixedUsageIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Non-Residential Use","dataPointName":"PropertyMixedUsageIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_USE_SUMMARY/"},{"uniqueId":"1500.0036","dataElement":"PropertyPrimarilyResidentialUseIndicator","messageId":"UAD1309","message":"Indicate whether the property is primarily residential.","ruleLogic":"If LandOwnedInCommonIndicator = \\"false\\", and PropertyMixedUsageIndicator = \\"true\\", and PropertyPrimarilyResidentialUseIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Primarily Residential","dataPointName":"PropertyPrimarilyResidentialUseIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_USE_SUMMARY/"},{"uniqueId":"1500.0039","dataElement":"NonResidentialUseType","messageId":"UAD1310","message":"Provide the non-residential use type.","ruleLogic":"If LandOwnedInCommonIndicator = \\"false\\", and PropertyMixedUsageIndicator = \\"true\\", and ( at least one instance of PROPERTY_USE is not provided or NonResidentialUseType is not provided in a given instance of PROPERTY_USE)","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Non-Residential Use","dataPointName":"NonResidentialUseType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_USES/PROPERTY_USE/"},{"uniqueId":"1500.0040","dataElement":"NonResidentialUseTypeOtherDescription","messageId":"UAD1311","message":"Provide a description when 'Non-Residential Use' = 'Other'.","ruleLogic":"If NonResidentialUseType = \\"Other\\" and NonResidentialUseTypeOtherDescription is not provided in a given instance of PROPERTY_USE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Non-Residential Use","dataPointName":"NonResidentialUseTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_USES/PROPERTY_USE/"},{"uniqueId":"1500.0042","dataElement":"HazardZoneType","messageId":"UAD1313","message":"The type of hazard zone must be included. Select 'None' if the property is not in a hazard zone.","ruleLogic":"If at least one instance of HAZARD_ZONE is not provided or HazardZoneType is not provided in a given instance of HAZARD_ZONE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"HazardZoneType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HAZARD_ZONES/HAZARD_ZONE/"},{"uniqueId":"1500.0043","dataElement":"HazardZoneTypeOtherDescription","messageId":"UAD1314","message":"Provide a description when hazard zone type = 'Other'.","ruleLogic":"If HazardZoneType = \\"Other\\" and HazardZoneTypeOtherDescription is not provided in a given instance of HAZARD_ZONE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"HazardZoneTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HAZARD_ZONES/HAZARD_ZONE/"},{"uniqueId":"1500.0045","dataElement":"LavaFlowZoneCode","messageId":"UAD1315","message":"Provide the lava flow zone.","ruleLogic":"If HazardZoneType = \\"USGSLavaFlowZone\\" and LavaFlowZoneCode is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"LavaFlowZoneCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HAZARD_ZONES/HAZARD_ZONE/"},{"uniqueId":"1500.0052","dataElement":"PrivateStreetMaintenanceAgreementExistIndicator","messageId":"UAD1316","message":"Indicate whether the private street maintenance agreement exists.","ruleLogic":"If PropertyPrimaryEntryExitMethodType = \\"PrivateStreet\\" and PrivateStreetMaintenanceAgreementExistIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Known Maintenance Agreement","dataPointName":"PrivateStreetMaintenanceAgreementExistIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/PROPERTY_ACCESS/PROPERTY_ACCESS_DETAIL/"},{"uniqueId":"1500.0054","dataElement":"PropertyAccessTypicalToMarketIndicator","messageId":"UAD1317","message":"Indicate whether the property access is common for the market.","ruleLogic":"If PropertyAccessTypicalToMarketIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Typical for Market","dataPointName":"PropertyAccessTypicalToMarketIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/PROPERTY_ACCESS/PROPERTY_ACCESS_DETAIL/"},{"uniqueId":"1500.0055","dataElement":"PropertyPrimaryEntryExitMethodType","messageId":"UAD1318","message":"Provide the primary ingress / egress method for the property.","ruleLogic":"If PropertyPrimaryEntryExitMethodType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Primary Access","dataPointName":"PropertyPrimaryEntryExitMethodType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/PROPERTY_ACCESS/PROPERTY_ACCESS_DETAIL/"},{"uniqueId":"1500.0056","dataElement":"PropertyPrimaryEntryExitMethodTypeOtherDescription","messageId":"UAD1319","message":"Provide a description when 'Primary Access' = 'Other'.","ruleLogic":"If PropertyPrimaryEntryExitMethodType = \\"Other\\" and PropertyPrimaryEntryExitMethodTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Primary Access","dataPointName":"PropertyPrimaryEntryExitMethodTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/PROPERTY_ACCESS/PROPERTY_ACCESS_DETAIL/"},{"uniqueId":"1500.0060","dataElement":"SiteDrainageReasonType","messageId":"UAD1320","message":"Provide the type of the site drainage reason.","ruleLogic":"If SiteFeatureType = \\"Drainage\\" and (at least one instance of DRAINAGE_IMPACT_REASON is not provided or SiteDrainageReasonType is not provided in a given instance of DRAINAGE_IMPACT_REASON)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"SiteDrainageReasonType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_FEATURES/SITE_FEATURE/DRAINAGE_IMPACT_REASONS/DRAINAGE_IMPACT_REASON/"},{"uniqueId":"1500.0061","dataElement":"SiteDrainageReasonTypeOtherDescription","messageId":"UAD1321","message":"Provide a description when site drainage reason = 'Other'.","ruleLogic":"If SiteDrainageReasonType = \\"Other\\" and SiteDrainageReasonTypeOtherDescription is not provided in a given instance of DRAINAGE_IMPACT_REASON","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"SiteDrainageReasonTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_FEATURES/SITE_FEATURE/DRAINAGE_IMPACT_REASONS/DRAINAGE_IMPACT_REASON/"},{"uniqueId":"1500.0062","dataElement":"SiteFeatureType","messageId":"UAD1323","message":"The type of site feature must be included. Select 'None' if there are no site features reported by the Appraiser.","ruleLogic":"If at least one instance of SITE_FEATURE_DETAIL is not provided or SiteFeatureType is not provided in a given instance of SITE_FEATURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"SiteFeatureType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_FEATURES/SITE_FEATURE/SITE_FEATURE_DETAIL/"},{"uniqueId":"1500.0063","dataElement":"SiteFeatureTypeOtherDescription","messageId":"UAD1324","message":"Provide a description when site characteristic = 'Other'.","ruleLogic":"If SiteFeatureType = \\"Other\\" and SiteFeatureTypeOtherDescription is not provided in a given instance of SITE_FEATURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"SiteFeatureTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_FEATURES/SITE_FEATURE/SITE_FEATURE_DETAIL/"},{"uniqueId":"1500.0065","dataElement":"TopographyType","messageId":"UAD1325","message":"Provide the type of topography.","ruleLogic":"If SiteFeatureType = \\"Topography\\" and (at least one instance of TOPOGRAPHY is not provided or TopographyType is not provided in a given instance of TOPOGRAPHY)","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"TopographyType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_FEATURES/SITE_FEATURE/TOPOGRAPHIES/TOPOGRAPHY/"},{"uniqueId":"1500.0066","dataElement":"TopographyTypeOtherDescription","messageId":"UAD1326","message":"Provide a description when topography = 'Other'.","ruleLogic":"If TopographyType = \\"Other\\" and TopographyTypeOtherDescription is not provided in a given instance of TOPOGRAPHY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"TopographyTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_FEATURES/SITE_FEATURE/TOPOGRAPHIES/TOPOGRAPHY/"},{"uniqueId":"1500.0087","dataElement":"SiteInfluenceType","messageId":"UAD1328","message":"The type of site influence must be included.","ruleLogic":"If at least one instance of SITE_INFLUENCE_DETAIL is not provided or SiteInfluenceType is not provided in a given instance of SITE_INFLUENCE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Influence","dataPointName":"SiteInfluenceType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/SITE_INFLUENCE_DETAIL/"},{"uniqueId":"1500.0088","dataElement":"SiteInfluenceTypeOtherDescription","messageId":"UAD1329","message":"Provide a description when site influence = 'Other'.","ruleLogic":"If SiteInfluenceType = \\"Other\\" and SiteInfluenceTypeOtherDescription is not provided in a given instance of SITE_INFLUENCE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Influence","dataPointName":"SiteInfluenceTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/SITE_INFLUENCE_DETAIL/"},{"uniqueId":"1500.0086","dataElement":"SiteInfluenceProximityType","messageId":"UAD1330","message":"Provide the proximity type (i.e., Bordering, Offsite, Onsite) for the site influence.","ruleLogic":"If SiteInfluenceProximityType is not provided in a given instance of SITE_INFLUENCE_DETAIL with SiteInfluenceType <> \\"BodyOfWater\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Proximity","dataPointName":"SiteInfluenceProximityType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/SITE_INFLUENCE_DETAIL/","relatedValues":"SiteInfluenceType (%RV1%)"},{"uniqueId":"1500.0073","dataElement":"BodyOfWaterType","messageId":"UAD1331","message":"Provide the body of water type (e.g., river, lake, ocean).","ruleLogic":"If SiteInfluenceType = \\"BodyOfWater\\" and (at least one instance of BODY_OF_WATER is not provided or BodyOfWaterType is not provided in a given instance of BODY_OF_WATER)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Detail","dataPointName":"BodyOfWaterType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/BODIES_OF_WATER/BODY_OF_WATER/"},{"uniqueId":"1500.0074","dataElement":"BodyOfWaterTypeOtherDescription","messageId":"UAD1332","message":"Provide a description when body of water = 'Other'.","ruleLogic":"If BodyOfWaterType = \\"Other\\" and BodyOfWaterTypeOtherDescription is not provided in a given instance of BODY_OF_WATER","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Detail","dataPointName":"BodyOfWaterTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/BODIES_OF_WATER/BODY_OF_WATER/"},{"uniqueId":"1500.0079","dataElement":"WaterAccessRightType","messageId":"UAD1333","message":"Provide the 'Waterfront Access Rights'.","ruleLogic":"If SiteInfluenceType = \\"BodyOfWater\\" and PrivateAccessIndicator = \\"true\\", and WaterAccessRightType is not provided in a given instance of BODY_OF_WATER","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Waterfront Access Rights","dataPointName":"WaterAccessRightType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/BODIES_OF_WATER/BODY_OF_WATER/","relatedValues":"BodyOfWaterType (%RV1%)"},{"uniqueId":"1500.0080","dataElement":"WaterAccessRightTypeOtherDescription","messageId":"UAD1334","message":"Provide a description when 'Waterfront Access Rights' = 'Other'.","ruleLogic":"If WaterAccessRightType = \\"Other\\" and WaterAccessRightTypeOtherDescription is not provided in a given instance of BODY_OF_WATER","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Waterfront Access Rights","dataPointName":"WaterAccessRightTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/BODIES_OF_WATER/BODY_OF_WATER/"},{"uniqueId":"1500.0082","dataElement":"WaterfrontFeatureType","messageId":"UAD1335","message":"Provide the 'Permanent Waterfront Feature'.","ruleLogic":"If SiteInfluenceType = \\"BodyOfWater\\" and PrivateAccessIndicator = \\"true\\" for one or more BODY_OF_WATER, and (at least one instance of WATER_FRONT_FEATURE is not provided or WaterfrontFeatureType is not provided in a given instance of WATER_FRONT_FEATURE)","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Permanent Waterfront Feature","dataPointName":"WaterfrontFeatureType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/BODIES_OF_WATER/WATER_FRONT_FEATURES/WATER_FRONT_FEATURE/","relatedValues":"SiteInfluenceType (%RV1%)"},{"uniqueId":"1500.0083","dataElement":"WaterfrontFeatureTypeOtherDescription","messageId":"UAD1336","message":"Provide a description when 'Permanent Waterfront Feature' = 'Other'.","ruleLogic":"If WaterfrontFeatureType = \\"Other\\" and WaterfrontFeatureTypeOtherDescription is not provided in a given instance of WATER_FRONT_FEATURE","
11severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Permanent Waterfront Feature","dataPointName":"WaterfrontFeatureTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/BODIES_OF_WATER/WATER_FRONT_FEATURES/WATER_FRONT_FEATURE/"},{"uniqueId":"1500.0197","dataElement":"WaterAccessDepthType","messageId":"UAD1337","message":"Provide the 'Water Frontage Access Depth'.","ruleLogic":"If SiteInfluenceType = \\"BodyOfWater\\" and PrivateAccessIndicator = \\"true\\", and WaterAccessDepthType is not provided in a given instance of BODY_OF_WATER","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Access Depth","dataPointName":"WaterAccessDepthType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/BODIES_OF_WATER/BODY_OF_WATER/","relatedValues":"BodyOfWaterType (%RV1%)"},{"uniqueId":"1500.0198","dataElement":"WaterAccessDepthTypeOtherDescription","messageId":"UAD1338","message":"Provide a description when 'Water Frontage Access Depth' = 'Other'.","ruleLogic":"If WaterAccessDepthType = \\"Other\\" and WaterAccessDepthTypeOtherDescription is not provided in a given instance of BODY_OF_WATER","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Access Depth","dataPointName":"WaterAccessDepthTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/BODIES_OF_WATER/BODY_OF_WATER/"},{"uniqueId":"1500.0091","dataElement":"WaterFrontageTotalLengthLinearMeasure","messageId":"UAD1339","message":"Provide the 'Total Linear Measurement' for waterfront.","ruleLogic":"If PrivateAccessIndicator = \\"true\\" for one or more instances of BODY_OF_WATER and WaterFrontageTotalLengthLinearMeasure is not provided in a given instance of SITE_INFLUENCE_DETAIL with SiteInfluenceType = \\"BodyOfWater\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Total Linear Measurement","dataPointName":"WaterFrontageTotalLengthLinearMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/SITE_INFLUENCE_DETAIL/","relatedValues":"SiteInfluenceType (%RV1%)"},{"uniqueId":"1500.0092","dataElement":"WaterfrontDevelopmentRightsIndicator","messageId":"UAD1340","message":"Indicate whether the property has rights to develop waterfront features.","ruleLogic":"If WaterfrontFeatureType = \\"None\\" and WaterfrontDevelopmentRightsIndicator is not provided in a given instance of SITE_INFLUENCE_DETAIL with SiteInfluenceType = \\"BodyOfWater\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Site Influence","reportLabel":"Right to Build","dataPointName":"WaterfrontDevelopmentRightsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/SITE_INFLUENCE_DETAIL/","relatedValues":"SiteInfluenceType (%RV1%)"},{"uniqueId":"1500.0093","dataElement":"LotSizeAreaMeasure","messageId":"UAD1341","message":"Provide the total site (lot) size.","ruleLogic":"If LandOwnedInCommonIndicator = \\"false\\" and LotSizeAreaMeasure is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Total Site Size","dataPointName":"LotSizeAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_SIZE_LAYOUT/"},{"uniqueId":"1500.0094","dataElement":"ParcelCount","messageId":"UAD1342","message":"Provide the 'Number of Parcels'.","ruleLogic":"If LandOwnedInCommonIndicator = \\"false\\" and ParcelCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Number of Parcels","dataPointName":"ParcelCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_SIZE_LAYOUT/"},{"uniqueId":"1500.0095","dataElement":"ParcelsContiguousIndicator","messageId":"UAD1343","message":"Indicate whether the parcels are contiguous.","ruleLogic":"If LandOwnedInCommonIndicator = \\"false\\", and ParcelCount > 1, and ParcelsContiguousIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Contiguous","dataPointName":"ParcelsContiguousIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_SIZE_LAYOUT/"},{"uniqueId":"1500.0104","dataElement":"UtilityType","messageId":"UAD1344","message":"The type of utility must be included.","ruleLogic":"If UtilityType is not provided in a given instance of SITE_UTILITY_DETAIL or no instance of UtilityType is delivered","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"{No Label}","dataPointName":"UtilityType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_DETAIL/"},{"uniqueId":"1500.0104","dataElement":"UtilityType","messageId":"UAD1345","message":"Provide details on the electricity connection.","ruleLogic":"If no instances of SITE_UTILITY_DETAIL with UtilityType = \\"Electricity\\" are provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"{No Label}","dataPointName":"UtilityType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_DETAIL/"},{"uniqueId":"1500.0104","dataElement":"UtilityType","messageId":"UAD1346","message":"Provide details on the water connection.","ruleLogic":"If no instances of SITE_UTILITY_DETAIL with UtilityType = \\"Water\\" are provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"{No Label}","dataPointName":"UtilityType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_DETAIL/"},{"uniqueId":"1500.0104","dataElement":"UtilityType","messageId":"UAD1347","message":"Provide details on the sewer connection.","ruleLogic":"If no instances of SITE_UTILITY_DETAIL with UtilityType = \\"SanitarySewer\\" are provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"{No Label}","dataPointName":"UtilityType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_DETAIL/"},{"uniqueId":"1500.0105","dataElement":"UtilityTypeOtherDescription","messageId":"UAD1348","message":"Provide a description when 'Utility Type' = 'Other'.","ruleLogic":"If UtilityType = \\"Other\\" and UtilityTypeOtherDescription is not provided in a given instance of SITE_UTILITY_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"{No Label}","dataPointName":"UtilityTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_DETAIL/"},{"uniqueId":"1500.0102","dataElement":"SiteUtilityOwnershipType","messageId":"UAD1349","message":"Indicate whether the utility is public or private.","ruleLogic":"If SiteUtilityOwnershipType is not provided in a given instance of SITE_UTILITY_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Public/Private","dataPointName":"SiteUtilityOwnershipType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_DETAIL/","relatedValues":"UtilityType (%RV1%)"},{"uniqueId":"1500.0103","dataElement":"UtilitySharedIndicator","messageId":"UAD1350","message":"Indicate whether the utility is shared.","ruleLogic":"If SiteUtilityOwnershipType = \\"NonPublic\\" and UtilitySharedIndicator is not provided in a given instance of SITE_UTILITY_SERVICE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"UtilitySharedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_SERVICES/SITE_UTILITY_SERVICE/","relatedValues":"UtilityType (%RV1%)"},{"uniqueId":"1500.0183","dataElement":"ValueMarketabilityImpactType","messageId":"UAD1351","message":"Provide the impact to value / marketability for the private utility.","ruleLogic":"If SiteUtilityOwnershipType = \\"NonPublic\\" and ValueMarketabilityImpactType is not provided in a given instance of SITE_UTILITY_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Private Utility Impact","dataPointName":"ValueMarketabilityImpactType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_DETAIL/","relatedValues":"UtilityType (%RV1%)"},{"uniqueId":"1500.0106","dataElement":"ElectricitySourceType","messageId":"UAD1352","message":"Provide the private electricity source.","ruleLogic":"If UtilityType = \\"Electricity\\" and SiteUtilityOwnershipType = \\"NonPublic\\", and (at least one instance of SITE_UTILITY_SERVICE is not provided or ElectricitySourceType is not provided in a given instance of SITE_UTILITY_SERVICE)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ElectricitySourceType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_SERVICES/SITE_UTILITY_SERVICE/"},{"uniqueId":"1500.0106","dataElement":"ElectricitySourceType","messageId":"UAD1353","message":"No public electricity connection has been identified. Please check for accuracy.","ruleLogic":"If there are no instances of SITE_UTILITY_DETAIL with UtilityType = \\"Electricity\\" and SiteUtilityOwnershipType = \\"Public\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ElectricitySourceType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_SERVICES/SITE_UTILITY_SERVICE/"},{"uniqueId":"1500.0107","dataElement":"ElectricitySourceTypeOtherDescription","messageId":"UAD1354","message":"Provide a description when private electricity source = 'Other'.","ruleLogic":"If ElectricitySourceType = \\"Other\\" and ElectricitySourceTypeOtherDescription is not provided in a given instance of SITE_UTILITY_SERVICE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ElectricitySourceTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_SERVICES/SITE_UTILITY_SERVICE/"}
11,{"uniqueId":"1500.0108","dataElement":"SewerSystemType","messageId":"UAD1355","message":"Provide the type of private sewer system.","ruleLogic":"If UtilityType = \\"SanitarySewer\\" and SiteUtilityOwnershipType = \\"NonPublic\\", and (at least one instance of SITE_UTILITY_SERVICE is not provided or SewerSystemType is not provided in a given instance of SITE_UTILITY_SERVICE)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"SewerSystemType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_SERVICES/SITE_UTILITY_SERVICE/"},{"uniqueId":"1500.0109","dataElement":"SewerSystemTypeOtherDescription","messageId":"UAD1356","message":"Provide a description when private sewer system = 'Other'.","ruleLogic":"If SewerSystemType = \\"Other\\" and SewerSystemTypeOtherDescription is not provided in a given instance of SITE_UTILITY_SERVICE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"SewerSystemTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_SERVICES/SITE_UTILITY_SERVICE/"},{"uniqueId":"1500.0111","dataElement":"WaterSourceType","messageId":"UAD1357","message":"Provide the type of water source.","ruleLogic":"If UtilityType = \\"Water\\" and SiteUtilityOwnershipType = \\"NonPublic\\", and (at least one instance of SITE_UTILITY_SERVICE is not provided or WaterSourceType is not provided in a given instance of SITE_UTILITY_SERVICE)","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"WaterSourceType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_SERVICES/SITE_UTILITY_SERVICE/"},{"uniqueId":"1500.0112","dataElement":"WaterSourceTypeOtherDescription","messageId":"UAD1358","message":"Provide a description when water source = 'Other'.","ruleLogic":"If WaterSourceType = \\"Other\\" and WaterSourceTypeOtherDescription is not provided in a given instance of SITE_UTILITY_SERVICE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"WaterSourceTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_SERVICES/SITE_UTILITY_SERVICE/"},{"uniqueId":"1500.0114","dataElement":"WaterWellTypeOtherDescription","messageId":"UAD1359","message":"Provide a description when water well type = 'Other'.","ruleLogic":"If WaterWellType = \\"Other\\" and WaterWellTypeOtherDescription is not provided in a given instance of SITE_UTILITY_SERVICE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"WaterWellTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_UTILITIES/SITE_UTILITY/SITE_UTILITY_SERVICES/SITE_UTILITY_SERVICE/"},{"uniqueId":"1500.0120","dataElement":"ViewType","messageId":"UAD1361","message":"The type of view must be included.","ruleLogic":"If at least one instance of SITE_VIEW is not provided or ViewType is not provided in a given instance of SITE_VIEW","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"View and Impact to Value / Marketability","reportLabel":"View","dataPointName":"ViewType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_VIEWS/SITE_VIEW/"},{"uniqueId":"1500.0121","dataElement":"ViewTypeOtherDescription","messageId":"UAD1362","message":"Provide a description when view type = 'Other'.","ruleLogic":"If ViewType = \\"Other\\" and ViewTypeOtherDescription is not provided in a given instance of SITE_VIEW","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"View and Impact to Value / Marketability","reportLabel":"View","dataPointName":"ViewTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_VIEWS/SITE_VIEW/"},{"uniqueId":"1500.0117","dataElement":"ViewPrimaryIndicator","messageId":"UAD1363","message":"Indicate whether the view is the primary view.","ruleLogic":"If ViewPrimaryIndicator is not provided in a given instance of SITE_VIEW","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"View and Impact to Value / Marketability","reportLabel":"(Primary)","dataPointName":"ViewPrimaryIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_VIEWS/SITE_VIEW/","relatedValues":"ViewType (%RV1%)"},{"uniqueId":"1500.0118","dataElement":"ViewRangeType","messageId":"UAD1364","message":"Provide 'Range of View'.","ruleLogic":"If ViewRangeType is not provided in a given instance of SITE_VIEW","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"View and Impact to Value / Marketability","reportLabel":"Range of View","dataPointName":"ViewRangeType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_VIEWS/SITE_VIEW/","relatedValues":"ViewType (%RV1%)"},{"uniqueId":"1500.0119","dataElement":"ViewRangeTypeOtherDescription","messageId":"UAD1365","message":"Provide a description when range of view = 'Other'.","ruleLogic":"If ViewRangeType = \\"Other\\" and ViewRangeTypeOtherDescription is not provided in a given instance of SITE_VIEW","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"View and Impact to Value / Marketability","reportLabel":"Range of View","dataPointName":"ViewRangeTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_VIEWS/SITE_VIEW/"},{"uniqueId":"1500.0184","dataElement":"ValueMarketabilityImpactType","messageId":"UAD1366","message":"Provide the type of impact the selected view has on the value and marketability of the property.","ruleLogic":"If ValueMarketabilityImpactType is not provided in a given instance of SITE_VIEW","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"View and Impact to Value / Marketability","reportLabel":"Impact","dataPointName":"ValueMarketabilityImpactType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_VIEWS/SITE_VIEW/","relatedValues":"ViewType (%RV1%)"},{"uniqueId":"1500.0122","dataElement":"SiteZoningClassificationIdentifier","messageId":"UAD1367","message":"Provide the site zoning classification code.","ruleLogic":"If SiteZoningComplianceType <> \\"NoZoning\\" and SiteZoningClassificationIdentifier is not provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Classification Code","dataPointName":"SiteZoningClassificationIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_ZONING/SITE_ZONING_DETAIL/"},{"uniqueId":"1500.0123","dataElement":"SiteZoningClassificationDescription","messageId":"UAD1368","message":"Provide the site zoning classification code description.","ruleLogic":"If SiteZoningComplianceType <> \\"NoZoning\\" and SiteZoningClassificationDescription is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Classification Code Description","dataPointName":"SiteZoningClassificationDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_ZONING/SITE_ZONING_DETAIL/"},{"uniqueId":"1500.0125","dataElement":"SiteZoningComplianceType","messageId":"UAD1369","message":"Provide 'Zoning Compliance'.","ruleLogic":"If SiteZoningComplianceType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Compliance","dataPointName":"SiteZoningComplianceType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_ZONING/SITE_ZONING_DETAIL/"},{"uniqueId":"1500.0128","dataElement":"SiteZoningComplianceIllegalReasonType","messageId":"UAD1370","message":"Provide the 'Reasons Illegal' for site zoning.","ruleLogic":"If SiteZoningComplianceType = \\"Illegal\\" and (at least one instance of ZONING_ILLEGAL_REASON is not provided or SiteZoningComplianceIllegalReasonType is not provided in a given instance of ZONING_ILLEGAL_REASON)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Reasons Illegal","dataPointName":"SiteZoningComplianceIllegalReasonType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_ZONING/ZONING_ILLEGAL_REASONS/ZONING_ILLEGAL_REASON/"},{"uniqueId":"1500.0129","dataElement":"SiteZoningComplianceIllegalReasonTypeOtherDescription","messageId":"UAD1371","message":"Provide a description when 'Reasons Illegal' = 'Other'.","ruleLogic":"If SiteZoningComplianceIllegalReasonType = \\"Other\\" and SiteZoningComplianceIllegalReasonTypeOtherDescription is not provided in a given instance of ZONING_ILLEGAL_REASON","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Reasons Illegal","dataPointName":"SiteZoningComplianceIllegalReasonTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_ZONING/ZONING_ILLEGAL_REASONS/ZONING_ILLEGAL_REASON/"},{"uniqueId":"1500.0166","dataElement":"BroadbandInternetAvailableIndicator","messageId":"UAD1372","message":"Indicate whether the broadband internet is available for the market.","ruleLogic":"If BroadbandInternetAvailableIndicator is not provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Utilities and Impact to Value / Marketability","reportLabel":"Broadband Internet Available","dataPointName":"BroadbandInternetAvailableIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_DETAIL/"},{"uniqueId":"1500.0178","dataElement":"SiteDefectsExistIndicator","messageId":"UAD1373","message":"Indicate whether any defects, damages, or deficiencies are observed on the site.","ruleLogic":"If SiteDefectsExistIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Site","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"{No Label}","dataPointName":"SiteDefectsExistIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_DETAIL/"},{"uniqueId":"1500.0185","dataElement":"ValuationAnalysisCategoryType","messageId":"UAD1374","message":"Provide ValuationAnalysisCategoryType = 'HazardZones' when the property is in a hazard zone. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If HazardZoneType <> \\"None\\" for @ValuationUseType = \\"SubjectProperty\\", and there is no instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"HazardZones\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ValuationAnalysisCategoryType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/"},{"uniqueId":"1500.0187","dataElement":"ValueMarketabilityImpactType","messageId":"UAD1375","message":"The impact to value / marketability must be provided when the subject property is in a hazard zone.","ruleLogic":"If HazardZoneType <> \\"None\\" for @ValuationUseType = \\"SubjectProperty\\", and (ValueMarketabilityImpactType is not provided in the instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"HazardZones\\" or there is no instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"HazardZones\\")","severity":"Fatal","propertyAffected":"N/A","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Impact","dataPointName":"ValueMarketabilityImpactType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/","relatedValues":"ValuationAnalysisCategoryType (HazardZones)"},{"uniqueId":"1500.0191","dataElement":"ValuationAnalysisCategoryType","messageId":"UAD1377","message":"Provide ValuationAnalysisCategoryType = 'ZoningCompliance' when the current use of the land or structure does not comply with local zoning regulations. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If SiteZoningComplianceType <> \\"Legal\\" for @ValuationUseType = \\"SubjectProperty\\", and there is no instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"ZoningCompliance\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ValuationAnalysisCategoryType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/"},{"uniqueId":"1500.0193","dataElement":"ValueMarketabilityImpactType","messageId":"UAD1378","message":"Provide the impact to value / marketability for site zoning.","ruleLogic":"If SiteZoningComplianceType <> \\"Legal\\" for @ValuationUseType = \\"SubjectProperty\\", and (ValueMarketabilityImpactType is not provided in the instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"ZoningCompliance\\" or there is no instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"ZoningCompliance\\")","severity":"Fatal","propertyAffected":"N/A","reportSection":"Site","reportSubsection":"{No Subsection}","reportLabel":"Impact","dataPointName":"ValueMarketabilityImpactType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/","relatedValues":"ValuationAnalysisCategoryType (ZoningCompliance)"},{"uniqueId":"1500.0199","dataElement":"NativeAmericanLandsType","messageId":"UAD1380","message":"Provide the native american land type (i.e., Alaska Native Corporation Land, Hawaiian Home Lands, Tribal Trust Land).","ruleLogic":"If NativeAmericanLandsIndicator = \\"true\\" and NativeAmericanLandsType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Native American Lands","dataPointName":"NativeAmericanLandsType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1500.0200","dataElement":"NativeAmericanLandsTypeOtherDescription","messageId":"UAD1381","message":"Provide a description when 'Native American Lands' = 'Other'.","ruleLogic":"If NativeAmericanLandsType = \\"Other\\" and NativeAmericanLandsTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Native American Lands","dataPointName":"NativeAmericanLandsTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1600.0004","dataElement":"ExteriorConditionRatingCode","messageId":"UAD1382","message":"Provide the exterior condition rating.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and ExteriorConditionRatingCode is not provided in a given instance of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Exterior Condition Rating","dataPointName":"ExteriorConditionRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"1600.0005","dataElement":"ExteriorQualityRatingCode","messageId":"UAD1383","message":"Provide the exterior quality rating.","ruleLogic":"If ImprovementType = \\"Dwelling\\" and HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\" and ExteriorQualityRatingCode is not provided in a given instance of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Quality and Condition","reportLabel":"Exterior Quality Ratin
11g","dataPointName":"ExteriorQualityRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"1600.0006","dataElement":"OverallConditionRatingCode","messageId":"UAD1384","message":"Provide 'Overall Condition'.","ruleLogic":"If OverallConditionRatingCode is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Overall Quality and Condition","reportSubsection":"{No Subsection}","reportLabel":"Overall Condition","dataPointName":"OverallConditionRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1600.0007","dataElement":"OverallQualityRatingCode","messageId":"UAD1385","message":"Provide 'Overall Quality'.","ruleLogic":"If OverallQualityRatingCode is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Overall Quality and Condition","reportSubsection":"{No Subsection}","reportLabel":"Overall Quality","dataPointName":"OverallQualityRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1600.0009","dataElement":"ValuationAnalysisCategoryType","messageId":"UAD1386","message":"Provide ValuationAnalysisCategoryType = 'OverallQualityAndCondition' for the reconciliation of overall quality and condition. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If an instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"OverallQualityAndCondition\\" is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ValuationAnalysisCategoryType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/"},{"uniqueId":"1600.0008","dataElement":"ValuationCommentText","messageId":"UAD1387","message":"Provide 'Reconciliation of Overall Quality and Condition'.","ruleLogic":"If ValuationCommentText is not provided in the instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"OverallQualityAndCondition\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Overall Quality and Condition","reportSubsection":"Reconciliation of Overall Quality and Condition","reportLabel":"{No Label}","dataPointName":"ValuationCommentText","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/","relatedValues":"ValuationAnalysisCategoryType (OverallQualityAndCondition)"},{"uniqueId":"","dataElement":"ValuationAnalysisCategoryType","messageId":"UAD1388","message":"ValuationAnalysisCategoryType must be provided. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ValuationAnalysisCategoryType is not provided in a given instance of VALUATION_COMMENTARY","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ValuationAnalysisCategoryType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/"},{"uniqueId":"1800.0001","dataElement":"AddressLineText","messageId":"UAD1390","message":"Provide the address line for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and AddressLineText is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Property Address","dataPointName":"AddressLineText","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"1800.0003","dataElement":"CityName","messageId":"UAD1391","message":"Provide the city name for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and CityName is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Property Address","dataPointName":"CityName","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"1800.0004","dataElement":"PostalCode","messageId":"UAD1392","message":"Provide the ZIP code for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PostalCode is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Property Address","dataPointName":"PostalCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"1800.0005","dataElement":"StateCode","messageId":"UAD1393","message":"Provide the state code for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and StateCode is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Property Address","dataPointName":"StateCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ADDRESS/"},{"uniqueId":"1800.0063","dataElement":"MortgageType","messageId":"UAD1394","message":"The 'Financing Type' must be provided when the sales comparable mortgage was financed.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and NoFinancingTransactionIndicator = \\"false\\" and MortgageType is not provided","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Financing Type","dataPointName":"MortgageType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0064","dataElement":"MortgageTypeOtherDescription","messageId":"UAD1395","message":"Provide a description when 'Financing Type' = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and MortgageType = \\"Other\\", and MortgageTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Financing Type","dataPointName":"MortgageTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0065","dataElement":"ProximityToSubjectDistanceLinearMeasure","messageId":"UAD1396","message":"Provide the 'Proximity to Subject' distance for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ProximityToSubjectDistanceLinearMeasure is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Proximity to Subject","dataPointName":"ProximityToSubjectDistanceLinearMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0066","dataElement":"ComparableToSubjectDirectionType","messageId":"UAD1397","message":"Provide the 'Proximity to Subject' direction for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ProximityToSubjectDistanceLinearMeasure > 0, and ComparableToSubjectDirectionType is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Proximity to Subject","dataPointName":"ComparableToSubjectDirectionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0068","dataElement":"RestrictionType","messageId":"UAD1398","message":"Provide the type of the property restriction that could impact the value or use of the property.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and EncumbranceType = \\"ConditionsCovenantsRestrictions\\", and (at least one instance of CONDITION_COVENANT_RESTRICTION is not provided or RestrictionType is not provided in a given instance of CONDITION_COVENANT_RESTRICTION)","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Property Restriction","dataPointName":"RestrictionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/CONDITION_COVENANT_RESTRICTIONS/CONDITION_COVENANT_RESTRICTION/"},{"uniqueId":"1800.0069","dataElement":"RestrictionTypeOtherDescription","messageId":"UAD1399","message":"Provide a description when property restriction = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and RestrictionType = \\"Other\\" and RestrictionTypeOtherDescription is not provided in a given instance of CONDITION_COVENANT_RESTRICTION","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Property Restriction","dataPointName":"RestrictionTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/CONDITION_COVENANT_RESTRICTIONS/CONDITION_COVENANT_RESTRICTION/"},{"uniqueId":"1800.0070","dataElement":"EasementType","messageId":"UAD1400","message":"Provide the easement type.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and EncumbranceType = \\"Easement\\", and (at least one instance of EASEMENT is not provided or EasementType is not provided in a given instance of EASEMENT)","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Easement","dataPointName":"EasementType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/EASEMENTS/EASEMENT/"},{"uniqueId":"1800.0071","dataElement":"EasementTypeOtherDescription","messageId":"UAD1401","message":"Provide a description when 'Easement' = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and EasementType = \\"Other\\" and EasementTypeOtherDescription is not provided in a given instance of EASEMENT","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Easement","dataPointName":"EasementTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENCUMBRANCES/ENCUMBRANCE/EASEMENTS/EASEMENT/"},{"uniqueId":"1800.0075","dataElement":"ListingStatusType","messageId":"UAD1402","message":"Provide 'Listing Status' for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ListingStatusType is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Listing Status","dataPointName":"ListingStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/"},{"uniqueId":"1800.0075","dataElement":"ListingStatusType","messageId":"UAD1403","message":"Only one listing status must be delivered for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and there is more than one instance of LISTING_INFORMATION","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Listing Status","dataPointName":"ListingStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/"},{"uniqueId":"1000.0032","dataElement":"SalesComparisonApproachIndicator","messageId":"UAD1404","message":"Sales comparison approach is included in the appraisal, however, no s
11ales comparables have been provided. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If SalesComparisonApproachIndicator = \\"true\\" and there are no instances of PROPERTY with @ValuationUseType = \\"SalesComparable\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"SalesComparisonApproachIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"1800.0095","dataElement":"CarStorageType","messageId":"UAD1405","message":"Provide the type of vehicle storage. Select 'None' if there is no vehicle storage.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (at least one instance of CAR_STORAGE_DETAIL is not provided or CarStorageType is not provided in a given instance of CAR_STORAGE_DETAIL)","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Vehicle Storage","reportLabel":"Type | Spaces | Detail","dataPointName":"CarStorageType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/"},{"uniqueId":"1800.0096","dataElement":"CarStorageTypeOtherDescription","messageId":"UAD1407","message":"Provide a description when vehicle storage type = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and CarStorageType = \\"Other\\" and CarStorageTypeOtherDescription is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Vehicle Storage","reportLabel":"Type | Spaces | Detail","dataPointName":"CarStorageTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/"},{"uniqueId":"1800.0094","dataElement":"CarStorageAttachmentType","messageId":"UAD1408","message":"Provide the attachment type for the 'Carport' or 'Garage'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and CarStorageType = \\"Garage\\" or \\"Carport\\", and CarStorageAttachmentType is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Vehicle Storage","reportLabel":"Type | Spaces | Detail","dataPointName":"CarStorageAttachmentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"1800.0097","dataElement":"ImprovedSurfaceMaterialType","messageId":"UAD1409","message":"Provide the material used for the 'Driveway' or 'SharedDriveway'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and CarStorageType = \\"Driveway\\" or \\"SharedDriveway\\", and ImprovedSurfaceMaterialType is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Vehicle Storage","reportLabel":"Type | Spaces | Detail","dataPointName":"ImprovedSurfaceMaterialType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"1800.0098","dataElement":"ImprovedSurfaceMaterialTypeOtherDescription","messageId":"UAD1410","message":"Provide a description when street surface material = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ImprovedSurfaceMaterialType = \\"Other\\" and ImprovedSurfaceMaterialTypeOtherDescription is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Vehicle Storage","reportLabel":"Type | Spaces | Detail","dataPointName":"ImprovedSurfaceMaterialTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/"},{"uniqueId":"1800.0099","dataElement":"ParkingSpacesCount","messageId":"UAD1411","message":"Provide the number of parking space
11s.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (CarStorageType = \\"Driveway\\" or \\"SharedDriveway\\" and TenOrMoreParkingSpacesIndicator = \\"false\\") or (CarStorageType = \\"Carport\\" or \\"CommonCarport\\" or \\"Garage\\" or \\"OpenLot\\" or \\"Other\\" or \\"ParkingGarage\\"), and ParkingSpacesCount is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Vehicle Storage","reportLabel":"Type | Spaces | Detail","dataPointName":"ParkingSpacesCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"1800.0100","dataElement":"ProjectParkingSpaceAssignmentType","messageId":"UAD1412","message":"Provide the type of parking space assignment for 'CommonCarport' , 'OpenLot', or 'ParkingGarage'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\", and CarStorageType = \\"CommonCarport\\" or \\"OpenLot\\" or \\"ParkingGarage\\", and ProjectParkingSpaceAssignmentType is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Vehicle Storage","reportLabel":"Type | Spaces | Detail","dataPointName":"ProjectParkingSpaceAssignmentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"1800.0103","dataElement":"TenOrMoreParkingSpacesIndicator","messageId":"UAD1414","message":"Indicate whether the 'Driveway' or 'SharedDriveway' has ten or more parking spaces.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\", and CarStorageType = \\"Driveway\\" or \\"SharedDriveway\\", and TenOrMoreParkingSpacesIndicator is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Vehicle Storage","reportLabel":"Type | Spaces | Detail","dataPointName":"TenOrMoreParkingSpacesIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"1800.0125","dataElement":"ImprovementType","messageId":"UAD1415","message":"Indicate whether the structure is a 'Dwelling' or 'Outbuilding'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ImprovementType is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s); ADU Interior Quality and Condition","reportLabel":"Location of ADU","dataPointName":"ImprovementType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"1800.0128","dataElement":"PropertyStructureBuiltYear","messageId":"UAD1416","message":"Provide the calendar year in which the construction of the structure was completed.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ImprovementType = \\"Dwelling\\" and PropertyStructureBuiltYear is not provided in a given instance of IMPROVEMENT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Year Built","dataPointName":"PropertyStructureBuiltYear","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"1800.0128","dataElement":"PropertyStructureBuiltYear","messageId":"UAD1418","message":"The 'Year Built' is prior to 1800. Please check for accuracy.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PropertyStructureBuiltYear < 1800 in a given instance of IMPROVEMENT_DETAIL with ImprovementType = \\"Dwelling\\"","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Year Built (%PV%)","dataPointName":"PropertyStructureBuiltYear (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/","minValue":1800},{"uniqueId":"1800.0157","dataElement":"InteriorConditionRatingCode","messageId":"UAD1419","message":"Provide the interior condition rating.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (ImprovementType = \\"Dwelling\\" \\r\\nor (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and InteriorConditionRatingCode is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Interior Quality and Condition; ADU Interior Quality and Condition","reportLabel":"Condition","dataPointName":"InteriorConditionRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1800.0158","dataElement":"InteriorQualityRatingCode","messageId":"UAD1420","message":"Provide the interior quality rating.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (ImprovementType = \\"Dwelling\\" \\r\\nOR (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and InteriorQualityRatingCode is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Interior Quality and Condition; ADU Interior Quality and Condition","reportLabel":"Quality","dataPointName":"InteriorQualityRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1800.0165","dataElement":"HeatingSystemType","messageId":"UAD1421","message":"Provide the heating system type. Select 'None' if there is no heating system.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" AND ImprovementType = \\"Dwelling\\" and (at least one instance of HEATING_SYSTEM is not provided or HeatingSystemType is not provided in a given instance of HEATING_SYSTEM)","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Heating","dataPointName":"HeatingSystemType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/SYSTEM/HEATING_SYSTEMS/HEATING_SYSTEM/"},{"uniqueId":"1800.0166","dataElement":"HeatingSystemTypeOtherDescription","messageId":"UAD1422","message":"Provide a description when heating system type = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and HeatingSystemType = \\"Other\\" and HeatingSystemTypeOtherDescription is not provided in a given instance of HEATING_SYSTEM","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Heating","dataPointName":"HeatingSystemTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/SYSTEM/HEATING_SYSTEMS/HEATING_SYSTEM/"},{"uniqueId":"1800.0169","dataElement":"StructuralDesignType","messageId":"UAD1423","message":"Provide 'Structural Design'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ImprovementType = \\"Dwelling\\" and AttachmentType = \\"Attached\\" and StructuralDesignType is not provided in a given instance of ARCHITECTURAL_DESIGN","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Structure Design","dataPointName":"StructuralDesignType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/ARCHITECTURAL_DESIGN/"},{"uniqueId":"1800.0170","dataElement":"StructuralDesignTypeOtherDescription","messageId":"UAD1424","message":"Provide a description when 'Structure Design' = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and StructuralDesignType = \\"Other\\" and StructuralDesignTypeOtherDescription is not provided in a given instance of ARCHITECTURAL_DESIGN","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Structure Design","dataPointName":"StructuralDesignTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/ARCHITECTURAL_DESIGN/"},{"uniqueId":"1800.0184","dataElement":"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure","messageId":"UAD1425","message":"Provide the 'Gross Building Finished Area'.","ruleLogic":"If SalesComparisonApproachIndicator = \\"true\\" and LivingUnitExcludingADUCount > 1 and TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Gross Building Finished Area","dataPointName":"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0185","dataElement":"ExteriorConditionRatingCode","messageId":"UAD1426","message":"Provide the exterior condition rating.","ruleLogic":"If (@ValuationUseType = \\"SalesComparable\\" and ImprovementType = \\"Dwelling\\" and HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\"), and (@ValuationUseType = \\"SubjectProperty\\" and HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\") and ExteriorConditionRatingCode is not provided in a given instance of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Exterior Quality and Condition","reportLabel":"Condition","dataPointName":"ExteriorConditionRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"1800.0186","dataElement":"ExteriorQualityRatingCode","messageId":"UAD1427","message":"Provide the exterior quality rating.","ruleLogic":"If (@ValuationUseType = \\"SalesComparable\\" and ImprovementType = \\"Dwelling\\" and HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\"), and (@ValuationUseType = \\"SubjectProperty\\" and HomeownerResponsibleForExteriorMaintenanceIndicator = \\"true\\") and ExteriorQualityRatingCode is not provided in a given instance of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Exterior Quality and Condition","reportLabel":"Quality","dataPointName":"ExteriorQualityRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"1800.0189","dataElement":"DaysOnMarketCount","messageId":"UAD1428","message":"Provide the total number of days the property has been on the market.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and DaysOnMarketCount is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Days on Market","dataPointName":"DaysOnMarketCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/"},{"uniqueId":"1800.0190","dataElement":"LatitudeIdentifier","messageId":"UAD1429","message":"Provide the latitude for the sales comparable. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LatitudeIdentifier is not provided","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LatitudeIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LOCATION_IDENTIFIER/GEOSPATIAL_INFORMATION/"},{"uniqueId":"1800.0191","dataElement":"LongitudeIdentifier","messageId":"UAD1430","message":"Provide the longitude for the sales comparable. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LongitudeIdentifier is not provided","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LongitudeIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LOCATION_IDENTIFIER/GEOSPATIAL_INFORMATION/"},{"uniqueId":"1800.0192","dataElement":"PropertyOrdinalNumber","messageId":"UAD1431","message":"A numeric identifier ('Comparable #') must be assigned for each sales comparable. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PropertyOrdinalNumber is not provided","severity":"Fatal","propertyAffected":"Sales Comparable","reportSection":"Sales Comparison Approach; Prior Sale and Transfer History","reportSubsection":"General Information;
11 Comparable Transfer History","reportLabel":"Comparable","dataPointName":"PropertyOrdinalNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/","relatedValues":"AddressLineText (%RV1%)"},{"uniqueId":"1800.0192","dataElement":"PropertyOrdinalNumber","messageId":"UAD1432","message":"Comparable # must be unique. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"if PropertyOrdinalNumber is not unique across all instances of PROPERTY with @ValuationUseType = \\"SalesComparable\\"","severity":"Fatal","propertyAffected":"Sales Comparable","reportSection":"Sales Comparison Approach; Prior Sale and Transfer History","reportSubsection":"General Information; Comparable Transfer History","reportLabel":"Comparable","dataPointName":"PropertyOrdinalNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0195","dataElement":"AttachmentType","messageId":"UAD1433","message":"Indicate whether the sales comparable is attached or detached.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and AttachmentType is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Attached/Detached","dataPointName":"AttachmentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0196","dataElement":"OverallConditionRatingCode","messageId":"UAD1434","message":"Provide the overall condition rating for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and OverallConditionRatingCode is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Overall Quality and Condition","reportLabel":"Condition","dataPointName":"OverallConditionRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0197","dataElement":"OverallQualityRatingCode","messageId":"UAD1435","message":"Provide the overall quality rating for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and OverallQualityRatingCode is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Overall Quality and Condition","reportLabel":"Quality","dataPointName":"OverallQualityRatingCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0198","dataElement":"PriorSalesOrTransfersIndicator","messageId":"UAD1436","message":"Indicate whether the sales comparable has a prior sale or transfer.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PriorSalesOrTransfersIndicator is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Prior Sale and Transfer History","reportSubsection":"Comparable Transfer History","reportLabel":"Transfer Terms","dataPointName":"PriorSalesOrTransfersIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0273","dataElement":"OwnershipTransferTransactionType","messageId":"UAD1438","message":"The ownership transfer transaction type must be provided as sale.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ListingStatusType = \\"SettledSale\\" and OwnershipTransferTransactionType is not provided as \\"Sale\\" for the most recent OwnershipTransferDate","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"OwnershipTransferTransactionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/"},{"uniqueId":"1800.0208; 1800.0272","dataElement":"OwnershipTransferTransactionAmount","messageId":"UAD1439","message":"Provide either the amount related to the transfer of ownership of real property (typically the sale price), or the reason why the ownership transfer amount was not available.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (OwnershipTransferTransactionAmount and OwnershipTransferAmountNotAvailableReasonType) is not provided in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Prior Sale and Transfer History; Sales Comparison Approach","reportSubsection":"Comparable Transfer History; General Information","reportLabel":"Amount; Sale Price","dataPointName":"OwnershipTransferTransactionAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","relatedValues":"OwnershipTransferTransactionType (%RV1%)"},{"uniqueId":"1800.0206","dataElement":"OwnershipTransferAmountNotAvailableReasonTypeOtherDescription","messageId":"UAD1440","message":"Provide a description when 'Ownership Transfer Amount Not Available Reason Type' = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and OwnershipTransferAmountNotAvailableReasonType = \\"Other\\" and OwnershipTransferAmountNotAvailableReasonTypeOtherDescription is not provided in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Prior Sale and Transfer History","reportSubsection":"Comparable Transfer History","reportLabel":"Amount","dataPointName":"OwnershipTransferAmountNotAvailableReasonTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/"},{"uniqueId":"1800.0208; 1800.0272","dataElement":"OwnershipTransferTransactionAmount","messageId":"UAD1442","message":"The amount related to the transfer of ownership of real property (typically the sale price) must be greater than or equal to $0.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and OwnershipTransferTransactionAmount < 0 in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Prior Sale and Transfer History; Sales Comparison Approach","reportSubsection":"Comparable Transfer History; General Information","reportLabel":"Amount; Sale Price (%PV%)","dataPointName":"OwnershipTransferTransactionAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","relatedValues":"OwnershipTransferTransactionType (%RV1%)","minValue":0},{"uniqueId":"1800.0211","dataElement":"SaleTypeOtherDescription","messageId":"UAD1444","message":"Provide a description when 'Transfer Terms' = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and SaleType = \\"Other\\" and SaleTypeOtherDescription is not provided in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Prior Sale and Transfer History","reportSubsection":"Comparable Transfer History","reportLabel":"Transfer Terms","dataPointName":"SaleTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/"},{"uniqueId":"1800.0212","dataElement":"HazardZoneType","messageId":"UAD1445","message":"Provide the hazard zone type. Select 'None' if the property is not in a hazard zone.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (at least one instance of HAZARD_ZONE 
11is not provided or HazardZoneType is not provided in a given instance of HAZARD_ZONE)","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Hazard Zone","dataPointName":"HazardZoneType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HAZARD_ZONES/HAZARD_ZONE/"},{"uniqueId":"1800.0213","dataElement":"HazardZoneTypeOtherDescription","messageId":"UAD1446","message":"Provide a description when hazard zone type = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and HazardZoneType = \\"Other\\" and HazardZoneTypeOtherDescription is not provided in a given instance of HAZARD_ZONE","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Hazard Zone","dataPointName":"HazardZoneTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HAZARD_ZONES/HAZARD_ZONE/"},{"uniqueId":"1800.0215","dataElement":"ImprovedSurfaceMaterialTypeOtherDescription","messageId":"UAD1447","message":"Provide a description when street surface material = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ImprovedSurfaceMaterialType = \\"Other\\", and ImprovedSurfaceMaterialTypeOtherDescription is not provided in a given instance of ACCESS_STREET","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Street Type | Surface","dataPointName":"ImprovedSurfaceMaterialTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/PROPERTY_ACCESS/ACCESS_STREETS/ACCESS_STREET/"},{"uniqueId":"1800.0221","dataElement":"SiteDrainageReasonTypeOtherDescription","messageId":"UAD1448","message":"Provide a description when site drainage reason = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and SiteDrainageReasonType = \\"Other\\" and SiteDrainageReasonTypeOtherDescription is not provided in a given instance of DRAINAGE_IMPACT_REASON","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Drainage","dataPointName":"SiteDrainageReasonTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_FEATURES/SITE_FEATURE/DRAINAGE_IMPACT_REASONS/DRAINAGE_IMPACT_REASON/"},{"uniqueId":"1800.0239","dataElement":"LotSizeAreaMeasure","messageId":"UAD1449","message":"Provide the total site (lot) size.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LandOwnedInCommonIndicator = \\"false\\" and LotSizeAreaMeasure is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Site Size","dataPointName":"LotSizeAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_SIZE_LAYOUT/"},{"uniqueId":"1800.0243","dataElement":"ViewType","messageId":"UAD1450","message":"Provide the view type.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (at least one instance of SITE_VIEW is not provided or ViewType is not provided in a given instance of SITE_VIEW)","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"View | Range","dataPointName":"ViewType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_VIEWS/SITE_VIEW/"},{"uniqueId":"1800.0244","dataElement":"ViewTypeOtherDescription","messageId":"UAD1451","message":"Provide a description when view type = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ViewType = \\"Other\\" and ViewTypeOtherDescription is not provided in a given instance of SITE_VIEW","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"View | Range","dataPointName":"ViewTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_VIEWS/SITE_VIEW/"},{"uniqueId":"1800.0277","dataElement":"LandOwnedInCommonIndicator","messageId":"UAD1452","message":"Indicate whether the site is owned in common.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LandOwnedInCommonIndicator is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"{No Subsection}","reportLabel":"Site Owned in Common","dataPointName":"LandOwnedInCommonIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_DETAIL/"},{"uniqueId":"1800.0287","dataElement":"AccessoryDwellingUnitIndicator","messageId":"UAD1453","message":"Indicate whether the living unit is an ADU.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LivingUnitCount > 0, and AccessoryDwellingUnitIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"AccessoryDwellingUnitIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1800.0319","dataElement":"AdditionalComparisonLineItemIdentifier","messageId":"UAD1455","message":"One or more additional row labels are not identical for one or more properties. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"For each combination of ComparableAdjustmentType = (\\"SalesComparableAdditionalAdjustableComparisonItem\\" or \\"SalesComparableAdditionalNonAdjustableComparisonItem\\") and AdditionalComparisonLineItemIdentifier, if there are not matching occurrences of COMPARABLE_ADJUSTMENT across all instances of PROPERTY with @ValuationUseType = \\"SalesComparable\\", and the instance of PROPERTY with @ValuationUseType = \\"SubjectProperty\\". Example: In Appendix D-1: Sample Scenario SF1, an additional row was added with the Report Label \\"Basement Access\\". AdditionalComparisonLineItemIdentifier = \\"Basement Access\\" must be provided for the Subject and all Comps along with the associated data points.","severity":"Warning","propertyAffected":"Sales Comparable; Subject","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"{No Label}","dataPointName":"AdditionalComparisonLineItemIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_ADJUSTMENTS/COMPARABLE_ADJUSTMENT/"},{"uniqueId":"1800.0309","dataElement":"AdjustedSalesPriceAmount","messageId":"UAD1456","message":"Provide the 'Adjusted Price' for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and AdjustedSalesPriceAmount is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Summary","reportLabel":"Adjusted Price","dataPointName":"AdjustedSalesPriceAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0310","dataElement":"AdjustedSalesPricePerBedroomAmount","messageId":"UAD1457","message":"The 'Adjusted Price Per Bedroom' must be provided for a sales comparable with more than one living unit.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LivingUnitExcludingADUCount > 1 and AdjustedSalesPricePerBedroomAmount is not provided","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Summary","reportLabel":"Adjusted Price Per Bedroom","dataPointName":"AdjustedSalesPricePerBedroomAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0311","dataElement":"AdjustedSalesPricePerUnitAmount","messageId":"UAD1458","message":"The 'Adjusted Price Per Unit' must be provided for a sales comparable with more than one living unit.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LivingUnitExcludingADUCount > 1, and AdjustedSalesPricePerUnitAmount is not provided","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Summary","reportLabel":"Adjusted Price Per Unit","dataPointName":"AdjustedSalesPricePerUnitAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0312","dataElement":"ComparableWeightType","messageId":"UAD1459","message":"Provide the 'Comparable Weight' for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ComparableWeightType is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Summary","reportLabel":"Comparable Weight","dataPointName":"ComparableWeightType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0313","dataElement":"SalePriceNetTotalAdjustmentAmount","messageId":"UAD1460","message":"Provide the 'Net Adjustment Total'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and SalePriceNetTotalAdjustmentAmount is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Summary","reportLabel":"Net Adjustment Total","dataPointName":"SalePriceNetTotalAdjustmentAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0313","dataElement":"SalePriceNetTotalAdjustmentAmount","messageId":"UAD1461","message":"The 'Net Adjustment Total' does not equal the sum of the individual adjustments.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and SalePriceNetTotalAdjustmentAmount does not equal the sum of ComparableAdjustmentAmount across all instances of COMPARABLE_ADJUSTMENT","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Summary","reportLabel":"Net Adjustment Total (%PV%)","dataPointName":"SalePriceNetTotalAdjustmentAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0322","dataElement":"WaterAccessDepthTypeOtherDescription","messageId":"UAD1462","message":"Provide a description when water access depth = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and WaterAccessDepthType = \\"Other\\" and WaterAccessDepthTypeOtherDescription is not provided in a given instance of BODY_OF_WATER","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Water Frontage with Private Access","reportLabel":"Water Frontage","dataPointName":"WaterAccessDepthTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/BODIES_OF_WATER/BODY_OF_WATER/"},{"uniqueId":"1800.0330","dataElement":"BedroomCount","messageId":"UAD1463","message":"Provide the number of bedrooms in the living unit, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" AND OutbuildingRealPropertyIndicator = \\"true\\" AND AccessoryDwellingUnitIndicator = \\"true\\")), and BedroomCount is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Bedrooms","dataPointName":"BedroomCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1800.0331","dataElement":"FullBathroomCount","messageId":"UAD1464","message":"Provide the number of full bathrooms in the living unit, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" AND OutbuildingRealPropertyIndicator = \\"true\\" AND AccessoryDwellingUnitIndicator = \\"true\\")), and FullBathroomCount is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Baths - Full | Half","dataPointName":"FullBathroomCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1800.0332","dataElement":"HalfBathroomCount","messageId":"UAD1465","message":"Provide the number of half bathrooms in the living unit, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" AND OutbuildingRealPropertyIndicator = \\"true\\" AND AccessoryDwellingUnitIndicator = \\"true\\")), and HalfBathroomCount is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Baths - Full | Half","dataPointName":"HalfBathroomCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1800.0345","dataElement":"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure","messageId":"UAD1467","message":"Provide the 'Gross Building Finished Area'.","ruleLogic":"If (@ValuationUseType = \\"SalesComparable\\") and (@ValuationUseType = \\"SubjectProperty\\" and LivingUnitExcludingADUCount > 1), and TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Gross Building Finished Area","dataPointName":"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0347","dataElement":"DataSourceIdentifier","messageId":"UAD1468","message":"Provide the data source identifier (e.g., MLS number).","ruleLogic":"If DataSourceIdentifier is not provided in a given instance of DATA_SOURCE with DataSourceType = \\"MLS\\" that has arc role to PROPERTY container with @ValuationUseType <> (\\"SubjectProperty\\" or \\"PropertyAnalyzedNotUsed\\")","severity":"Fatal","propertyAffected":"N/A","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"Data Source","dataPointName":"DataSourceIdentifier","xpath":"../VALUATION_ANALYSIS/DATA_SOURCES/DATA_SOURCE/"},{"uniqueId":"1800.0359","dataElement":"NativeAmericanLandsTypeOtherDescription","messageId":"UAD1469","message":"Provide a description when 'Native American Lands' = 'Other'.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and NativeAmericanLandsType = \\"Other\\" and NativeAmericanLandsTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Native American Lands","dataPointName":"NativeAmericanLandsTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0360","dataElement":"@xlink:arcrole","messageId":"UAD1470","message":"When the sales comparable and the subject property have more than one living unit, each comparable unit must be associated to a subject property unit. In the UAD XML, a RELATIONSHIP container must be included that links the instance of PROPERTY_UNIT (@ValuationUseType = 'SalesComparable') to PROPERTY_UNIT (@ValuationUseType = 'SubjectProperty'). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If (@ValuationUseType = \\"SubjectProperty\\" and (LivingUnitExcludingADUCount > 1 or AccessoryDwellingUnitTotalCount > 0)) and\\r\\n(@ValuationUse
11Type = \\"SalesComparable\\" and (LivingUnitExcludingADUCount > 1 or AccessoryDwellingUnitTotalCount > 0)), and there is not an instance of RELATIONSHIP with @xlink:arcrole = urn:fdc:mismo.org:2009:residential/PROPERTY_UNIT_IsComparableFor_PROPERTY_UNIT","severity":"Fatal","propertyAffected":"Sales Comparable #n; Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"1800.0363","dataElement":"DwellingCount","messageId":"UAD1471","message":"Provide the total number of dwellings.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and DwellingCount is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"DwellingCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0363","dataElement":"DwellingCount","messageId":"UAD1472","message":"The total number of dwellings must be at least 1.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and DwellingCount < 1","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"DwellingCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/","minValue":1},{"uniqueId":"1800.0364","dataElement":"HomeownerResponsibleForExteriorMaintenanceIndicator","messageId":"UAD1473","message":"Indicate whether the homeowner is responsible for the exterior maintenance.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and HomeownerResponsibleForExteriorMaintenanceIndicator is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"HomeownerResponsibleForExteriorMaintenanceIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0365","dataElement":"LivingUnitExcludingADUCount","messageId":"UAD1474","message":"Provide the total number of living units, excluding any ADUs for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LivingUnitExcludingADUCount is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LivingUnitExcludingADUCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0365","dataElement":"LivingUnitExcludingADUCount","messageId":"UAD1475","message":"The total number of living units, excluding any ADUs, must be at least 1.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LivingUnitExcludingADUCount < 1","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LivingUnitExcludingADUCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/","minValue":1},{"uniqueId":"1800.0367","dataElement":"LavaFlowZoneCode","messageId":"UAD1476","message":"Provide the lava flow zone.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and HazardZoneType = \\"USGSLavaFlowZone\\", and LavaFlowZoneCode is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Hazard Zone","dataPointName":"LavaFlowZoneCode","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HAZARD_ZONES/HAZARD_ZONE/"},{"uniqueId":"1800.0374","dataElement":"@xlink:arcrole","messageId":"UAD1477","message":"Provide at least one data source for each sales comparable. In the UAD XML, a minimum of one RELATIONSHIP container must be included that links DATA_SOURCE to PROPERTY (@ValuationUseType = 'SalesComparable'). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If SalesComparisonApproachIndicator = \\"true\\" and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DATA_SOURCE_IsDataSourceFor_PROPERTY\\" that links DATA_SOURCE to PROPERTY where @ValuationUseType = \\"SalesComparable\\"","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"1800.0377","dataElement":"ProjectLegalStructureType","messageId":"UAD1478","message":"Provide the ownership type of the property (e.g., cooperative, condominium, condop).","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PropertyInProjectIndicator = \\"true\\" and ProjectLegalStructureType is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ProjectLegalStructureType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"1800.0378","dataElement":"PropertyInProjectIndicator","messageId":"UAD1479","message":"Indicate whether the sales comparable is located in a project.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PropertyInProjectIndicator is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"PropertyInProjectIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0383","dataElement":"PUDIndicator","messageId":"UAD1480","message":"Indicate whether the sales comparable is located in a planned unit development (PUD).","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PUDIndicator is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"PUDIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0385","dataElement":"ContractDateUnknownIndicator","messageId":"UAD1481","message":"Indicate whether the contract date is known.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ListingStatusType = \\"Pending\\" or \\"SettledSale\\" and ContractDateUnknownIndicator is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Contract Date","dataPointName":"ContractDateUnknownIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"1800.0390","dataElement":"UnitStandardAboveGradeFinis
11hedAreaMeasure","messageId":"UAD1482","message":"Provide the 'Finished Above Grade' Area, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and UnitStandardAboveGradeFinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Finished Area Above Grade","dataPointName":"UnitStandardAboveGradeFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1800.0393","dataElement":"UnitStandardBelowGradeFinishedAreaMeasure","messageId":"UAD1483","message":"Provide the 'Finished Below Grade' Area, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and UnitStandardBelowGradeFinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Finished Area Below Grade","dataPointName":"UnitStandardBelowGradeFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1800.0398","dataElement":"UnitNonStandardBelowGradeFinishedAreaMeasure","messageId":"UAD1484","message":"Provide the 'Finished Below Grade (Nonstandard)' Area, even if the value is 0.","ruleLogic":"If ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\"), and UnitNonStandardBelowGradeFinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"Finished Below Grade (Nonstandard)","dataPointName":"UnitNonStandardBelowGradeFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1900.0017","dataElement":"PropertyOrdinalNumber","messageId":"UAD1485","message":"Comparable # must be unique. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"if PropertyOrdinalNumber is not unique across all instances of PROPERTY with @ValuationUseType = \\"PropertyAnalyzedNotUsed\\"","severity":"Fatal","propertyAffected":"Property Analyzed Not Used","reportSection":"Sales Comparison Approach","reportSubsection":"Additional Properties Analyzed Not Used","reportLabel":"#","dataPointName":"PropertyOrdinalNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"2000.0012","dataElement":"RentalUnitAdjustedRentAmount","messageId":"UAD1486","message":"Provide the 'Adjusted Rent' for the rental comparable.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and RentalUnitAdjustedRentAmount is not provided in a given instance of RENTAL_COMPARISON_DETAIL","severity":"Fatal","propertyAffected":"Rental Comparable #n","reportSection":"Rental Information","reportSubsection":"Comparable Rental Analysis","reportLabel":"Adjusted Rent","dataPointName":"RentalUnitAdjustedRentAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/RENTAL_INFORMATIONS/RENTAL_INFORMATION/RENTAL_COMPARISON/RENTAL_COMPARISON_DETAIL/"},{"uniqueId":"2000.0021","dataElement":"UnitTotalFinishedAreaMeasure","messageId":"UAD1487","message":"Provide the total finished area of the living unit.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and UnitTotalFinishedAreaMeasure is not provided in PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Rental Comparable #n","reportSection":"Rental Information","reportSubsection":"Comparable Rental Analysis","reportLabel":"Finished Area","dataPointName":"UnitTotalFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/"},{"uniqueId":"2000.0032","dataElement":"TotalMonthlyActualRentAmount","messageId":"UAD1488","message":"Provide the total monthly actual rent for the rental unit(s) on the property.","ruleLogic":"If (RentScheduleIndicator = \\"true\\" or IncomeApproachIndicator = \\"true\\"), and TotalMonthlyActualRentAmount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"TotalMonthlyActualRentAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/RENTAL_INFORMATION_SUMMARY/RENTAL_INFORMATION_SUMMARY_DETAIL/"},{"uniqueId":"2000.0035","dataElement":"TotalMonthlyMarketRentAmount","messageId":"UAD1489","message":"Provide the total monthly market rent for the rental unit(s) on the property.","ruleLogic":"If (RentScheduleIndicator = \\"true\\" or IncomeApproachIndicator = \\"true\\"), and TotalMonthlyMarketRentAmount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"TotalMonthlyMarketRentAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/RENTAL_INFORMATION_SUMMARY/RENTAL_INFORMATION_SUMMARY_DETAIL/"},{"uniqueId":"2000.0041","dataElement":"UnitMonthlyActualRentAmount","messageId":"UAD1490","message":"Provide the monthly 'Actual Rent' for the living unit, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and UnitMonthlyActualRentAmount is not provided in UNIT_RENT_SCHEDULE","severity":"Fatal","propertyAffected":"Rental Comparable #n","reportSection":"Rental Information","reportSubsection":"Comparable Rental Properties; Comparable Rental Analysis","reportLabel":"Actual Rent","dataPointName":"UnitMonthlyActualRentAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/UNIT_RENT_SCHEDULE/"},{"uniqueId":"2000.0050","dataElement":"UnitTotalFinishedAreaMeasure","messageId":"UAD1491","message":"Provide the total finished area of the living unit.","ruleLogic":"If RentScheduleIndicator = \\"true\\", and UnitIncludedInRentScheduleIndicator = \\"true\\", and UnitTotalFinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Subject","reportSection":"Rental Information","reportSubsection":"Comparable Rental Analysis","reportLabel":"Finished Area","dataPointName":"UnitTotalFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/"},{"uniqueId":"2000.0066","dataElement":"ComparableToSubjectDirectionType","messageId":"UAD1492","message":"Provide the 'Proximity to Subject' direction for the rental comparable.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and ProximityToSubjectDistanceLinearMeasure > 0, and ComparableToSubjectDirectionType is not provided","severity":"Fatal","propertyAffected":"Rental Comparable #n","reportSection":"Rental Information","reportSubsection":"Comparable Rental Analysis","reportLabel":"Proximity to Subject","dataPointName":"ComparableToSubjectDirectionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"2000.0067","dataElement":"ProximityToSubjectDistanceLinearMeasure","messageId":"UAD1493","message":"Provide the 'Proximity to Subject' distance for the rental comparable.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and ProximityToSubjectDistanceLinearMeasure is not provided","severity":"Fatal","propertyAffected":"Rental Comparable #n","reportSection":"Rental Information","reportSubsection":"Comparable Rental Analysis","reportLabel":"Proximity to Subject","dataPointName":"ProximityToSubjectDistanceLinearMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"2000.0078","dataElement":"PropertyOrdinalNumber","messageId":"UAD1494","message":"A numeric identifier ('Comparable #') must be assigned for each rental comparable. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and PropertyOrdinalNumber is not provided","severity":"Fatal","propertyAffected":"Rental Comparable","reportSection":"Rental Information","reportSubsection":"Comparable Rental Properties","reportLabel":"Comparable #","dataPointName":"PropertyOrdinalNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/","relatedValues":"AddressLineText (%RV1%)"},{"uniqueId":"2000.0078","dataElement":"PropertyOrdinalNumber","messageId":"UAD1495","message":"Comparable # must be unique. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"if PropertyOrdinalNumber is not unique across all instances of PROPERTY with @ValuationUseType = \\"RentalComparable\\"","severity":"Fatal","propertyAffected":"Rental Comparable","reportSection":"Rental Information","reportSubsection":"Comparable Rental Properties","reportLabel":"Comparable #","dataPointName":"PropertyOrdinalNumber","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_DETAIL/"},{"uniqueId":"2000.0088","dataElement":"RentControlStatusType","messageId":"UAD1496","message":"Indicate whether the living unit is subject to rent control.","ruleLogic":"If RentScheduleIndicator = \\"true\\", and UnitIncludedInRentScheduleIndicator = \\"true\\", and RentControlStatusType is not provided in a given instance of UNIT_RENT_SCHEDULE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Rental Information","reportSubsection":"Rent Schedule; Comparable Rental Analysis","reportLabel":"Rent Control","dataPointName":"RentControlStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/UNIT_RENT_SCHEDULE/"},{"uniqueId":"2000.0089","dataElement":"UnitMonthlyActualRentAmount","messageId":"UAD1497","message":"Provide the monthly 'Actual Rent' for the living unit.","ruleLogic":"If RentScheduleIndicator = \\"true\\", and UnitIncludedInRentScheduleIndicator = \\"true\\", and UnitMonthlyActualRentAmount is not provided in a given instance of UNIT_RENT_SCHEDULE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Rental Information","reportSubsection":"Rent Schedule; Comparable Rental Analysis","reportLabel":"Monthly Rent\\r\\nActual Rent","dataPointName":"UnitMonthlyActualRentAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/UNIT_RENT_SCHEDULE/"},{"uniqueId":"2000.0092","dataElement":"UnitMonthlyMarketRentAmount","messageId":"UAD1498","message":"Provide the 'Opinion of Market Rent' for the living unit.","ruleLogic":"If RentScheduleIndicator = \\"true\\", and UnitIncludedInRentScheduleIndicator = \\"true\\", and UnitMonthlyMarketRentAmount is not provided in a given instance of UNIT_RENT_SCHEDULE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Rental Information","reportSubsection":"Rent Schedule; Comparable Rental Analysis","reportLabel":"{No Label}; Opinion of Market Rent","dataPointName":"UnitMonthlyMarketRentAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/UNIT_RENT_SCHEDULE/"},{"uniqueId":"2000.0101","dataElement":"BedroomCount","messageId":"UAD1499","message":"Provide the number of bedrooms in the living unit, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and BedroomCount is not provided in PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Rental Comparable #n","reportSection":"Rental Information","reportSubsection":"Comparable Rental Analysis","reportLabel":"Bedrooms","dataPointName":"BedroomCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"2000.0102","dataElement":"FullBathroomCount","messageId":"UAD1500","message":"Provide the number of full bathrooms in the living unit, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and FullBathroomCount is not provided in PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Rental Comparable #n","reportSection":"Rental Information","reportSubsection":"Comparable Rental Analysis","reportLabel":"Full |Half","dataPointName":"FullBathroomCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"2000.0103","dataElement":"HalfBathroomCount","messageId":"UAD1501","message":"Provide the number of half bathrooms in the living unit, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"RentalComparable\\" and HalfBathroomCount is not provided in PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Rental Comparable #n","reportSection":"Rental Information","reportSubsection":"Comparable Rental Analysis","reportLabel":"Full |Half","dataPointName":"HalfBathroomCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"2100.0045","dataElement":"ValuationReportContentIdentifier","messageId":"UAD1502","message":"Provide the UAD Delivery Specification version. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ValuationReportContentIdentifier is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ValuationReportContentIdentifier","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},{"uniqueId":"2200.0154; 2200.0002","dataElement":"ExecutionDate","messageId":"UAD1505","message":"The 'Date of Signature and Report' cannot be a future date.","ruleLogic":"If ExecutionDate is in the future","severity":"Warning","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Signature","reportLabel":"Date of Signature and Report (%PV%)","dataPointName":"ExecutionDate (%PV%)","xpath":"MESSAGE/DOCUMENT_SETS/DOCUMENT_SET/DOCUMENTS/DOCUMENT/SIGNATORIES/SIGNATORY/EXECUTION/EXECUTION_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"2200.0154; 2200.0002","dataElement":"ExecutionDate","messageId":"UAD1506","message":"The 'Date of Signature and Report' cannot be more than a year old.","ruleLogic":"If ExecutionDate is more than 367 days before the current date.","severity":"Warning","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Signature","reportLabel":"Date of Signature and Report (%PV%)","dataPointName":"ExecutionDate (%PV%)","xpath":"MESSAGE/DOCUMENT_SETS/DOCUMENT_SET/DOCUMENTS/DOCUMENT/SIGNATORIES/SIGNATORY/EXECUTION/EXECUTION_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"2200.0154; 2200.0002","dataElement":"ExecutionDate","messageId":"UAD1507","message":"The 'Date of Signature and Report' must include year, month and day.","ruleLogic":"If ExecutionDate does not include year, month and day (YYYY-MM-DD format) in a given instance of SIGNATORY","severity":"Fatal","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Signature","reportLabel":"Date of Signature and Report (%PV%)","dataPointName":"ExecutionDate (%PV%)","xpath":"MESSAGE/DOCUMENT_SETS/DOCUMENT_SET/DOCUMENTS/DOCUMENT/SIGNATORIES/SIGNATORY/EXECUTION/EXECUTION_DETAIL/","da
11teFormat":"CCYY-MM-DD"},{"uniqueId":"2200.0017","dataElement":"AppraiserPriorServicesPerformedIndicator","messageId":"UAD1508","message":"Indicate whether the Appraiser has performed any prior services for the subject property.","ruleLogic":"If AppraiserPriorServicesPerformedIndicator is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Appraiser Certifications","reportLabel":"{No Label}","dataPointName":"AppraiserPriorServicesPerformedIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},{"uniqueId":"2200.0034","dataElement":"AppraiserAdditionalCertificationIndicator","messageId":"UAD1509","message":"Indicate whether additional certifications have been identified by the Appraiser.","ruleLogic":"If AppraiserAdditionalCertificationIndicator is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"AppraiserAdditionalCertificationIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},{"uniqueId":"2200.0037","dataElement":"ValuationAdditionalIntendedUserIndicator","messageId":"UAD1510","message":"Indicate whether additional intended users have been identified for the appraisal.","ruleLogic":"If ValuationAdditionalIntendedUserIndicator is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ValuationAdditionalIntendedUserIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"2200.0038","dataElement":"ValuationReportInspectionCertificationType","messageId":"UAD1511","message":"Provide the type of inspection performed by the Appraiser in the valuation certifications (Cert #10) for this assignment.","ruleLogic":"If ValuationReportInspectionCertificationType is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Appraiser Certifications","reportLabel":"{No Label}","dataPointName":"ValuationReportInspectionCertificationType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},{"uniqueId":"1000.0158","dataElement":"PropertyValuationMethodType","messageId":"UAD1512","message":"The Appraiser Certification (#10) does not align with the 'Property Valuation Method'.","ruleLogic":"If PropertyValuationMethodType = \\"TraditionalAppraisal\\" and ValuationReportInspectionCertificationType <> \\"InteriorAndExterior\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Property Valuation Method (Traditional Appraisal)","dataPointName":"PropertyValuationMethodType (TraditionalAppraisal)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_VALUATIONS/PROPERTY_VALUATION/PROPERTY_VALUATION_DETAIL/","relatedValues":"ValuationReportInspectionCertificationType (%RV1%)"},{"uniqueId":"1000.0158","dataElement":"PropertyValuationMethodType","messageId":"UAD1513","message":"The Appraiser Certification (#10) does not align with the 'Property Valuation Method'.","ruleLogic":"If PropertyValuationMethodType = \\"ExteriorAppraisal\\" and ValuationReportInspectionCertificationType <> \\"Exterior\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Property Valuation Method (Exterior Appraisal)","dataPointName":"PropertyValuationMethodType (ExteriorAppraisal)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_VALUATIONS/PROPERTY_VALUATION/PROPERTY_VALUATION_DETAIL/","relatedValues":"ValuationReportInspectionCertificationType (%RV1%)"},{"uniqueId":"1000.0158","dataElement":"PropertyValuationMethodType","messageId":"UAD1514","message":"The Appraiser Certification (#10) does not align with the 'Property Valuation Method'.","ruleLogic":"If PropertyValuationMethodType = \\"DesktopAppraisal\\" and ValuationReportInspectionCertificationType <> \\"NoPhysicalInspection\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Property Valuation Method (Desktop Appraisal)","dataPointName":"PropertyValuationMethodType (DesktopAppraisal)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_VALUATIONS/PROPERTY_VALUATION/PROPERTY_VALUATION_DETAIL/","relatedValues":"ValuationReportInspectionCertificationType (%RV1%)"},{"uniqueId":"1000.0158","dataElement":"PropertyValuationMethodType","messageId":"UAD1515","message":"The Appraiser Certification (#10) does not align with the 'Property Valuation Method'.","ruleLogic":"If PropertyValuationMethodType = \\"HybridAppraisal\\" and ValuationReportInspectionCertificationType <> \\"NoPhysicalInspection\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Property Valuation Method (Hybrid Appraisal)","dataPointName":"PropertyValuationMethodType (HybridAppraisal)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_VALUATIONS/PROPERTY_VALUATION/PROPERTY_VALUATION_DETAIL/","relatedValues":"ValuationReportInspectionCertificationType (%RV1%)"},{"uniqueId":"2200.0038","dataElement":"ValuationReportInspectionCertificationType","messageId":"UAD1516","message":"The Appraiser Certification (#10) does not align with the appraiser subject property inspection.","ruleLogic":"If PropertyInteriorInspectionMethodType = \\"Physical\\" and PropertyExteriorInspectionMethodType = \\"Physical\\" for PartyRoleType = \\"Appraiser\\", and ValuationReportInspectionCertificationType <> \\"InteriorAndExterior\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Appraiser Certifications","reportLabel":"{No Label} (%PV%)","dataPointName":"ValuationReportInspectionCertificationType (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/","relatedValues":"PropertyInteriorInspectionMethodType (%RV1%); PropertyExteriorInspectionMethodType (%RV2%)"},{"uniqueId":"2200.0038","dataElement":"ValuationReportInspectionCertificationType","messageId":"UAD1517","message":"The Appraiser Certification (#10) does not align with the appraiser subject property inspection.","ruleLogic":"If (PropertyInteriorInspectionMethodType = \\"Virtual\\" or \\"NoInspection\\" and PropertyExteriorInspectionMethodType = \\"Virtual\\" or \\"NoInspection\\" for PartyRoleType = \\"Appraiser\\"), and ValuationReportInspectionCertificationType <> \\"NoPhysicalInspection\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Appraiser Certifications","reportLabel":"{No Label} (%PV%)","dataPointName":"ValuationReportInspectionCertificationType (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/","relatedValues":"PropertyInteriorInspectionMethodType (%RV1%); PropertyExteriorInspectionMethodType (%RV2%)"},{"uniqueId":"2200.0038","dataElement":"ValuationReportInspectionCertificationType","messageId":"UAD1518","message":"The Appraiser Certification (#10) does not align with the appraiser subject property inspection.","ruleLogic":"If (PropertyInteriorInspectionMethodType = \\"Virtual\\" or \\"NoInspection\\" and PropertyExteriorInspectionMethodType = \\"Physical\\" for PartyRoleType = \\"Appraiser\\"), and ValuationReportInspectionCertificationType <> \\"Exterior\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Appraiser Certifications","reportLabel":"{No Label} (%PV%)","dataPointName":"ValuationReportInspectionCertificationType (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/","relatedValues":"PropertyInteriorInspectionMethodType (%RV1%); PropertyExteriorInspectionMethodType (%RV2%)"},{"uniqueId":"1000.0043","dataElement":"PropertyDataReportIndicator","messageId":"UAD1519","message":"Indicate whether a third-party property data report was used.","ruleLogic":"If PropertyDataReportIndicator is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Was a Property Data Report used in lieu of an Inspection?","dataPointName":"PropertyDataReportIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},{"uniqueId":"2400.0513","dataElement":"PartyRoleType","messageId":"UAD1520","message":"When a property data report was used, provide details on the individual providing property data collection.","ruleLogic":"If PropertyDataReportIndicator = \\"true\\" and there is no instance of ROLE_DETAIL with PartyRoleType = \\"PropertyDataCollector\\" in SERVICE container with ServiceType = \\"Inspection\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"PartyRoleType","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/ROLE_DETAIL/"},{"uniqueId":"1000.0132","dataElement":"PropertyExteriorInspectionMethodType","messageId":"UAD1521","message":"Provide the manner in which the Property Data Collector conducted the exterior inspection.","ruleLogic":"If PropertyDataReportIndicator = \\"true\\" and PropertyExteriorInspectionMethodType is not provided in SERVICE container with ServiceType = \\"Inspection\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Exterior","dataPointName":"PropertyExteriorInspectionMethodType","xpath":"../SERVICE/INSPECTION_SERVICE/INSPECTION_SERVICE_RESPONSE/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/INSPECTION_DETAIL/"},{"uniqueId":"1000.0133","dataElement":"PropertyInteriorInspectionMethodType","messageId":"UAD1522","message":"Provide the manner in which the Property Data Collector conducted the interior inspection.","ruleLogic":"If PropertyDataReportIndicator = \\"true\\" and PropertyInteriorInspectionMethodType is not provided in SERVICE container with ServiceType = \\"Inspection\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Interior","dataPointName":"PropertyInteriorInspectionMethodType","xpath":"../SERVICE/INSPECTION_SERVICE/INSPECTION_SERVICE_RESPONSE/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/INSPECTION_DETAIL/"},{"uniqueId":"2200.0062","dataElement":"ValuationAdditionalScopeOfWorkIndicator","messageId":"UAD1523","message":"Indicate whether additional scope of work (beyond the minimum scope) has been identified for this valuation assignment.","ruleLogic":"If ValuationAdditionalScopeOfWorkIndicator is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ValuationAdditionalScopeOfWorkIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/SCOPE_OF_WORK/SCOPE_OF_WORK_DETAIL/"},{"uniqueId":"2200.0075","dataElement":"FirstName","messageId":"UAD1524","message":"Provide the Supervisory Appraiser's first name.","ruleLogic":"If FirstName is not provided for PartyRoleType = \\"AppraiserSupervisor\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Supervisory Appraiser - Name","dataPointName":"FirstName","xpath":"../SERVICE/PARTIES/PARTY/INDIVIDUAL/NAME/"},{"uniqueId":"2200.0076","dataElement":"LastName","messageId":"UAD1525","message":"Provide the Supervisory Appraiser's last name.","ruleLogic":"If LastName is not provided for PartyRoleType = \\"AppraiserSupervisor\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Supervisory Appraiser - Name","dataPointName":"LastName","xpath":"../SERVICE/PARTIES/PARTY/INDIVIDUAL/NAME/"},{"uniqueId":"2200.0080","dataElement":"AppraiserLicenseType","messageId":"UAD1526","message":"Provide the Supervisory Appraiser's state-level credentials.","ruleLogic":"If AppraiserLicenseType is not provided for PartyRoleType = \\"AppraiserSupervisor\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Supervisory Appraiser - Level","dataPointName":"AppraiserLicenseType","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/APPRAISER_LICENSE/"},{"uniqueId":"2200.0081; 2400.0052","dataElement":"AppraiserLicenseTypeOtherDescription","messageId":"UAD1527","message":"Provide a description when the license type = 'Other'.","ruleLogic":"If AppraiserLicenseType = \\"Other\\" and AppraiserLicenseTypeOtherDescription is not provided in a given instance of APPRAISER_LICENSE","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Credentials - Level","dataPointName":"AppraiserLicenseTypeOtherDescription","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/APPRAISER_LICENSE/"},{"uniqueId":"2200.0082","dataElement":"LicenseExpirationDate","messageId":"UAD1528","message":"Provide the Supervisory Appraiser's license expiration date.","ruleLogic":"If LicenseExpirationDate is not provided for PartyRoleType = \\"AppraiserSupervisor\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Supervisory Appraiser - Expires","dataPointName":"LicenseExpirationDate","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/LICENSE_DETAIL/"},{"uniqueId":"2200.0082","dataElement":"LicenseExpirationDate","messageId":"UAD1529","message":"The Appraiser and/or Supervisory Appraiser license expired before the 'Effective Date of Appraisal'.","ruleLogic":"If LicenseExpirationDate for PartyRoleType = \\"Appraiser\\" and/or \\"AppraiserSupervisor\\" < AppraisalReportEffectiveDate","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Expires (%PV%)","dataPointName":"LicenseExpirationDate (%PV%)","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/LICENSE_DETAIL/","relatedValues":"AppraisalReportEffectiveDate (%RV1%); PartyRoleType (%RV2%)"},{"uniqueId":"2400.0053; 2200.0082","dataElement":"LicenseExpirationDate","messageId":"UAD1530","message":"The license expiration date must include year, month and day.","ruleLogic":"If LicenseExpirationDate does not include year, month and day (YYYY-MM-DD format)","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Expires (%PV%)","dataPointName":"LicenseExpirationDate (%PV%)","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/LICENSE_DETAIL/","relatedValues":"PartyRoleType (%RV1%)","dateFormat":"CCYY-MM-DD"},{"uniqueId":"2200.0083","dataElement":"LicenseIdentifier","messageId":"UAD1531","message":"Provide the Supervisory Appraiser's license number.","ruleLogic":"If LicenseIdentifier is not provided for PartyRoleType = \\"AppraiserSupervisor\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Supervisory Appraiser - ID","dataPointName":"LicenseIdentifier","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/LICENSE_DETAIL/"},{"uniqueId":"2200.0084","dataElement":"LicenseIssuingAuthorityStateCode","messageId":"UAD1532","message":"Provide the Supervisory Appraiser's license issuing state.","ruleLogic":"If LicenseIssuingAuthorityStateCode is not provided for PartyRoleType = \\"AppraiserSupervisor\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Supervisory Appraiser - State","dataPointName":"LicenseIssuingAuthorityStateCode","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/LICENSE_DETAIL/"},
11{"uniqueId":"2200.0084; 2400.0055","dataElement":"LicenseIssuingAuthorityStateCode","messageId":"UAD1533","message":"The Appraiser and Supervisory Appraiser must be licensed in the state in which the subject property is located.","ruleLogic":"If LicenseIssuingAuthorityStateCode for PartyRoleType = \\"Appraiser\\" or \\"AppraiserSupervisor\\" <> StateCode (PROPERTY/ADDRESS with @ValuationUseType = \\"SubjectProperty\\")","severity":"Warning","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"State","dataPointName":"LicenseIssuingAuthorityStateCode","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/LICENSE_DETAIL/"},{"uniqueId":"2200.0085","dataElement":"PartyRoleType","messageId":"UAD1534","message":"A party role type of 'Supervisory Appraiser' must be provided.","ruleLogic":"If (PartyRoleType = \\"Appraiser\\" and (AppraiserLicenseType = \\"None\\" or AppraiserLicenseType = \\"TraineeAppraiser\\")) and there is no instance of PARTY with PartyRoleType = \\"AppraiserSupervisor\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Supervisory Appraiser","dataPointName":"PartyRoleType","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/ROLE_DETAIL/"},{"uniqueId":"2200.0154; 2200.0002","dataElement":"ExecutionDate","messageId":"UAD1535","message":"The 'Date of Signature and Report' must be provided for the Appraiser and the Supervisory Appraiser (if applicable), with only one instance allowed per party.","ruleLogic":"If ExecutionDate is not provided for PartyRoleType = (\\"AppraiserSupervisor\\" or \\"Appraiser\\") or more than one instance of ExecutionDate is provided for PartyRoleType = (\\"AppraiserSupervisor\\" or \\"Appraiser\\")","severity":"Fatal","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Signature","reportLabel":"Date of Signature and Report","dataPointName":"ExecutionDate","xpath":"MESSAGE/DOCUMENT_SETS/DOCUMENT_SET/DOCUMENTS/DOCUMENT/SIGNATORIES/SIGNATORY/EXECUTION/EXECUTION_DETAIL/"},{"uniqueId":"2200.0154; 2200.0002","dataElement":"ExecutionDate","messageId":"UAD1536","message":"The 'Date of Signature and Report' must be on or after the 'Effective Date of Appraisal'.","ruleLogic":"If ExecutionDate < AppraisalReportEffectiveDate in a given instance of SIGNATORY","severity":"Fatal","propertyAffected":"N/A","reportSection":"Certifications","reportSubsection":"Signature","reportLabel":"Date of Signature and Report (%PV%)","dataPointName":"ExecutionDate (%PV%)","xpath":"MESSAGE/DOCUMENT_SETS/DOCUMENT_SET/DOCUMENTS/DOCUMENT/SIGNATORIES/SIGNATORY/EXECUTION/EXECUTION_DETAIL/"},{"uniqueId":"2400.0001","dataElement":"AddressLineText","messageId":"UAD1537","message":"Provide the address line for the Client company address.","ruleLogic":"If AddressLineText is not provided for PartyRoleType = \\"Client\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Client/[Role] - Company Address","dataPointName":"AddressLineText","xpath":"../SERVICE/PARTIES/PARTY/ADDRESSES/ADDRESS/"},{"uniqueId":"2400.0002","dataElement":"CityName","messageId":"UAD1538","message":"Provide the city name for the Client company address.","ruleLogic":"If CityName is not provided for PartyRoleType = \\"Client\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Client/[Role] - Company Address","dataPointName":"CityName","xpath":"../SERVICE/PARTIES/PARTY/ADDRESSES/ADDRESS/"},{"uniqueId":"2400.0003","dataElement":"PostalCode","messageId":"UAD1539","message":"Provide the ZIP code for the Client company address.","ruleLogic":"If PostalCode is not provided for PartyRoleType = \\"Client\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Client/[Role] - Company Address","dataPointName":"PostalCode","xpath":"../SERVICE/PARTIES/PARTY/ADDRESSES/ADDRESS/"},{"uniqueId":"2400.0004","dataElement":"StateCode","messageId":"UAD1540","message":"Provide the state code for the Client company address.","ruleLogic":"If StateCode is not provided for PartyRoleType = \\"Client\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Client/[Role] - Company Address","dataPointName":"StateCode","xpath":"../SERVICE/PARTIES/PARTY/ADDRESSES/ADDRESS/"},{"uniqueId":"2400.0013","dataElement":"FullName","messageId":"UAD1541","message":"Provide the name of the Client.","ruleLogic":"If FullName is not provided for PartyRoleType = \\"Client\\"","severity":"Warning","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Client/[Role] - Company Name","dataPointName":"FullName","xpath":"../SERVICE/PARTIES/PARTY/LEGAL_ENTITY/LEGAL_ENTITY_DETAIL/"},{"uniqueId":"2400.0018","dataElement":"PartyRoleType","messageId":"UAD1542","message":"A party role type of 'Client' must be provided.","ruleLogic":"If no instances of PARTY with PartyRoleType = \\"Client\\" are provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Client/[Role]","dataPointName":"PartyRoleType","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/ROLE_DETAIL/"},{"uniqueId":"2400.0017","dataElement":"PartyRoleType","messageId":"UAD1543","message":"Provide a description (e.g., Lender, AMC) for the client.","ruleLogic":"If PartyRoleType = \\"Client\\" and there is not a second instance of ROLE_DETAIL in the Client instance of PARTY with PartyRoleType = \\"Attorney\\" or \\"Investor\\" or \\"Lender\\" or \\"ManagementCompany\\" or \\"Other\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Client/[Role]","dataPointName":"PartyRoleType","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/ROLE_DETAIL/"},{"uniqueId":"2400.0041","dataElement":"FirstName","messageId":"UAD1544","message":"Provide the Appraiser's first name.","ruleLogic":"If FirstName is not provided for PartyRoleType = \\"Appraiser\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Appraiser - Name","dataPointName":"FirstName","xpath":"../SERVICE/PARTIES/PARTY/INDIVIDUAL/NAME/"},{"uniqueId":"2400.0042","dataElement":"LastName","messageId":"UAD1545","message":"Provide the Appraiser's last name.","ruleLogic":"If LastName is not provided for PartyRoleType = \\"Appraiser\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Appraiser - Name","dataPointName":"LastName","xpath":"../SERVICE/PARTIES/PARTY/INDIVIDUAL/NAME/"},{"uniqueId":"2400.0051","dataElement":"AppraiserLicenseType","messageId":"UAD1546","message":"Provide the Appraiser's state-level credentials.","ruleLogic":"If AppraiserLicenseType is not provided for PartyRoleType = \\"Appraiser\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Appraiser - Level","dataPointName":"AppraiserLicenseType","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/APPRAISER_LICENSE/"},{"uniqueId":"2400.0053","dataElement":"LicenseExpirationDate","messageId":"UAD1548","message":"Provide the Appraiser's license expiration date.","ruleLogic":"If AppraiserLicenseType <> \\"None\\" and LicenseExpirationDate is not provided for PartyRoleType = \\"Appraiser\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Appraiser - Expires","dataPointName":"LicenseExpirationDate","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/LICENSE_DETAIL/"},{"uniqueId":"2400.0054","dataElement":"LicenseIdentifier","messageId":"UAD1551","message":"Provide the Appraiser's license number.","ruleLogic":"If AppraiserLicenseType <> \\"None\\" and LicenseIdentifier is not provided for PartyRoleType = \\"Appraiser\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Appraiser - ID","dataPointName":"LicenseIdentifier","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/LICENSE_DETAIL/"},{"uniqueId":"2400.0055","dataElement":"LicenseIssuingAuthorityStateCode","messageId":"UAD1552","message":"Provide the state issuing the Appraiser's license.","ruleLogic":"If AppraiserLicenseType <> \\"None\\" and LicenseIssuingAuthorityStateCode is not provided for PartyRoleType = \\"Appraiser\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Appraiser - State","dataPointName":"LicenseIssuingAuthorityStateCode","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/LICENSES/LICENSE/LICENSE_DETAIL/"},{"uniqueId":"2400.0056","dataElement":"PartyRoleType","messageId":"UAD1554","message":"A party role type of 'Appraiser' must be provided.","ruleLogic":"If no instances of PARTY with PartyRoleType = \\"Appraiser\\" are provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Appraiser","dataPointName":"PartyRoleType","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/ROLE_DETAIL/"},{"uniqueId":"","dataElement":"PartyRoleTypeOtherDescription","messageId":"UAD1555","message":"Provide a description when party role type = 'Other'.","ruleLogic":"If PartyRoleType = \\"Other\\" and PartyRoleTypeOtherDescription is not provided in a given instance of ROLE_DETAIL","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"","dataPointName":"PartyRoleTypeOtherDescription","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/ROLE_DETAIL/"},{"uniqueId":"2400.0080; 2400.0502","dataElement":"InspectionDate","messageId":"UAD1556","message":"Provide the date the Appraiser and/or Supervisory Appraiser inspected the subject property.","ruleLogic":"If (PropertyExteriorInspectionMethodType = \\"Physical\\" or \\"Virtual\\"), or (PropertyInteriorInspectionMethodType = \\"Physical\\" or \\"Virtual\\"), and InspectionDate is not provided in a given instance of INSPECTION_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Inspection Date","dataPointName":"InspectionDate","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/INSPECTION_DETAIL/"},{"uniqueId":"2400.0080; 2400.0502","dataElement":"InspectionDate","messageId":"UAD1557","message":"The 'Inspection Date' must be on or before the 'Effective Date of Appraisal'.","ruleLogic":"If InspectionDate > AppraisalReportEffectiveDate","severity":"Fatal","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Inspection Date (%PV%)","dataPointName":"InspectionDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/INSPECTION_DETAIL/","relatedValues":"AppraisalReportEffectiveDate (%RV1%)"},{"uniqueId":"2400.0081; 2400.0503","dataElement":"PropertyExteriorInspectionMethodType","messageId":"UAD1558","message":"Provide the manner in which the exterior inspection was conducted by the Appraiser and/or Supervisory Appraiser.","ruleLogic":"If PropertyExteriorInspectionMethodType is not provided in a given instance of INSPECTION_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Exterior","dataPointName":"PropertyExteriorInspectionMethodType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/INSPECTION_DETAIL/"},{"uniqueId":"2400.0082; 2400.0504","dataElement":"PropertyInteriorInspectionMethodType","messageId":"UAD1559","message":"Provide the manner in which the interior inspection was conducted by the Appraiser and/or Supervisory Appraiser.","ruleLogic":"If PropertyInteriorInspectionMethodType is not provided in a given instance of INSPECTION_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Interior","dataPointName":"PropertyInteriorInspectionMethodType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/INSPECTION_DETAIL/"},{"uniqueId":"2400.0295","dataElement":"FullName","messageId":"UAD1560","message":"Provide the 'Company Name' for the Lender or AMC.","ruleLogic":"If PartyRoleType = \\"Lender\\" or \\"ManagementCompany\\" and FullName is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Company Name","dataPointName":"FullName","xpath":"../SERVICE/PARTIES/PARTY/LEGAL_ENTITY/LEGAL_ENTITY_DETAIL/","relatedValues":"PartyRoleType (%RV1%)"},{"uniqueId":"2400.0405","dataElement":"FirstName","messageId":"UAD1561","message":"Provide the first name of the person that has provided significant real property appraisal assistance.","ruleLogic":"If PartyRoleType = \\"SignificantRealPropertyAppraisalAssistance\\" and FirstName is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Significant Real Property Appraisal Assistance - Name","dataPointName":"FirstName","xpath":"../SERVICE/PARTIES/PARTY/INDIVIDUAL/NAME/"},{"uniqueId":"2400.0406","dataElement":"LastName","messageId":"UAD1562","message":"Provide the last name of the person that has provided significant real property appraisal assistance.","ruleLogic":"If PartyRoleType = \\"SignificantRealPropertyAppraisalAssistance\\" and LastName is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Significant Real Property Appraisal Assistance - Name","dataPointName":"LastName","xpath":"../SERVICE/PARTIES/PARTY/INDIVIDUAL/NAME/"},{"uniqueId":"2400.0413","dataElement":"PartyRoleTypeAdditionalDescription","messageId":"UAD1563","message":"Provide description of the significant real property appraisal assistance provided.","ruleLogic":"If PartyRoleType = \\"SignificantRealPropertyAppraisalAssistance\\" and PartyRoleTypeAdditionalDescription is not provided","severity":"Warning","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Significant Real Property Appraisal Assistance - Description","dataPointName":"PartyRoleTypeAdditionalDescription","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/ROLE_DETAIL/"},{"uniqueId":"2500.0002","dataElement":"AmenityOwnershipType","messageId":"UAD1568","message":"Provide the ownership rights for the amenity.","ruleLogic":"If AmenityType = \\"BoatSlip\\" or \\"UnitStorage\\", and AmenityOwnershipType is not provided in a given instance of PROJECT_AMENITY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Common Amenities / Services Included","dataPointName":"AmenityOwnershipType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_AMENITIES/PROJECT_AMENITY/","relatedValues":"AmenityType (%RV1%)"},{"uniqueId":"2500.0003","dataElement":"AmenityOwnershipTypeOtherDescription","messageId":"UAD1569","message":"Provide a description when amenity ownership type = 'Other'.","ruleLogic":"If AmenityOwnershipType = \\"Other\\" and AmenityOwnershipTypeOtherDescription is not provided in a given instance of PROJECT_AMENITY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Common Amenities / Services Included","dataPointName":"AmenityOwn
11ershipTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_AMENITIES/PROJECT_AMENITY/"},{"uniqueId":"","dataElement":"PROJECT_AMENITY","messageId":"UAD1570","message":"Provide amenities in the project. Select 'None' if there are no amenities.","ruleLogic":"If (PUDIndicator = \\"true\\" or PropertyInProjectIndicator = \\"true\\"), and (at least one instance of PROJECT_AMENITY is not provided or AmenityType is not provided in a given instance of PROJECT_AMENITY)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Common Amenities / Services Included","dataPointName":"PROJECT_AMENITY","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_AMENITIES/PROJECT_AMENITY/"},{"uniqueId":"2500.0005","dataElement":"AmenityTypeOtherDescription","messageId":"UAD1571","message":"Provide a description when amenity type = 'Other'.","ruleLogic":"If AmenityType = \\"Other\\" and AmenityTypeOtherDescription is not provided in a given instance of PROJECT_AMENITY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Common Amenities / Services Included","dataPointName":"AmenityTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_AMENITIES/PROJECT_AMENITY/"},{"uniqueId":"2500.0006","dataElement":"AssociationChargeType","messageId":"UAD1572","message":"The AssociationChargeType must be provided as 'AssociationDues' for the mandatory association fees. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"IF PropertyInProjectIndicator = \\"true\\" or PUDIndicator = \\"true\\", and there is no instance of ASSOCIATION_CHARGE with AssociationChargeType = \\"AssociationDues\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"AssociationChargeType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/HOMEOWNERS_ASSOCIATIONS/HOMEOWNERS_ASSOCIATION/ASSOCIATION_CHARGES/ASSOCIATION_CHARGE/ASSOCIATION_CHARGE_DETAIL/"},{"uniqueId":"2500.0007","dataElement":"AssociationChargeAmount","messageId":"UAD1573","message":"Provide the mandatory monthly fee amount, even if the amount is 0.","ruleLogic":"If AssociationChargeType = \\"AssociationDues\\" and AssociationChargeAmount is not provided in the given instance of ASSOCIATION_CHARGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Monthly Amount","dataPointName":"AssociationChargeAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/HOMEOWNERS_ASSOCIATIONS/HOMEOWNERS_ASSOCIATION/ASSOCIATION_CHARGES/ASSOCIATION_CHARGE/ASSOCIATION_CHARGE_DETAIL/","relatedValues":"AssociationChargeType (AssociationDues)"},{"uniqueId":"2500.0008","dataElement":"AssociationChargePeriodType","messageId":"UAD1574","message":"The association charge period must be provided as monthly. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If AssociationChargeType = \\"AssociationDues\\", and AssociationChargePeriodType is either not provided, or not = \\"Monthly\\" in the given instance of ASSOCIATION_CHARGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"AssociationChargePeriodType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/HOMEOWNERS_ASSOCIATIONS/HOMEOWNERS_ASSOCIATION/ASSOCIATION_CHARGES/ASSOCIATION_CHARGE/ASSOCIATION_CHARGE_DETAIL/","relatedValues":"AssociationChargeType (AssociationDues)"},{"uniqueId":"2500.0009","dataElement":"AssociationChargeIncludesUtilityType","messageId":"UAD1575","message":"Provide the type of the common utility / service that is included in the association charges.","ruleLogic":"If AssociationChargeType = \\"AssociationDues\\" and (at least one instance of ASSOCIATION_CHARGE_INCLUDES_UTILITY is not provided or AssociationChargeIncludesUtilityType is not provided in the given instance of ASSOCIATION_CHARGE_INCLUDES_UTILITY)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Utilities Included","dataPointName":"AssociationChargeIncludesUtilityType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/HOMEOWNERS_ASSOCIATIONS/HOMEOWNERS_ASSOCIATION/ASSOCIATION_CHARGES/ASSOCIATION_CHARGE/ASSOCIATION_CHARGE_INCLUDES_UTILITIES/ASSOCIATION_CHARGE_INCLUDES_UTILITY/","relatedValues":"AssociationChargeType (AssociationDues)"},{"uniqueId":"2500.0010","dataElement":"AssociationChargeIncludesUtilityTypeOtherDescription","messageId":"UAD1576","message":"Provide a description when the type of the utility / service included in the association charges = 'Other'.","ruleLogic":"If AssociationChargeIncludesUtilityType = \\"Other\\" and AssociationChargeIncludesUtilityTypeOtherDescription is not provided in a given instance of ASSOCIATION_CHARGE_INCLUDES_UTILITY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Utilities Included","dataPointName":"AssociationChargeIncludesUtilityTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/HOMEOWNERS_ASSOCIATIONS/HOMEOWNERS_ASSOCIATION/ASSOCIATION_CHARGES/ASSOCIATION_CHARGE/ASSOCIATION_CHARGE_INCLUDES_UTILITIES/ASSOCIATION_CHARGE_INCLUDES_UTILITY/"},{"uniqueId":"2500.0012","dataElement":"AssociationChargeType","messageId":"UAD1577","message":"The AssociationChargeType must be provided as 'AssociationSpecialAssessment' for the project special assessments. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" or PUDIndicator = \\"true\\", and there is no instance of ASSOCIATION_CHARGE with AssociationChargeType = \\"AssociationSpecialAssessment\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"AssociationChargeType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/HOMEOWNERS_ASSOCIATIONS/HOMEOWNERS_ASSOCIATION/ASSOCIATION_CHARGES/ASSOCIATION_CHARGE/ASSOCIATION_CHARGE_DETAIL/"},{"uniqueId":"2500.0013","dataElement":"AssociationChargeBalanceAmount","messageId":"UAD1578","message":"Provide the existing special assessment balance attributed to the subject property.","ruleLogic":"If AssociationChargeType = \\"AssociationSpecialAssessment\\" and AssociationSpecialAssessmentStatusType = \\"Existing\\", and AssociationChargeBalanceAmount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"AssociationChargeBalanceAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/HOMEOWNERS_ASSOCIATIONS/HOMEOWNERS_ASSOCIATION/ASSOCIATION_CHARGES/ASSOCIATION_CHARGE/ASSOCIATION_CHARGE_DETAIL/","relatedValues":"AssociationChargeType (AssociationSpecialAssessment)"},{"uniqueId":"2500.0019","dataElement":"OwnershipTransferFeeIndicator","messageId":"UAD1579","message":"Indicate whether transferring ownership incurs a fee with the association.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and OwnershipTransferFeeIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"OwnershipTransferFeeIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/HOMEOWNERS_ASSOCIATIONS/HOMEOWNERS_ASSOCIATION/ASSOCIATION_CHARGES/ASSOCIATION_CHARGE/ASSOCIATION_CHARGE_DETAIL/"},{"uniqueId":"2500.0023","dataElement":"CooperativeProprietaryLeaseExpirationDate","messageId":"UAD1580","message":"Provide the cooperative proprietary lease expiration date.","ruleLogic":"If ProjectLegalStructureType = \\"Cooperative\\" or \\"Condop\\", and CooperativeProprietaryLeaseExpirationDate is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information","reportLabel":"Proprietary Lease Expires","dataPointName":"CooperativeProprietaryLeaseExpirationDate","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"2500.0024","dataElement":"PropertyCooperativeSharesCount","messageId":"UAD1581","message":"Provide the number of 'Shares Attributable to Subject Property'.","ruleLogic":"If ProjectLegalStructureType = \\"Cooperative\\" or \\"Condop\\", and PropertyCooperativeSharesCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information","reportLabel":"Shares Attributable to Subject Property","dataPointName":"PropertyCooperativeSharesCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"2500.0025","dataElement":"ProRataSharePercent","messageId":"UAD1582","message":"Provide the 'Pro Rata Share' for the subject property.","ruleLogic":"If ProjectBlanketFinancingIndicator = \\"true\\" and ProRataSharePercent is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information - Project Blanket Financing","reportLabel":"Pro Rata Share","dataPointName":"ProRataSharePercent","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"}
11,{"uniqueId":"2500.0031","dataElement":"ProjectAnalysisGroundRentIndicator","messageId":"UAD1583","message":"Indicate whether the project is subject to ground rent.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectAnalysisGroundRentIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Ground Rent","dataPointName":"ProjectAnalysisGroundRentIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_ANALYSIS/"},{"uniqueId":"2500.0032","dataElement":"ProjectConditionAndQualityDescription","messageId":"UAD1584","message":"Provide a description of the deficiencies observed in the project.","ruleLogic":"If ProjectDeficiencyObservedIndicator = \\"true\\" and ProjectConditionAndQualityDescription is not provided","severity":"Warning","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Description of Deficiencies","dataPointName":"ProjectConditionAndQualityDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_ANALYSIS/"},{"uniqueId":"2500.0033","dataElement":"ProjectDeficiencyObservedIndicator","messageId":"UAD1585","message":"Indicate whether any deficiencies that impact value / marketability have been observed in the project.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectDeficiencyObservedIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Observed Deficiencies","dataPointName":"ProjectDeficiencyObservedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_ANALYSIS/"},{"uniqueId":"2500.0036","dataElement":"BalloonIndicator","messageId":"UAD1586","message":"Indicate whether a final balloon payment is required to fully pay off the loan.","ruleLogic":"If ProjectBlanketFinancingIndicator = \\"true\\" and BalloonIndicator is not provided in a given instance of PROJECT_BLANKET_FINANCING","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information - Project Blanket Financing","reportLabel":"Balloon Mortgage","dataPointName":"BalloonIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_BLANKET_FINANCINGS/PROJECT_BLANKET_FINANCING/","relatedValues":"LienPriorityType (%RV1%)"},{"uniqueId":"2500.0041","dataElement":"LoanRemainingMaturityTermMonthsCount","messageId":"UAD1587","message":"Provide the remaining maturity term for each lien of the project blanket financing.","ruleLogic":"If ProjectBlanketFinancingIndicator = \\"true\\" and LoanRemainingMaturityTermMonthsCount is not provided in a given instance of PROJECT_BLANKET_FINANCING","severity":"Warning","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information - Project Blanket Financing","reportLabel":"Remaining Term","dataPointName":"LoanRemainingMaturityTermMonthsCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_BLANKET_FINANCINGS/PROJECT_BLANKET_FINANCING/","relatedValues":"LienPriorityType (%RV1%)"},{"uniqueId":"2500.0044","dataElement":"UPBProRataShareAttributableToUnitAmount","messageId":"UAD1588","message":"Provide the 'Pro Rata Share of Balance Attributable to Unit'.","ruleLogic":"If ProjectBlanketFinancingIndicator = \\"true\\", and LineOfCreditIndicator = \\"false\\", and UPBProRataShareAttributableToUnitAmount is not provided in a given instance of PROJECT_BLANKET_FINANCING","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information - Project Blanket Financing","reportLabel":"Pro Rata Share of Balance Attributable to Unit","dataPointName":"UPBProRataShareAttributableToUnitAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_BLANKET_FINANCINGS/PROJECT_BLANKET_FINANCING/","relatedValues":"LienPriorityType (%RV1%)"},{"uniqueId":"2500.0046","dataElement":"UPBAmount","messageId":"UAD1589","message":"Provide the 'Unpaid Principal Balance'.","ruleLogic":"If ProjectBlanketFinancingIndicator = \\"true\\", and LineOfCreditIndicator = \\"false\\", and UPBAmount is not provided in a given instance of PROJECT_BLANKET_FINANCING","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information - Project Blanket Financing","reportLabel":"Unpaid Principal Balance","dataPointName":"UPBAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_BLANKET_FINANCINGS/PROJECT_BLANKET_FINANCING/","relatedValues":"LienPriorityType (%RV1%)"},{"uniqueId":"2500.0048","dataElement":"ProjectConversionIndicator","messageId":"UAD1590","message":"Indicate whether the property has been converted from its prior use.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectConversionIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Converted in Past 3 Years","dataPointName":"ProjectConversionIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_CONVERSION/"},{"uniqueId":"2500.0049","dataElement":"ProjectConversionOriginalUseType","messageId":"UAD1591","message":"Provide the original use of the project.","ruleLogic":"If (PropertyInProjectIndicator = \\"true\\" and ProjectConversionIndicator = \\"true\\"), and ProjectConversionOriginalUseType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ProjectConversionOriginalUseType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_CONVERSION/"},{"uniqueId":"2500.0050","dataElement":"ProjectConversionOriginalUseTypeOtherDescription","messageId":"UAD1592","message":"Provide a description when the project's original use = 'Other'.","ruleLogic":"If ProjectConversionOriginalUseType = \\"Other\\" and ProjectConversionOriginalUseTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ProjectConversionOriginalUseTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_CONVERSION/"},{"uniqueId":"2500.0051","dataElement":"LegalActionIndicator","messageId":"UAD1593","message":"Indicate whether the research on the project revealed pending or current legal actions.","ruleLogic":"If (PropertyInProjectIndicator = \\"true\\" or PUDIndicator = \\"true\\") and LegalActionIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"LegalActionIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2500.0055","dataElement":"ProjectCommercialSpaceIndicator","messageId":"UAD1594","message":"Indicate whether the project contains commercial space.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectCommercialSpaceIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ProjectCommercialSpaceIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2500.0057","dataElement":"ProjectCommercialSpacePercent","messageId":"UAD1595","message":"Provide the overall percentage of commercial space in the project in which the subject property is located.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\", and ProjectCommercialSpaceIndicator = \\"true\\", and ProjectCommercialSpacePercent is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ProjectCommercialSpacePercent","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2500.0058","dataElement":"ProjectCompletedIndicator","messageId":"UAD1596","message":"Indicate whether the construction of the units, common elements and amenities in the project are complete.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectCompletedIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Are units, common areas, and amenities in project complete?","dataPointName":"ProjectCompletedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2500.0060","dataElement":"ProjectDwellingUnitCount","messageId":"UAD1597","message":"Provide the total number of units in the project.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectDwellingUnitCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Total Units","dataPointName":"ProjectDwellingUnitCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2500.0061","dataElement":"ProjectDwellingUnitsForSaleCount","messageId":"UAD1598","message":"Provide the total number of units in the project that are currently for sale.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectDwellingUnitsForSaleCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Units for Sale","dataPointName":"ProjectDwellingUnitsForSaleCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2500.0062","dataElement":"ProjectDwellingUnitsRentedCount","messageId":"UAD1599","message":"Provide the total number of units in the project that are currently rented.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectDwellingUnitsRentedCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Units Rented","dataPointName":"ProjectDwellingUnitsRentedCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2500.0064","dataElement":"ProjectDwellingUnitsSoldCount","messageId":"UAD1600","message":"Provide the total number of units in the project that have been sold.","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectDwellingUnitsSoldCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Units Sold","dataPointName":"ProjectDwellingUnitsSoldCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2500.0066","dataElement":"SubjectBuildingCompletedIndicator","messageId":"UAD1601","message":"Indicate whether the project's building containing the subject property is complete.","ruleLogic":"If (PropertyInProjectIndicator = \\"true\\" and ProjectCompletedIndicator = \\"false\\") and SubjectBuildingCompletedIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Subject Property Building Complete","dataPointName":"SubjectBuildingCompletedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2500.0067","dataElement":"ProjectDeveloperOrSponsorControlsProjectManagementIndicator","messageId":"UAD1602","message":"Indicate whether the developer or the sponsor is in control of the management of the project.","ruleLogic":"If (PropertyInProjectIndicator = \\"true\\" or PUDIndicator = \\"true\\") and ProjectDeveloperOrSponsorControlsProjectManagementIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ProjectDeveloperOrSponsorControlsProjectManagementIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DEVELOPER/"},{"uniqueId":"2500.0071","dataElement":"ProjectComponentCategoryType","messageId":"UAD1603","message":"Provide the incomplete project element
11(s).","ruleLogic":"If ProjectCompletedIndicator = \\"false\\" and (at least one instance of PROJECT_COMPONENT is not provided or ProjectComponentCategoryType is not provided in a given instance of PROJECT_COMPONENT)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ProjectComponentCategoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_COMPONENTS/PROJECT_COMPONENT/"},{"uniqueId":"2500.0072","dataElement":"ProjectComponentCategoryTypeOtherDescription","messageId":"UAD1604","message":"Provide a description when the incomplete project element = 'Other'.","ruleLogic":"If ProjectComponentCategoryType = \\"Other\\" and ProjectComponentCategoryTypeOtherDescription is not provided in a given instance of PROJECT_COMPONENT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"ProjectComponentCategoryTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_COMPONENTS/PROJECT_COMPONENT/"},{"uniqueId":"2500.0073","dataElement":"ProjectComponentCompletedIndicator","messageId":"UAD1605","message":"Deliver ProjectComponentCompletedIndicator as false for each incomplete project element. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ProjectCompletedIndicator = \\"false\\" and ProjectComponentCompletedIndicator is not = \\"false\\" in a given instance of PROJECT_COMPONENT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ProjectComponentCompletedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_COMPONENTS/PROJECT_COMPONENT/","relatedValues":"ProjectComponentCategoryType (%RV1%)"},{"uniqueId":"2500.0074","dataElement":"ProjectBlanketFinancingIndicator","messageId":"UAD1606","message":"Indicate whether the cooperative has project blanket financing.","ruleLogic":"If ProjectLegalStructureType = \\"Cooperative\\" or \\"Condop\\", and ProjectBlanketFinancingIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information","reportLabel":"{No Label}","dataPointName":"ProjectBlanketFinancingIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_FINANCIAL_INFORMATION/"},{"uniqueId":"2500.0075","dataElement":"ProjectTotalSharesIssuedAndOutstandingCount","messageId":"UAD1607","message":"Provide the number of 'Shares Issued and Outstanding'.","ruleLogic":"If ProjectLegalStructureType = \\"Cooperative\\" or \\"Condop\\", and ProjectTotalSharesIssuedAndOutstandingCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information","reportLabel":"Shares Issued and Outstanding","dataPointName":"ProjectTotalSharesIssuedAndOutstandingCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_FINANCIAL_INFORMATION/"},{"uniqueId":"2500.0076","dataElement":"SingleEntityGreatestNumberOfSharesCount","messageId":"UAD1608","message":"Provide the greatest number of shares owned by a single entity in the cooperative project.","ruleLogic":"If ProjectLegalStructureType = \\"Cooperative\\" or \\"Condop\\", and SingleEntityGreatestNumberOfSharesCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"SingleEntityGreatestNumberOfSharesCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_FINANCIAL_INFORMATION/"},{"uniqueId":"2500.0078","dataElement":"SingleEntityGreatestNumberOfUnitsCount","messageId":"UAD1609","message":"Provide the greatest number of units owned by a single entity in the condominium project.","ruleLogic":"If ProjectLegalStructureType = \\"Condominium\\" and SingleEntityGreatestNumberOfUnitsCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"SingleEntityGreatestNumberOfUnitsCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_FINANCIAL_INFORMATION/"},{"uniqueId":"2500.0081","dataElement":"PropertyTaxAbatementsOrExemptionsIndicator","messageId":"UAD1610","message":"Indicate whether a tax reduction or exemption has been granted to the subject property.","ruleLogic":"If (PropertyInProjectIndicator = \\"true\\" or PUDIndicator = \\"true\\") and PropertyTaxAbatementsOrExemptionsIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"PropertyTaxAbatementsOrExemptionsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_TAXES/PROPERTY_TAX/PROPERTY_TAX_DETAIL/"},{"uniqueId":"2500.0084","dataElement":"TaxAbatementsOrExemptionsExpirationDate","messageId":"UAD1611","message":"The expiration date for the tax abatements or exemptions cannot be before the 'Effective Date of Appraisal'.","ruleLogic":"If TaxAbatementsOrExemptionsExpirationDate < YYYY-MM of AppraisalReportEffectiveDate","severity":"Warning","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail (%PV%)","dataPointName":"TaxAbatementsOrExemptionsExpirationDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_TAXES/PROPERTY_TAX/PROPERTY_TAX_EXEMPTIONS/PROPERTY_TAX_EXEMPTION/","relatedValues":"AppraisalReportEffectiveDate (%RV1%)"},{"uniqueId":"2500.0151","dataElement":"LineOfCreditIndicator","messageId":"UAD1612","message":"Indicate whether the given lien is a line of credit.","ruleLogic":"If ProjectBlanketFinancingIndicator = \\"true\\" and LineOfCreditIndicator is not provided in a given instance of PROJECT_BLANKET_FINANCING","severity":"Warning","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LineOfCreditIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_BLANKET_FINANCINGS/PROJECT_BLANKET_FINANCING/","relatedValues":"LienPriorityType (%RV1%)"},{"uniqueId":"2500.0163","dataElement":"AssociationSpecialAssessmentStatusType","messageId":"UAD1613","message":"Provide the association special assessment status (i.e., existing, none, proposed).","ruleLogic":"If AssociationChargeType = \\"AssociationSpecialAssessment\\" and AssociationSpecialAssessmentStatusType is not provided in the given instance of ASSOCIATION_CHARGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail","dataPointName":"AssociationSpecialAssessmentStatusType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/HOMEOWNERS_ASSOCIATIONS/HOMEOWNERS_ASSOCIATION/ASSOCIATION_CHARGES/ASSOCIATION_CHARGE/ASSOCIATION_CHARGE_DETAIL/","relatedValues":"AssociationChargeType (AssociationSpecialAssessment)"},{"uniqueId":"2500.0165","dataElement":"@xlink:arcrole","messageId":"UAD1614","message":"Provide at least one data source when the subject property is located in a project or PUD. In the UAD XML, a minimum of one RELATIONSHIP container must be included that links DATA_SOURCE to PROJECT. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and (PropertyInProjectIndicator = \\"true\\" or PUDIndicator = \\"true\\"), and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DATA_SOURCE_IsDataSourceFor_PROJECT\\" that links DATA_SOURCE to PROJECT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"2500.0168","dataElement":"ProjectLegalStructureType","messageId":"UAD1615","message":"Provide the project legal structure ( i.e., Condominium, Cooperative, Condop).","ruleLogic":"If PropertyInProjectIndicator = \\"true\\" and ProjectLegalStructureType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"{No Subsection}","reportLabel":"Condominium; Cooperative; Condop","dataPointName":"ProjectLegalStructureType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROJECT/PROJECT_DETAIL/"},{"uniqueId":"2600.0003","dataElement":"EfficiencyRatingExistsIndicator","messageId":"UAD1616","message":"Indicate whether the property has obtained an efficie
11ncy rating.","ruleLogic":"If EfficiencyRatingExistsIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Energy Efficient and Green Features","reportSubsection":"{No Subsection}","reportLabel":"Known Efficiency Ratings","dataPointName":"EfficiencyRatingExistsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENERGY_EFFICIENCY_AND_GREEN/ENERGY_EFFICIENCY_AND_GREEN_DETAIL/"},{"uniqueId":"2600.0004","dataElement":"GreenCertificationExistsIndicator","messageId":"UAD1617","message":"Indicate whether the property has obtained green, health or wellness certification.","ruleLogic":"If GreenCertificationExistsIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Energy Efficient and Green Features","reportSubsection":"{No Subsection}","reportLabel":"Known Building Certifications","dataPointName":"GreenCertificationExistsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENERGY_EFFICIENCY_AND_GREEN/ENERGY_EFFICIENCY_AND_GREEN_DETAIL/"},{"uniqueId":"2600.0005","dataElement":"RenewableEnergyComponentExistsIndicator","messageId":"UAD1618","message":"Indicate whether the property has any renewable energy components.","ruleLogic":"If RenewableEnergyComponentExistsIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Energy Efficient and Green Features","reportSubsection":"{No Subsection}","reportLabel":"Known Renewable Energy Components","dataPointName":"RenewableEnergyComponentExistsIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENERGY_EFFICIENCY_AND_GREEN/ENERGY_EFFICIENCY_AND_GREEN_DETAIL/"},{"uniqueId":"2600.0016","dataElement":"RenewableEnergyComponentFinancedIndicator","messageId":"UAD1619","message":"Indicate whether the renewable energy component is subject to a financing arrangement.","ruleLogic":"If RenewableEnergyComponentOwnershipType = \\"Owned\\" and RenewableEnergyComponentFinancedIndicator is not provided in a given instance of RENEWABLE_ENERGY_COMPONENT","severity":"Warning","propertyAffected":"Subject","reportSection":"Energy Efficient and Green Features","reportSubsection":"{No Subsection}","reportLabel":"Financing Arrangement","dataPointName":"RenewableEnergyComponentFinancedIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENERGY_EFFICIENCY_AND_GREEN/RENEWABLE_ENERGY_COMPONENTS/RENEWABLE_ENERGY_COMPONENT/","relatedValues":"RenewableEnergyComponentType (%RV1%)"},{"uniqueId":"2600.0018","dataElement":"RenewableEnergyComponentOwnershipTypeOtherDescription","messageId":"UAD1620","message":"Provide a description when renewable energy component ownership type = 'Other'.","ruleLogic":"If RenewableEnergyComponentOwnershipType = \\"Other\\" and RenewableEnergyComponentOwnershipTypeOtherDescription is not provided in a given instance of RENEWABLE_ENERGY_COMPONENT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Energy Efficient and Green Features","reportSubsection":"{No Subsection}","reportLabel":"Ownership","dataPointName":"RenewableEnergyComponentOwnershipTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENERGY_EFFICIENCY_AND_GREEN/RENEWABLE_ENERGY_COMPONENTS/RENEWABLE_ENERGY_COMPONENT/"},{"uniqueId":"2600.0019","dataElement":"RenewableEnergyComponentType","messageId":"UAD1622","message":"Provide the type of renewable energy component.","ruleLogic":"If RenewableEnergyComponentExistsIndicator = \\"true\\" and (at least one instance of RENEWABLE_ENERGY_COMPONENT is not provided or RenewableEnergyComponentType is not provided in a given instance of RENEWABLE_ENERGY_COMPONENT)","severity":"Warning","propertyAffected":"Subject","reportSection":"Energy Efficient and Green Features","reportSubsection":"{No Subsection}","reportLabel":"Renewable Energy Component","dataPointName":"RenewableEnergyComponentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENERGY_EFFICIENCY_AND_GREEN/RENEWABLE_ENERGY_COMPONENTS/RENEWABLE_ENERGY_COMPONENT/"},{"uniqueId":"2600.0020","dataElement":"RenewableEnergyComponentTypeOtherDescription","messageId":"UAD1623","message":"Provide a description when renewable energy component type = 'Other'.","ruleLogic":"If RenewableEnergyComponentType = \\"Other\\" and RenewableEnergyComponentTypeOtherDescription is not provided in a given instance of RENEWABLE_ENERGY_COMPONENT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Energy Efficient and Green Features","reportSubsection":"{No Subsection}","reportLabel":"Renewable Energy Component","dataPointName":"RenewableEnergyComponentTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/ENERGY_EFFICIENCY_AND_GREEN/RENEWABLE_ENERGY_COMPONENTS/RENEWABLE_ENERGY_COMPONENT/"},{"uniqueId":"1300.0010","dataElement":"PropertyValuationConditionalConclusionType","messageId":"UAD1624","message":"At least one defect, damage, or deficiency must be provided when the appraisal 'Market Value Condition' is 'Subject to Repair'.","ruleLogic":"If PropertyValuationConditionalConclusionType = \\"SubjectToRepair\\" and there are no instances of DEFECT_DETAIL with DefectItemRecommendedActionType = \\"Repair\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Market Value Condition","dataPointName":"PropertyValuationConditionalConclusionType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_CONDITIONS/VALUATION_CONDITION/"},{"uniqueId":"3000.0008","dataElement":"MarketBoundariesDescription","messageId":"UAD1626","message":"Provide a description of the 'Market Boundary'.","ruleLogic":"If MarketBoundariesDescription is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"{No Subsection}","reportLabel":"Market Boundary","dataPointName":"MarketBoundariesDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_DETAIL/"},{"uniqueId":"3000.0009","dataElement":"MarketInventoryLookbackMonthsCount","messageId":"UAD1627","message":"Provide the lookback period for sales in the market area.","ruleLogic":"If MarketInventoryLookbackMonthsCount is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Sales in Past ___ Months","dataPointName":"MarketInventoryLookbackMonthsCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_DETAIL/"},{"uniqueId":"3000.0018","dataElement":"MarketInventoryCount","messageId":"UAD1629","message":"Provide the number of active listings, even if the value is 0.","ruleLogic":"If MarketInventoryCount is not provided for the instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Active Listings","dataPointName":"MarketInventoryCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0019","dataElement":"MarketInventoryHighestPriceAmount","messageId":"UAD1630","message":"Provide the 'Highest List Price'.","ruleLogic":"If MarketInventoryHighestPriceAmount is not provided in the instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\" and MarketInventoryCount > 0","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Highest List Price","dataPointName":"MarketInventoryHighestPriceAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0019","dataElement":"MarketInventoryHighestPriceAmount","messageId":"UAD1631","message":"The 'Highest List Price' must be greater than $0.","ruleLogic":"If MarketInventoryHighestPriceAmount <= 0 for the instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Highest List Price (%PV%)","dataPointName":"MarketInventoryHighestPriceAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/","minValue":1},{"uniqueId":"3000.0020","dataElement":"MarketInventoryLowestPriceAmount","messageId":"UAD1632","message":"Provide the 'Lowest List Price'.","ruleLogic":"If MarketInventoryLowestPriceAmount is not provided in the instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\" and MarketInventoryCount > 0","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Lowest List Price","dataPointName":"MarketInventoryLowestPriceAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0020","dataElement":"MarketInventoryLowestPriceAmount","messageId":"UAD1633","message":"The 'Lowest List Price' must be greater than $0.","ruleLogic":"If MarketInventoryLowestPriceAmount <= 0 for the instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Lowest List Price (%PV%)","dataPointName":"MarketInventoryLowestPriceAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/","minValue":1},{"uniqueId":"3000.0021","dataElement":"MarketInventoryMedianDaysOnMarketCount","messageId":"UAD1634","message":"Provide the 'Median Days on Market' for the active listings.","ruleLogic":"If MarketInventoryMedianDaysOnMarketCount is not provided in the instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\" and MarketInventoryCount > 0","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Median Days on Market","dataPointName":"MarketInventoryMedianDaysOnMarketCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0022","dataElement":"MarketInventoryMedianPriceAmount","messageId":"UAD1635","message":"Provide the 'Median List Price'.","ruleLogic":"If MarketInventoryMedianPriceAmount is not provided in the instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\" and MarketInventoryCount > 0","severity":"Warning","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Median List Price","dataPointName":"MarketInventoryMedianPriceAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0022","dataElement":"MarketInventoryMedianPriceAmount","messageId":"UAD1636","message":"The 'Median List Price' must be greater than $0.","ruleLogic":"If MarketInventoryMedianPriceAmount <= 0 for the instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Median List Price (%PV%)","dataPointName":"MarketInventoryMedianPriceAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/","minValue":1},{"uniqueId":"3000.0023","dataElement":"MarketInventoryType","messageId":"UAD1637","message":"The market inventory type qual
11ifier of 'ActiveListings' must be provided only once. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is more than one instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MarketInventoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0023","dataElement":"MarketInventoryType","messageId":"UAD1638","message":"A market inventory type qualifier of 'ActiveListings' must be provided for active listings inventory. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is no instance of MARKET_INVENTORY with MarketInventoryType = \\"ActiveListings\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MarketInventoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0024","dataElement":"MarketInventoryCount","messageId":"UAD1639","message":"Provide the number of pending sales, even if the value is 0.","ruleLogic":"If MarketInventoryCount is not provided for the instance of MARKET_INVENTORY with MarketInventoryType = \\"PendingSales\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Pending Sales","dataPointName":"MarketInventoryCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0025","dataElement":"MarketInventoryType","messageId":"UAD1640","message":"A market inventory type qualifier of 'PendingSales' must be provided only once. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is more than one instance of MARKET_INVENTORY with MarketInventoryType = \\"PendingSales\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MarketInventoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0025","dataElement":"MarketInventoryType","messageId":"UAD1641","message":"A market inventory type qualifier of 'PendingSales' must be provided for pending sales inventory. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is no instance of MARKET_INVENTORY with MarketInventoryType = \\"PendingSales\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MarketInventoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0026","dataElement":"MarketInventoryCount","messageId":"UAD1642","message":"Provide the number of total sales within the look back period, even if the value is 0.","ruleLogic":"If MarketInventoryCount is not provided for the instance of MARKET_INVENTORY with MarketInventoryType = \\"TotalSales\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Sales in Past ___ Months","dataPointName":"MarketInventoryCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0027","dataElement":"MarketInventoryHighestPriceAmount","messageId":"UAD1643","message":"Provide the 'Highest Sale Price'.","ruleLogic":"If MarketInventoryHighestPriceAmount is not provided in the instance of MARKET_INVENTORY with MarketInventoryType = \\"TotalSales\\" and MarketInventoryCount > 0","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Highest Sale Price","dataPointName":"MarketInventoryHighestPriceAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0027","dataElement":"MarketInventoryHighestPriceAmount","messageId":"UAD1644","message":"The 'Highest Sale Price' must be greater than $0.","ruleLogic":"If MarketInventoryHighestPriceAmount <= 0 for the instance of MARKET_INVENTORY with MarketInventoryType = \\"TotalSales\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Highest Sale Price (%PV%)","dataPointName":"MarketInventoryHighestPriceAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/","minValue":1},{"uniqueId":"3000.0028","dataElement":"MarketInventoryLowestPriceAmount","messageId":"UAD1645","message":"Provide the 'Lowest Sale Price'.","ruleLogic":"If MarketInventoryLowestPriceAmount is not provided in the instance of MARKET_INVENTORY with MarketInventoryType = \\"TotalSales\\" and MarketInventoryCount > 0","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Lowest Sale Price","dataPointName":"MarketInventoryLowestPriceAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0028","dataElement":"MarketInventoryLowestPriceAmount","messageId":"UAD1646","message":"The 'Lowest Sale Price' must be greater than $0.","ruleLogic":"If MarketInventoryLowestPriceAmount <= 0 for the instance of MARKET_INVENTORY with MarketInventoryType = \\"TotalSales\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Lowest Sale Price (%PV%)","dataPointName":"MarketInventoryLowestPriceAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/","minValue":1},{"uniqueId":"3000.0029","dataElement":"MarketInventoryMedianPriceAmount","messageId":"UAD1647","message":"Provide the 'Median Sale Price'.","ruleLogic":"If MarketInventoryMedianPriceAmount is not provided in the instance of MARKET_INVENTORY with MarketInventoryType = \\"TotalSales\\" and MarketInventoryCount > 0","severity":"Warning","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Median Sale Price","dataPointName":"MarketInventoryMedianPriceAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0029","dataElement":"MarketInventoryMedianPriceAmount","messageId":"UAD1648","message":"The 'Median Sale Price' must be greater than $0.","ruleLogic":"If MarketInventoryMedianPriceAmount <= 0 for the instance of MARKET_INVENTORY with MarketInventoryType = \\"TotalSales\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Median Sale Price (%PV%)","dataPointName":"MarketInventoryMedianPriceAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/","minValue":1},{"uniqueId":"3000.0030","dataElement":"MarketInventoryType","messageId":"UAD1649","message":"A market inventory type qual
11ifier of 'TotalSales' must be provided only once. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is more than one instance of MARKET_INVENTORY with MarketInventoryType = \\"TotalSales\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MarketInventoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0030","dataElement":"MarketInventoryType","messageId":"UAD1650","message":"A market inventory type qualifier of 'TotalSales' must be provided for total sales inventory. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is no instance of MARKET_INVENTORY with MarketInventoryType = \\"TotalSales\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MarketInventoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_INVENTORIES/MARKET_INVENTORY/"},{"uniqueId":"3000.0033","dataElement":"MarketSupplyTrendType","messageId":"UAD1652","message":"Provide 'Demand/Supply'.","ruleLogic":"If MarketSupplyTrendType is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Housing Trends","reportLabel":"Demand/Supply","dataPointName":"MarketSupplyTrendType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_TREND/"},{"uniqueId":"3000.0034","dataElement":"MarketTrendsForeclosureActivityIndicator","messageId":"UAD1653","message":"Indicate whether distressed market competition exists.","ruleLogic":"If MarketTrendsForeclosureActivityIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Distressed Market Competition","dataPointName":"MarketTrendsForeclosureActivityIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/MARKET/MARKET_TREND/"},{"uniqueId":"1400.0638","dataElement":"ImageCategoryType","messageId":"UAD1656","message":"Provide either an image of the price trend graph or price trend anal
11ysis commentary.","ruleLogic":"If PriceTrendsAnalysisDescription is not provided, and ImageCategoryType = \\"PriceTrendGraph\\" is not provided in any instance of IMAGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Graph","dataPointName":"ImageCategoryType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/"},{"uniqueId":"3000.0051","dataElement":"DataSourceName","messageId":"UAD1657","message":"Provide 'Price Trend Source' name for each data source used for the development of the price trend analysis.","ruleLogic":"If DataSourceName is not provided in a given instance of DATA_SOURCE that captures the Price Trend Source","severity":"Warning","propertyAffected":"N/A","reportSection":"Market","reportSubsection":"Search Result Metrics","reportLabel":"Price Trend Source","dataPointName":"DataSourceName","xpath":"../VALUATION_ANALYSIS/DATA_SOURCES/DATA_SOURCE/"},{"uniqueId":"3000.0053","dataElement":"@xlink:arcrole","messageId":"UAD1658","message":"Provide at least one data source that the Appraiser used to determine price trends for the subject property. In the UAD XML, a minimum of one RELATIONSHIP must be included linking DATA_SOURCE to MARKET_TREND. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DATA_SOURCE_IsDataSourceFor_MARKET_TREND\\" linking DATA_SOURCE to MARKET_TREND where @ValuationUseType = \\"SubjectProperty\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"3100.0003","dataElement":"FinanciallyFeasibleIndicator","messageId":"UAD1659","message":"Indicate whether the highest and best use of the property is financially feasible.","ruleLogic":"If FinanciallyFeasibleIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Highest and Best Use","reportSubsection":"{No Subsection}","reportLabel":"Financially Feasible","dataPointName":"FinanciallyFeasibleIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HIGHEST_AND_BEST_USE/"},{"uniqueId":"3100.0004","dataElement":"LegallyPermissibleIndicator","messageId":"UAD1660","message":"Indicate whether the highest and best use of the property is legally permissible.","ruleLogic":"If LegallyPermissibleIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Highest and Best Use","reportSubsection":"{No Subsection}","reportLabel":"Legally Permissible","dataPointName":"LegallyPermissibleIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HIGHEST_AND_BEST_USE/"},{"uniqueId":"3100.0005","dataElement":"MaximallyProductiveIndicator","messageId":"UAD1661","message":"Indicate whether the highest and best use of the property is maximally productive.","ruleLogic":"If MaximallyProductiveIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Highest and Best Use","reportSubsection":"{No Subsection}","reportLabel":"Maximally Productive","dataPointName":"MaximallyProductiveIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HIGHEST_AND_BEST_USE/"},{"uniqueId":"3100.0006","dataElement":"PhysicallyPossibleIndicator","messageId":"UAD1662","message":"Indicate whether the highest and best use of the property is physically possible.","ruleLogic":"If PhysicallyPossibleIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Highest and Best Use","reportSubsection":"{No Subsection}","reportLabel":"Physically Possible","dataPointName":"PhysicallyPossibleIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HIGHEST_AND_BEST_USE/"},{"uniqueId":"3100.0007","dataElement":"SiteHighestBestUseIndicator","messageId":"UAD1663","message":"Indicate whether the present or the proposed use is the highest and best.","ruleLogic":"If SiteHighestBestUseIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Highest and Best Use","reportSubsection":"{No Subsection}","reportLabel":"Is the highest and best use of the subject property as improved (or as proposed per plans and specifications) the present use?","dataPointName":"SiteHighestBestUseIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/HIGHEST_AND_BEST_USE/"},{"uniqueId":"3200.0004","dataElement":"CarStorageAreaMeasure","messageId":"UAD1664","message":"Provide the area of the 'Carport' or 'Garage'.","ruleLogic":"If CarStorageType = \\"Carport\\" or \\"Garage\\", and CarStorageAreaMeasure is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"{No Subsection}","reportLabel":"Detail","dataPointName":"CarStorageAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"3200.0005","dataElement":"CarStorageAttachmentType","messageId":"UAD1665","message":"Provide the attachment type for the 'Carport' or 'Garage'.","ruleLogic":"If CarStorageType = \\"Carport\\" or \\"Garage\\", and CarStorageAttachmentType is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"{No Subsection}","reportLabel":"Detail","dataPointName":"CarStorageAttachmentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"3200.0006","dataElement":"CarStorageType","messageId":"UAD1667","message":"The type of vehicle storage must be included. Select 'None' if there is no vehicle storage.","ruleLogic":"If at least one instance of CAR_STORAGE_DETAIL is not provided or CarStorageType is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"{No Subsection}","reportLabel":"Storage","dataPointName":"CarStorageType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/"},{"uniqueId":"3200.0007","dataElement":"CarStorageTypeOtherDescription","messageId":"UAD1668","message":"Provide a description when vehicle storage type = 'Other'.","ruleLogic":"If CarStorageType = \\"Other\\" and CarStorageTypeOtherDescription is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"{No Subsection}","reportLabel":"Storage","dataPointName":"CarStorageTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/"},{"uniqueId":"3200.0008","dataElement":"ImprovedSurfaceMaterialType","messageId":"UAD1669","message":"Provide the material used for the 'Driveway' or 'Shared Driveway'.","ruleLogic":"If CarStorageType = \\"Driveway\\" or \\"SharedDriveway\\", and ImprovedSurfaceMaterialType is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"{No Subsection}","reportLabel":"Detail","dataPointName":"ImprovedSurfaceMaterialType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"3200.0009","dataElement":"ImprovedSurfaceMaterialTypeOtherDescription","messageId":"UAD1670","message":"Provide a description when street surface material = 'Other'.","ruleLogic":"If ImprovedSurfaceMaterialType = \\"Other\\" and ImprovedSurfaceMaterialTypeOtherDescription is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"{No Subsection}","reportLabel":"Detail","dataPointName":"ImprovedSurfaceMaterialTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/"},{"uniqueId":"3200.0010","dataElement":"ParkingSpacesCount","messageId":"UAD1671","message":"Provide the number of parking space
11s.","ruleLogic":"If (CarStorageType = \\"Driveway\\" or \\"SharedDriveway\\", and TenOrMoreParkingSpacesIndicator = \\"false\\") or (CarStorageType = \\"Carport\\" or \\"CommonCarport\\" or \\"Garage\\" or \\"OpenLot\\" or \\"Other\\" or \\"ParkingGarage\\"), and ParkingSpacesCount is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"{No Subsection}","reportLabel":"Number of Parking Spaces","dataPointName":"ParkingSpacesCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"3200.0011","dataElement":"TenOrMoreParkingSpacesIndicator","messageId":"UAD1672","message":"Indicate whether the 'Driveway' or 'Shared Driveway' has ten or more parking spaces.","ruleLogic":"If CarStorageType = \\"Driveway\\" or \\"SharedDriveway\\", and TenOrMoreParkingSpacesIndicator is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"{No Subsection}","reportLabel":"Number of Parking Spaces","dataPointName":"TenOrMoreParkingSpacesIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"3200.0012","dataElement":"ProjectParkingSpaceAssignmentType","messageId":"UAD1673","message":"Provide the parking space assignment for 'Common Carport', 'Open Lot', or 'Parking Garage'.","ruleLogic":"If CarStorageType = \\"CommonCarport\\" or \\"OpenLot\\" or \\"ParkingGarage\\", and ProjectParkingSpaceAssignmentType is not provided in a given instance of CAR_STORAGE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"{No Subsection}","reportLabel":"Number of Parking Spaces","dataPointName":"ProjectParkingSpaceAssignmentType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/CAR_STORAGE_DETAIL/","relatedValues":"CarStorageType (%RV1%)"},{"uniqueId":"3200.0021","dataElement":"VehicleStorageDefectsExistIndicator","messageId":"UAD1675","message":"Indicate whether any vehicle storage has defects.","ruleLogic":"If CarStorageType <> \\"None\\" and VehicleStorageDefectsExistIndicator is not provided","severity":"Fatal","propertyAffected":"Subject","reportSection":"Vehicle Storage","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"{No Label}","dataPointName":"VehicleStorageDefectsExistIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"3300.0002","dataElement":"SketchExistsIndicator","messageId":"UAD1676","message":"Indicate whether a sketch or floor plan has been included in the appraisal.","ruleLogic":"If SketchExistsIndicator is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Sketch","reportSubsection":"{No Subsection}","reportLabel":"{No Label}","dataPointName":"SketchExistsIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},{"uniqueId":"3300.0007","dataElement":"MeasurementStandardPublisherType","messageId":"UAD1677","message":"Provide the 'Measurement Standard' (i.e., ANSI, AMS) used for the appraisal.","ruleLogic":"If SketchExistsIndicator = \\"true\\" and MeasurementStandardPublisherType is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Sketch","reportSubsection":"{No Subsection}","reportLabel":"Measurement Standard","dataPointName":"MeasurementStandardPublisherType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},{"uniqueId":"3300.0008","dataElement":"MeasurementStandardPublisherTypeOtherDescription","messageId":"UAD1678","message":"Provide a description when 'Measurement Standard' = 'Other'.","ruleLogic":"If MeasurementStandardPublisherType = \\"Other\\" and MeasurementStandardPublisherTypeOtherDescription is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Sketch","reportSubsection":"{No Subsection}","reportLabel":"Measurement Standard","dataPointName":"MeasurementStandardPublisherTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},{"uniqueId":"3600.0002","dataElement":"FunctionalIssueType","messageId":"UAD1680","message":"The type of functional issue must be included. Select 'None' if there are no functional issues.","ruleLogic":"If at least one instance of FUNCTIONAL_ISSUE is not provided or FunctionalIssueType is not provided in a given instance of FUNCTIONAL_ISSUE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Functional Obsolescence","reportSubsection":"{No Subsection}","reportLabel":"Functional Issues","dataPointName":"FunctionalIssueType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/FUNCTIONAL_ISSUES/FUNCTIONAL_ISSUE/"},{"uniqueId":"3600.0003","dataElement":"FunctionalIssueTypeOtherDescription","messageId":"UAD1681","message":"Provide a description when 'Functional Issues' = 'Other'.","ruleLogic":"If FunctionalIssueType = \\"Other\\" and FunctionalIssueTypeOtherDescription is not provided in a given instance of FUNCTIONAL_ISSUE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Functional Obsolescence","reportSubsection":"{No Subsection}","reportLabel":"Functional Issues","dataPointName":"FunctionalIssueTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/FUNCTIONAL_ISSUES/FUNCTIONAL_ISSUE/"},{"uniqueId":"3700.0002","dataElement":"DisasterMitigationFeatureType","messageId":"UAD1683","message":"The type of disaster mitigation feature must be included. Select 'None' if there are no disaster mitigation features.","ruleLogic":"If at least one instance of DISASTER_MITIGATION_FEATURE is not provided or DisasterMitigationFeatureType is not provided in a given instance of DISASTER_MITIGATION_FEATURE","
11severity":"Fatal","propertyAffected":"Subject","reportSection":"Disaster Mitigation","reportSubsection":"{No Subsection}","reportLabel":"Mitigation Feature","dataPointName":"DisasterMitigationFeatureType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/DISASTER_MITIGATION_FEATURES/DISASTER_MITIGATION_FEATURE/"},{"uniqueId":"3700.0003","dataElement":"DisasterMitigationFeatureTypeOtherDescription","messageId":"UAD1684","message":"Provide a description when 'Mitigation Feature' = 'Other'.","ruleLogic":"If DisasterMitigationFeatureType = \\"Other\\" and DisasterMitigationFeatureTypeOtherDescription is not provided in a given instance of DISASTER_MITIGATION_FEATURE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Disaster Mitigation","reportSubsection":"{No Subsection}","reportLabel":"Mitigation Feature","dataPointName":"DisasterMitigationFeatureTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/DISASTER_MITIGATION_FEATURES/DISASTER_MITIGATION_FEATURE/"},{"uniqueId":"3900.0033","dataElement":"@xlink:arcrole","messageId":"UAD1685","message":"Provide at least one defect when the Appraiser identified a defect, damage or deficiency with one or more amenities. In the UAD XML, a minimum of one RELATIONSHIP must be included linking each DEFECT to the AMENITY that has the defect. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and SubjectPropertyAmenitiesDefectsExistIndicator = \\"true\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DEFECT_ContainsDefectOf_AMENITY\\" linking DEFECT to the AMENITY","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"3900.0091","dataElement":"@xlink:arcrole","messageId":"UAD1686","message":"Provide at least one defect when the Appraiser identified a defect, damage or deficiency with one or more vehicle storages. In the UAD XML, a minimum of one RELATIONSHIP must be included linking each DEFECT to the CAR_STORAGE that has the defect. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and VehicleStorageDefectsExistIndicator = \\"true\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DEFECT_ContainsDefectOf_CAR_STORAGE\\" linking DEFECT to CAR_STORAGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"3900.0097","dataElement":"DwellingExteriorDefectsExistIndicator","messageId":"UAD1687","message":"Indicate whether any defects, damages, or deficiencies are observed on the exterior of the dwelling.","ruleLogic":"If DwellingExteriorDefectsExistIndicator is not provided in a given instance of IMPROVEMENT_DETAIL where ImprovementType = \\"Dwelling\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Dwelling Exterior","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"{No Label}","dataPointName":"DwellingExteriorDefectsExistIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},{"uniqueId":"3900.0107","dataElement":"UnitInteriorDefectsExistIndicator","messageId":"UAD1688","message":"Indicate whether the living unit has any defects, damages, or deficiencies.","ruleLogic":"If (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and UnitInteriorDefectsExistIndicator is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"{No Label}","dataPointName":"UnitInteriorDefectsExistIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/"},{"uniqueId":"3900.0145","dataElement":"@xlink:arcrole","messageId":"UAD1689","message":"Provide at least one defect when the Appraiser identified a defect, damage or deficiency with the dwelling exterior. In the UAD XML, a minimum of one RELATIONSHIP must be included linking DEFECT to IMPROVEMENT (ImprovementType = 'Dwelling'). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and DwellingExteriorDefectsExistIndicator = \\"true\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DEFECT_ContainsDefectOf_IMPROVEMENT\\" that links DEFECT to the given instance of IMPROVEMENT with ImprovementType = 'Dwelling'","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"3900.0148","dataElement":"@xlink:arcrole","messageId":"UAD1690","message":"Provide at least one defect when the Appraiser identified a defect, damage or deficiency with the site. In the UAD XML, a minimum of one RELATIONSHIP must be included linking DEFECT to SITE. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and SiteDefectsExistIndicator = \\"true\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DEFECT_ContainsDefectOf_SITE\\" linking DEFECT to SITE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"3900.0154","dataElement":"@xlink:arcrole","messageId":"UAD1691","message":"Provide at least one defect when the Appraiser identified a defect, damage or deficiency in the interior of the living unit or the ADU. In the UAD XML, a minimum of one RELATIONSHIP must be included linking DEFECT to the PROPERTY_UNIT that has the defect. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and UnitInteriorDefectsExistIndicator = \\"true\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DEFECT_ContainsDefectOf_PROPERTY_UNIT\\" linking DEFECT to the given instance of PROPERTY_UNIT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"3900.0192","dataElement":"@xlink:arcrole","messageId":"UAD1692","message":"Provide at least one defect when the Appraiser identified a defect, damage or deficiency in the outbuilding. In the UAD XML, a minimum of one RELATIONSHIP must be included linking DEFECT to IMPROVEMENT (ImprovementType = 'Outbuilding'). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SubjectProperty\\" and OutbuildingDefectsExistIndicator = \\"true\\", and there is no instance of RELATIONSHIP with @xlink:arcrole = \\"urn:fdc:mismo.org:2009:residential/DEFECT_ContainsDefectOf_IMPROVEMENT\\" linking DEFECT to IMPROVEMENT with ImprovementType = 'Outbuilding'","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"0300.0063","dataElement":"LivingUnitCount","messageId":"UAD1693","message":"The number of 'Accessory Dwelling Units' plus the number of 'Units Excluding ADUs' must equal the total number of living units across all buildings.","ruleLogic":"If AccessoryDwellingUnitTotalCount plus\\r\\nLivingUnitExcludingADUCount does not equal the sum of LivingUnitCount across all instances of STRUCTURE_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"LivingUnitCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_DETAIL/"},{"uniqueId":"0700.0089","dataElement":"AccessoryDwellingUnitIndicator","messageId":"UAD1694","message":"Each dwelling must contain at least one living unit that is not an ADU.","ruleLogic":"For each instance of IMPROVEMENT_DETAIL with ImprovementType = \\"Dwelling\\", if there is no occurrences of PROPERTY_UNIT_DETAIL with AccessoryDwellingUnitIndicator = \\"false\\"","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"ADU","dataPointName":"AccessoryDwellingUnitIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","minValue":1},{"uniqueId":"0300.0039","dataElement":"EffectiveAgeYearsCount","messageId":"UAD1695","message":"Provide 'Effective Age' either as a number of years or as a range of years, but not both.","ruleLogic":"If CostApproachIndicator = \\"true\\" and ImprovementType = \\"Dwelling\\" and EffectiveAgeYearsCount is provided, and (either or both of Effe
11ctiveAgeRangeLowYearsCount or EffectiveAgeRangeHighYearsCount is provided) in a given instance of STRUCTURE_ANALYSIS_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Cost Approach","reportSubsection":"Depreciated Cost - Dwelling","reportLabel":"Effective Age","dataPointName":"EffectiveAgeYearsCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_ANALYSES/STRUCTURE_ANALYSIS/STRUCTURE_ANALYSIS_DETAIL/"},{"uniqueId":"0300.0039","dataElement":"EffectiveAgeYearsCount","messageId":"UAD1696","message":"Provide 'Effective Age' either as a number of years or as a range of years.","ruleLogic":"If CostApproachIndicator = \\"true\\" and ImprovementType = \\"Dwelling\\" and EffectiveAgeYearsCount is not provided, and (either EffectiveAgeRangeLowYearsCount or EffectiveAgeRangeHighYearsCount is not provided) in a given instance of STRUCTURE_ANALYSIS_DETAIL","severity":"Warning","propertyAffected":"Subject","reportSection":"Cost Approach","reportSubsection":"Depreciated Cost - Dwelling","reportLabel":"Effective Age","dataPointName":"EffectiveAgeYearsCount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/STRUCTURE_ANALYSES/STRUCTURE_ANALYSIS/STRUCTURE_ANALYSIS_DETAIL/"},{"uniqueId":"0800.0012","dataElement":"OwnershipTransferTransactionAmount","messageId":"UAD1698","message":"Provide either the amount related to the transfer of ownership of real property (typically the sale price), or the reason why the ownership transfer amount was not available.","ruleLogic":"If PriorSalesOrTransfersIndicator = \\"true\\" and ((OwnershipTransferTransactionAmount and OwnershipTransferAmountNotAvailableReasonType are not provided) or (OwnershipTransferTransactionAmount and OwnershipTransferAmountNotAvailableReasonType are provided))","severity":"Fatal","propertyAffected":"Subject","reportSection":"Prior Sale and Transfer History","reportSubsection":"Subject Transfer History","reportLabel":"Amount","dataPointName":"OwnershipTransferTransactionAmount","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","relatedValues":"OwnershipTransferTransactionType (%RV1%)"},{"uniqueId":"1000.0019","dataElement":"LastName","messageId":"UAD1699","message":"Provide the property 'Seller Name'.","ruleLogic":"If neither FullName nor LastName is provided for PartyRoleType = \\"PropertySeller\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Seller Name","dataPointName":"LastName","xpath":"../SERVICE/PARTIES/PARTY/INDIVIDUAL/NAME/; ../SERVICE/PARTIES/PARTY/LEGAL_ENTITY/LEGAL_ENTITY_DETAIL/"},{"uniqueId":"1000.0023","dataElement":"LastName","messageId":"UAD1700","message":"Provide the name of the 'Current Owner of Public Record'.","ruleLogic":"If neither FullName nor LastName is provided for PartyRoleType = \\"PropertyOwner\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Current Owner of Public Record","dataPointName":"LastName","xpath":"../SERVICE/PARTIES/PARTY/INDIVIDUAL/NAME/; ../SERVICE/PARTIES/PARTY/LEGAL_ENTITY/LEGAL_ENTITY_DETAIL/"},{"uniqueId":"1000.0102","dataElement":"LastName","messageId":"UAD1701","message":"Provide 'Borrower Name'.","ruleLogic":"If neither FullName nor LastName is provided for PartyRoleType = \\"Borrower\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"{No Subsection}","reportLabel":"Borrower Name","dataPointName":"LastName","xpath":"../SERVICE/PARTIES/PARTY/INDIVIDUAL/NAME/; ../SERVICE/PARTIES/PARTY/LEGAL_ENTITY/LEGAL_ENTITY_DETAIL/"},{"uniqueId":"","dataElement":"SALES_HISTORY","messageId":"UAD1702","message":"Only the most recent sale should be delivered. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"LandComparable\\" and there is more than one instance of SALES_HISTORY","severity":"Warning","propertyAffected":"Land Comparable #n","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"Sale Date","dataPointName":"SALES_HISTORY","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","maxValue":1},{"uniqueId":"","dataElement":"SALES_HISTORY","messageId":"UAD1703","message":"Only the most recent sale should be delivered. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"GrossRentMultiplierComparable\\" and there is more than one instance of SALES_HISTORY","severity":"Warning","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"Sale Date","dataPointName":"SALES_HISTORY","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","maxValue":1},{"uniqueId":"","dataElement":"SALES_HISTORY","messageId":"UAD1704","message":"Only the most recent sale should be delivered. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"PropertyAnalyzedNotUsed\\" and there is more than one instance of SALES_HISTORY","severity":"Warning","propertyAffected":"Property Analyzed Not Used #n","reportSection":"Sales Comparison Approach","reportSubsection":"Additional Properties Analyzed Not Used","reportLabel":"Sale Date","dataPointName":"SALES_HISTORY","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","maxValue":1},{"uniqueId":"","dataElement":"ImageFileLocationIdentifier","messageId":"UAD1705","message":"Provide the file name and location of the image within the .zip f
11ile (e.g., \\\\\\\\Images\\\\MH1_DwellingFront.png). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ImageFileLocationIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageFileLocationIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/","relatedValues":"ImageCategoryType (%RV1%)"},{"uniqueId":"","dataElement":"MIMETypeIdentifier","messageId":"UAD1707","message":"Provide the format of the image file. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If MIMETypeIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MIMETypeIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/","relatedValues":"ImageCategoryType (%RV1%)"},{"uniqueId":"1400.0901","dataElement":"MIMETypeIdentifier","messageId":"UAD1708","message":"Provide the format of the image file. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and MIMETypeIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"MIMETypeIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/IMAGES/IMAGE/","relatedValues":"ImageCategoryType (%RV1%)"},{"uniqueId":"","dataElement":"DefectItemAffectsSoundnessStructuralIntegrityIndicator","messageId":"UAD1710","message":"Indicate whether the defect, damage, or deficiency affects the soundness and / or structural integrity of the improvement.","ruleLogic":"If DefectItemAffectsSoundnessStructuralIntegrityIndicator is not provided in a given instance of DEFECT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"Affects Soundness or Structural Integrity","dataPointName":"DefectItemAffectsSoundnessStructuralIntegrityIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DEFECT/DEFECTS/DEFECT/DEFECT_DETAIL/","relatedValues":"DefectComponentLabelType (%RV1%)"},{"uniqueId":"","dataElement":"DefectItemDescription","messageId":"UAD1711","message":"Provide a description of the defect, damage or deficiency.","ruleLogic":"If DefectItemDescription is not provided in a given instance of DEFECT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"Description","dataPointName":"DefectItemDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DEFECT/DEFECTS/DEFECT/DEFECT_DETAIL/","relatedValues":"DefectComponentLabelType (%RV1%)"},{"uniqueId":"","dataElement":"DefectItemLocationType","messageId":"UAD1712","message":"Provide the location of the defect, damage or deficiency.","ruleLogic":"If DefectItemLocationType is not provided in a given instance of DEFECT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"Location","dataPointName":"DefectItemLocationType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DEFECT/DEFECTS/DEFECT/DEFECT_DETAIL/","relatedValues":"DefectComponentLabelType (%RV1%)"},{"uniqueId":"","dataElement":"DefectItemLocationTypeOtherDescription","messageId":"UAD1713","message":"Provide a description when the location of the defect, damage or deficiency = 'Other'.","ruleLogic":"If DefectItemLocationType = \\"Other\\" and DefectItemLocationTypeOtherDescription is not provided in a given instance of DEFECT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"Location","dataPointName":"DefectItemLocationTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DEFECT/DEFECTS/DEFECT/DEFECT_DETAIL/","relatedValues":"DefectComponentLabelType (%RV1%)"},{"uniqueId":"","dataElement":"DefectItemRecommendedActionType","messageId":"UAD1714","message":"Provide the recommended action for the identified defect, damage or deficiency.","ruleLogic":"If DefectItemRecommendedActionType is not provided in a given instance of DEFECT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"Recommended Action","dataPointName":"DefectItemRecommendedActionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DEFECT/DEFECTS/DEFECT/DEFECT_DETAIL/","relatedValues":"DefectComponentLabelType (%RV1%)"},{"uniqueId":"","dataElement":"DefectComponentLabelType","messageId":"UAD1715","message":"Provide the feature where the defect, damage or deficiency has been observed.","ruleLogic":"If DefectComponentLabelType is not provided in a given instance of DEFECT_DETAIL that is not associated with AMENTIY or 
11CAR_STORAGE","severity":"Warning","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"Feature","dataPointName":"DefectComponentLabelType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DEFECT/DEFECTS/DEFECT/DEFECT_DETAIL/"},{"uniqueId":"","dataElement":"DefectComponentLabelTypeOtherDescription","messageId":"UAD1716","message":"Provide a description when label of the defect, damage or deficiency = 'Other'.","ruleLogic":"If DefectComponentLabelType = \\"Other\\" and DefectComponentLabelTypeOtherDescription is not provided in a given instance of DEFECT_DETAIL","severity":"Fatal","propertyAffected":"Subject","reportSection":"(unspecified)","reportSubsection":"Apparent Defects, Damages, Deficiencies","reportLabel":"Feature","dataPointName":"DefectComponentLabelTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DEFECT/DEFECTS/DEFECT/DEFECT_DETAIL/"},{"uniqueId":"","dataElement":"RELATIONSHIP","messageId":"UAD1717","message":"One or more duplicate RELATIONSHIP containers exist. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If the 'xlink:arcrole', 'xlink:from', and 'xlink:to' labels are not unique across all instances of RELATIONSHIP","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"RELATIONSHIP","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"","dataElement":"xlink:from","messageId":"UAD1718","message":"The 'from' label included in a RELATIONSHIP container is missing from the associated container. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If the associated container does not have the xlink:from label specified in a given instance of RELATIONSHIP","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"Does Not Display","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/","relatedValues":"xlink:arcrole (%RV1%); xlink:from (%RV2%)"},{"uniqueId":"","dataElement":"xlink:to","messageId":"UAD1719","message":"The 'to' label included in a RELATIONSHIP container is missing from the associated container or data element. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If the associated container or data element does not have the xlink:to label specified in a given instance of RELATIONSHIP","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"Does Not Display","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/","relatedValues":"xlink:arcrole (%RV1%); xlink:to (%RV2%)"},{"uniqueId":"","dataElement":"DepreciationTotalAmount","messageId":"UAD1720","message":"Provide depreciation amount as summary, represented by 'Total Depreciation' or all three forms of depreciation ('Physical Depreciation', 'Functional Depreciation' and 'External Depreciation'), even if the value is 0.","ruleLogic":"If CostApproachIndicator = \\"true\\" and DepreciationTotalAmount is not provided, and (DepreciationExternalAmount or DepreciationFunctionalAmount or DepreciationPhysicalAmount are not provided) in a given instance of IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION","severity":"Fatal","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"{No Subsection}","reportLabel":"Total Depreciation","dataPointName":"DepreciationTotalAmount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/IMPROVEMENT_COST_AND_DEPRECIATED_VALUES/IMPROVEMENT_COST_AND_DEPRECIATED_VALUE/IMPROVEMENT_DEPRECIATION/"},{"uniqueId":"0500.0016","dataElement":"ManufacturedHomeManufactureDate","messageId":"UAD1721","message":"The 'Date of Manufacture' must include year, month and day.","ruleLogic":"If ManufacturedHomeManufactureDate does not include year, month and day in YYYY-MM-DD format","severity":"Fatal","propertyAffected":"Subject","reportSection":"Manufactured Home","reportSubsection":"HUD Data Plate","reportLabel":"Date of Manufacture (%PV%)","dataPointName":"ManufacturedHomeManufactureDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"2400.0056","dataElement":"PartyRoleType","messageId":"UAD1722","message":"More than one Appraiser has been identified in the appraisal. There can be only one Appraiser, the other has to be Supervisory Appraiser.","ruleLogic":"If more than one instance of ROLE_DETAIL has PartyRoleType = \\"Appraiser\\" across all instances of PARTY","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Appraiser","dataPointName":"PartyRoleType","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/ROLE_DETAIL/"},{"uniqueId":"2400.0080; 2400.0502","dataElement":"InspectionDate","messageId":"UAD1723","message":"The 'Inspection Date' must include year, month and day.","ruleLogic":"If InspectionDate does not include year, month and day (YYYY-MM-DD format)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Inspection Date (%PV%)","dataPointName":"InspectionDate (%PV%)","xpath":"../VALUATION_ANALYSES/VALUATION_ANALYSIS/PROPERTIES/PROPERTY/INSPECTIONS/INSPECTION/INSPECTION_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"0900.0012","dataElement":"ListingStartDate","messageId":"UAD1725","message":"The listing 'Start Date' must include year, month and day.","ruleLogic":"If ListingStartDate does not include year, month and day (YYYY-MM-DD format)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Listing Information","reportSubsection":"{No Subsection}","reportLabel":"Start Date (%PV%)","dataPointName":"ListingStartDate (%PV%)","xpath":"../VALUATION_ANALYSES/VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"0900.0010","dataElement":"ListingEndDate","messageId":"UAD1726","message":"The listing 'End Date' must include year, month and day.","ruleLogic":"If ListingEndDate does not include year, month and day (YYYY-MM-DD format)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Subject Listing Information","reportSubsection":"{No Subsection}","reportLabel":"End Date (%PV%)","dataPointName":"ListingEndDate (%PV%)","xpath":"../VALUATION_ANALYSES/VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LISTING_INFORMATIONS/LISTING_INFORMATION/LISTING_INFORMATION_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"2500.0084","dataElement":"TaxAbatementsOrExemptionsExpirationDate","messageId":"UAD1727","message":"The expiration date for the tax abatements or exemptions must include year and month (YYYY-MM format).","ruleLogic":"If TaxAbatementsOrExemptionsExpirationDate does not include year and month (YYYY-MM format)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Project Factors and Impact to Value / Marketability","reportLabel":"Detail (%PV%)","dataPointName":"TaxAbatementsOrExemptionsExpirationDate (%PV%)","xpath":"../VALUATION_ANALYSES/VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_TAXES/PROPERTY_TAX/PROPERTY_TAX_EXEMPTIONS/PROPERTY_TAX_EXEMPTION/","dateFormat":"CCYY-MM"},{"uniqueId":"0600.0009","dataElement":"SalesContractDate","messageId":"UAD1728","message":"The 'Contract Date' must include year, month and day.","ruleLogic":"If SalesContractDate does not include year, month and day (YYYY-MM-DD format)","severity":"Fatal","propertyAffected":"Subject","reportSection":"Sales Contract","reportSubsection":"{No Subsection}","reportLabel":"Contract Date (%PV%)","dataPointName":"SalesContractDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"0700.0089","dataElement":"AccessoryDwellingUnitIndicator","messageId":"UAD1730","message":"There is an indicator of a living unit in an outbuilding, and it was not identified as an ADU. Any living unit in an outbuilding is considered an ADU, or it would have to be identified as a dwelling.","ruleLogic":"If AccessoryDwellingUnitIndicator = \\"false\\" for a given instance of PROPERTY_UNIT_DETAIL in IMPROVEMENT with ImprovementType = \\"Outbuilding\\"","severity":"Warning","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"ADU","dataPointName":"AccessoryDwellingUnitIndicator","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/","relatedValues":"OutbuildingType (%RV1%)"},{"uniqueId":"1800.0202","dataElement":"SalesContractDate","messageId":"UAD1731","message":"Provide the date the sales contract was fully executed.","ruleLogic":"IF @ValuationUseType = \\"SalesComparable\\" AND ContractDateUnknownIndicator = \\"false\\", and SalesContractDate is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Contract Date","dataPointName":"SalesContractDate","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_CONTRACTS/SALES_CONTRACT/SALES_CONTRACT_DETAIL/"},{"uniqueId":"1300.0010","dataElement":"PropertyValuationConditionalConclusionType","messageId":"UAD1732","message":"At least one defect, damage, or deficiency must be provided when the appraisal 'Market Value Condition' is 'Subject to Inspection'.","ruleLogic":"If PropertyValuationConditionalConclusionType = \\"SubjectToInspection\\" and there are no instances of DEFECT_DETAIL with DefectItemRecommendedActionType = \\"Inspection\\"","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Market Value Condition","dataPointName":"PropertyValuationConditionalConclusionType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_CONDITIONS/VALUATION_CONDITION/"},{"uniqueId":"1300.0013","dataElement":"MarketingOrExposureDaysCount","messageId":"UAD1733","message":"Provide 'Reasonable Exposure Time' as a number of days or as a range of days, but not both.","ruleLogic":"If MarketingOrExposureDaysCount is provided, and (either or both of MarketingOrExposureLowRangeDaysCount or MarketingOrExposureHighRangeDaysCount is provided)","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Reasonable Exposure Time","dataPointName":"MarketingOrExposureDaysCount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/"},{"uniqueId":"1800.0209","dataElement":"OwnershipTransferTransactionType","messageId":"UAD1734","message":"Provide the ownership transfer transaction type (i.e., sale, deed transfer only).","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and PriorSalesOrTransfersIndicator = \\"true\\", and (at least one instance of SALES_HISTORY is not provided or OwnershipTransferTransactionType is not provided in a given instance of SALES_HISTORY)","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Prior Sale and Transfer History","reportSubsection":"Comparable Transfer History","reportLabel":"Transfer Terms","dataPointName":"OwnershipTransferTransactionType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/"},{"uniqueId":"1800.0207; 1800.0342","dataElement":"OwnershipTransferDate","messageId":"UAD1735","message":"Provide the ownership transfer date.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and OwnershipTransferDate is not provided in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach; Prior Sale and Transfer History","reportSubsection":"General Information;
11 Comparable Transfer History","reportLabel":"Sale Date; Date","dataPointName":"OwnershipTransferDate","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","relatedValues":"OwnershipTransferTransactionType (%RV1%)"},{"uniqueId":"1400.0742","dataElement":"ImageFileLocationIdentifier","messageId":"UAD1736","message":"Provide the file name and location of the image within the .zip file (e.g., \\\\\\\\Images\\\\MH1_Garage.png). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ImageFileLocationIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageFileLocationIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/CAR_STORAGES/CAR_STORAGE/IMAGES/IMAGE/","relatedValues":"Vehicle Storage"},{"uniqueId":"1400.0778","dataElement":"ImageFileLocationIdentifier","messageId":"UAD1737","message":"Provide the file name and location of the image within the .zip file (e.g., \\\\\\\\Images\\\\MH1_Flooring.png). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ImageFileLocationIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageFileLocationIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/INTERIOR_COMPONENTS/INTERIOR_COMPONENT/IMAGES/IMAGE/","relatedValues":"Interior Feature"},{"uniqueId":"1400.0784","dataElement":"ImageFileLocationIdentifier","messageId":"UAD1738","message":"Provide the file name and location of the image within the .zip file (e.g., \\\\\\\\Images\\\\MH1_Bedroom1.png). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ImageFileLocationIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageFileLocationIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/ROOMS/ROOM/IMAGES/IMAGE/","relatedValues":"Room"},{"uniqueId":"1400.0748","dataElement":"ImageFileLocationIdentifier","messageId":"UAD1739","message":"Provide the file name and location of the image within the .zip file (e.g., \\\\\\\\Images\\\\MH1_Deck.png). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ImageFileLocationIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageFileLocationIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_AMENITY/AMENITY_CATEGORIES/AMENITY_CATEGORY/AMENITIES/AMENITY/IMAGES/IMAGE/","relatedValues":"Amenity"},{"uniqueId":"","dataElement":"ImageFileLocationIdentifier","messageId":"UAD1740","message":"Provide the file name and location of the image within the .zip file (e.g., \\\\\\\\Images\\\\MH1_ExteriorTrimDDD.png). For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If ImageFileLocationIdentifier is not provided in a given instance of IMAGE","severity":"Fatal","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ImageFileLocationIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DEFECT/DEFECTS/DEFECT/IMAGES/IMAGE/","relatedValues":"Defect"},{"uniqueId":"2500.0023","dataElement":"CooperativeProprietaryLeaseExpirationDate","messageId":"UAD1741","message":"The cooperative proprietary lease expiration date must include year and month (YYYY-MM format).","ruleLogic":"If CooperativeProprietaryLeaseExpirationDate is not provided in YYYY-MM format.","severity":"Fatal","propertyAffected":"Subject","reportSection":"Project Information","reportSubsection":"Cooperative Information","reportLabel":"Proprietary Lease Expires (%PV%)","dataPointName":"CooperativeProprietaryLeaseExpirationDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/","dateFormat":"CCYY-MM"},{"uniqueId":"0100.0015","dataElement":"LatitudeIdentifier","messageId":"UAD1742","message":"The latitude must be a value between -90 and 90 with at least 5 digits of precision to the right of the decimal point. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If LatitudeIdentifier is not provided between -90 and 90 with at least 5 digits of precision to the right of the decimal point","severity":"Warning","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LatitudeIdentifier (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LOCATION_IDENTIFIER/GEOSPATIAL_INFORMATION/","minValue":-90,"maxValue":90},{"uniqueId":"0100.0016","dataElement":"LongitudeIdentifier","messageId":"UAD1743","message":"The longitude must be a value between -180 and 180 with at least 5 digits of precision to the right of the decimal point. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If LongitudeIdentifier is not provided between -180 and 180 with at least 5 digits of precision to the right of the decimal point","severity":"Warning","propertyAffected":"Subject","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LongitudeIdentifier (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LOCATION_IDENTIFIER/GEOSPATIAL_INFORMATION/","minValue":-180,"maxValue":180},{"uniqueId":"1800.0342; 1800.0207","dataElement":"OwnershipTransferDate","messageId":"UAD1744","message":"The prior sale or transfer date for the sales comparable must include year, month and day.","ruleLogic":"If OwnershipTransferDate does not include year, month and day (YYYY-MM-DD format) in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach; Prior Sale and Transfer History","reportSubsection":"General Information;
11 Comparable Transfer History","reportLabel":"Sale Date; Date (%PV%)","dataPointName":"OwnershipTransferDate (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"1200.0034","dataElement":"OwnershipTransferTransactionAmount","messageId":"UAD1745","message":"The amount related to the transfer of ownership of real property (typically the sale price) must be greater than or equal to $0.","ruleLogic":"If OwnershipTransferTransactionAmount < 0 in SALES_HISTORY","severity":"Fatal","propertyAffected":"Gross Rent Multiplier Comparable #n","reportSection":"Income Approach","reportSubsection":"Gross Rent Multiplier Comparables","reportLabel":"Sale Price (%PV%)","dataPointName":"OwnershipTransferTransactionAmount (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","minValue":0},{"uniqueId":"1300.0013","dataElement":"MarketingOrExposureDaysCount","messageId":"UAD1746","message":"Provide 'Reasonable Exposure Time' as a number of days or as a range of days.","ruleLogic":"If MarketingOrExposureDaysCount is not provided, and (either MarketingOrExposureLowRangeDaysCount or MarketingOrExposureHighRangeDaysCount is not provided)","severity":"Fatal","propertyAffected":"N/A","reportSection":"Reconciliation","reportSubsection":"Appraisal Summary","reportLabel":"Reasonable Exposure Time","dataPointName":"MarketingOrExposureDaysCount","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_RECONCILIATION/VALUATION_RECONCILIATION_SUMMARY/VALUATION_RECONCILIATION_SUMMARY_DETAIL/"},{"uniqueId":"2400.0492; 1400.0348","dataElement":"@xlink:arcrole","messageId":"UAD1747","message":"The exterior inspection method, interior inspection method, and inspection date must be associated with the party that performed the inspection. In the UAD XML, one instance of RELATIONSHIP must be included for each Appraiser and/or Supervisory Appraiser that links INSPECTION to ROLE. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If PartyRoleType = \\"Appraiser\\" or \\"AppraiserSupervisor\\" and there is no instance of RELATIONSHIP provided for each role that links INSPECTION to the associated ROLE.","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Subject Property Ins
11pection","dataPointName":"@xlink:arcrole","xpath":"../SERVICE/RELATIONSHIPS/RELATIONSHIP/"},{"uniqueId":"1800.0190","dataElement":"LatitudeIdentifier","messageId":"UAD1748","message":"The latitude must be a value between -90 and 90 with at least 5 digits of precision to the right of the decimal point. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LatitudeIdentifier is not provided between -90 and 90 with at least 5 digits of precision to the right of the decimal point","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LatitudeIdentifier (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LOCATION_IDENTIFIER/GEOSPATIAL_INFORMATION/","minValue":-90,"maxValue":90},{"uniqueId":"1800.0191","dataElement":"LongitudeIdentifier","messageId":"UAD1749","message":"The longitude must be a value between -180 and 180 with at least 5 digits of precision to the right of the decimal point. For assistance with this message, contact the appraisal software vendor.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and LongitudeIdentifier is not provided between -180 and 180 with at least 5 digits of precision to the right of the decimal point","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"LongitudeIdentifier (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/LOCATION_IDENTIFIER/GEOSPATIAL_INFORMATION/","minValue":-180,"maxValue":180},{"uniqueId":"4000.0004","dataElement":"ReconsiderationOfValueIndicator","messageId":"UAD1750","message":"Indicate whether a reconsideration of value has been requested.","ruleLogic":"If ReconsiderationOfValueIndicator is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display","dataPointName":"ReconsiderationOfValueIndicator","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},{"uniqueId":"4000.0005","dataElement":"ReconsiderationOfValueCommentDescription","messageId":"UAD1751","message":"Provide the commentary on the outcome of the reconsideration of value.","ruleLogic":"If ReconsiderationOfValueIndicator = \\"true\\" and ReconsiderationOfValueCommentDescription is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Revision History","reportSubsection":"Reconsideration of Value","reportLabel":"Reconsideration of Value Commentary","dataPointName":"ReconsiderationOfValueCommentDescription","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/RECONSIDERATIONS_OF_VALUE/RECONSIDERATION_OF_VALUE/"},{"uniqueId":"4000.0006","dataElement":"ReconsiderationOfValueRequestedByType","messageId":"UAD1752","message":"Provide the party that initiated the request for reconsideration of value.","ruleLogic":"If ReconsiderationOfValueIndicator = \\"true\\" and ReconsiderationOfValueRequestedByType is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Revision History","reportSubsection":"Reconsideration of Value","reportLabel":"Type","dataPointName":"ReconsiderationOfValueRequestedByType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/RECONSIDERATIONS_OF_VALUE/RECONSIDERATION_OF_VALUE/"},{"uniqueId":"4000.0008","dataElement":"ReconsiderationOfValueResultType","messageId":"UAD1753","message":"Indicate whether the reconsideration of value request resulted in a change to the Opinion of Market Value.","ruleLogic":"If ReconsiderationOfValueIndicator = \\"true\\" and ReconsiderationOfValueResultType is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Revision History","reportSubsection":"Reconsideration of Value","reportLabel":"Result","dataPointName":"ReconsiderationOfValueResultType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/RECONSIDERATIONS_OF_VALUE/RECONSIDERATION_OF_VALUE/"},{"uniqueId":"4000.0007","dataElement":"ReconsiderationOfValueResultDate","messageId":"UAD1754","message":"Provide the date the appraiser completed the reconsideration of value.","ruleLogic":"If ReconsiderationOfValueIndicator = \\"true\\" and ReconsiderationOfValueResultDate is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Revision History","reportSubsection":"Reconsideration of Value","reportLabel":"Date","dataPointName":"ReconsiderationOfValueResultDate","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/RECONSIDERATIONS_OF_VALUE/RECONSIDERATION_OF_VALUE/"},{"uniqueId":"4000.0007","dataElement":"ReconsiderationOfValueResultDate","messageId":"UAD1755","message":"The reconsideration of value date must include year, month and day.","ruleLogic":"If ReconsiderationOfValueResultDate does not include year, month and day YYYY-MM-DD format","severity":"Fatal","propertyAffected":"N/A","reportSection":"Revision History","reportSubsection":"Reconsideration of Value","reportLabel":"Date (%PV%)","dataPointName":"ReconsiderationOfValueResultDate (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/RECONSIDERATIONS_OF_VALUE/RECONSIDERATION_OF_VALUE/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"4000.0007","dataElement":"ReconsiderationOfValueResultDate","messageId":"UAD1756","message":"The reconsideration of value date must be on or after the 'Effective Date of Appraisal'.","ruleLogic":"If ReconsiderationOfValueResultDate < AppraisalReportEffectiveDate","severity":"Warning","propertyAffected":"N/A","reportSection":"Revision History","reportSubsection":"Reconsideration of Value","reportLabel":"Date (%PV%)","dataPointName":"ReconsiderationOfValueResultDate (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/RECONSIDERATIONS_OF_VALUE/RECONSIDERATION_OF_VALUE/","relatedValues":"AppraisalReportEffectiveDate (%RV1%)"},{"uniqueId":"4000.0007","dataElement":"ReconsiderationOfValueResultDate","messageId":"UAD1757","message":"The reconsideration of value date cannot be more than a year old.","ruleLogic":"If ReconsiderationOfValueResultDate is more than 367 days before the current date","severity":"Warning","propertyAffected":"N/A","reportSection":"Revision History","reportSubsection":"Reconsideration of Value","reportLabel":"Date (%PV%)","dataPointName":"ReconsiderationOfValueResultDate (%PV%)","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/RECONSIDERATIONS_OF_VALUE/RECONSIDERATION_OF_VALUE/","dateFormat":"CCYY-MM-DD"},{"uniqueId":"1800.0318","dataElement":"ComparableAdjustmentType","messageId":"UAD1758","message":"Only one line-item adjustment is allowed for this Adjustment Type.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and there is more than one instance of COMPARABLE_ADJUSTMENT with the same ComparableAdjustmentType enumeration that should only be adju
11sted once (e.g., View). Please refer to the Adjustments Cardinality tab for the list of adjustments that can be applied only once.","severity":"Warning","propertyAffected":"Sales Comparable #n","reportSection":"Does Not Display","reportSubsection":"Does Not Display","reportLabel":"Does Not Display (Comparable Adjustment Type (%PV%))","dataPointName":"ComparableAdjustmentType (%PV%)","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/COMPARABLE/COMPARABLE_ADJUSTMENTS/COMPARABLE_ADJUSTMENT/"},{"uniqueId":"2200.0085","dataElement":"PartyRoleType","messageId":"UAD1759","message":"More than one Supervisory Appraiser has been identified in the appraisal. There can be only one Supervisory Appraiser.","ruleLogic":"If more than one instance of ROLE_DETAIL has PartyRoleType = \\"AppraiserSupervisor\\" across all instances of PARTY","severity":"Fatal","propertyAffected":"N/A","reportSection":"Assignment Information","reportSubsection":"Contact Information","reportLabel":"Supervisory Appraiser","dataPointName":"PartyRoleType","xpath":"../SERVICE/PARTIES/PARTY/ROLES/ROLE/ROLE_DETAIL/"},{"uniqueId":"1800.0278","dataElement":"SalesComparisonCommentDescription","messageId":"UAD1760","message":"Provide 'Reconciliation of Sales Comparison Approach' when sales comparison approach is included in the appraisal.","ruleLogic":"If SalesComparisonApproachIndicator = \\"true\\" and SalesComparisonCommentDescription is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Sales Comparison Approach","reportSubsection":"Reconciliation of Sales Comparison Approach","reportLabel":"{No Label}","dataPointName":"SalesComparisonCommentDescription","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/SALES_COMPARISON_APPROACH/SALES_COMPARISON_APPROACH_DETAIL/"},{"uniqueId":"1100.0023","dataElement":"CostAnalysisCommentDescription","messageId":"UAD1761","message":"Provide 'Cost Approach Commentary' when cost approach is included in the appraisal.","ruleLogic":"If CostApproachIndicator = \\"true\\" and CostAnalysisCommentDescription is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Cost Approach","reportSubsection":"Cost Approach Commentary","reportLabel":"{No Label}","dataPointName":"CostAnalysisCommentDescription","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/COST_APPROACH/COST_APPROACH_DETAIL/"},{"uniqueId":"1200.0007","dataElement":"IncomeAnalysisCommentDescription","messageId":"UAD1762","message":"Provide 'Income Approach Commentary' when income approach is included in the appraisal.","ruleLogic":"If IncomeApproachIndicator = \\"true\\" and IncomeAnalysisCommentDescription is not provided","severity":"Fatal","propertyAffected":"N/A","reportSection":"Income Approach","reportSubsection":"Income Approach Commentary","reportLabel":"{No Label}","dataPointName":"IncomeAnalysisCommentDescription","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/APPROACH_TO_VALUE/INCOME_APPROACH/INCOME_APPROACH_DETAIL/"},{"uniqueId":"2000.0048; 2000.0047","dataElement":"ValuationAnalysisCategoryType","messageId":"UAD1763","message":"Provide 'Rental Analysis Commentary' when rent schedule is included in the appraisal.","ruleLogic":"If RentScheduleIndicator = \\"true\\" and there is no instance of VALUATION_COMMENTARY with ValuationAnalysisCategoryType = \\"ComparableRental\\" and ValuationCommentText","severity":"Fatal","propertyAffected":"N/A","reportSection":"Rental Information","reportSubsection":"Rental Analysis Commentary","reportLabel":"{No Label}","dataPointName":"ValuationAnalysisCategoryType","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/"},{"uniqueId":"","dataElement":"PROPERTY_UNIT","messageId":"UAD1764","message":"Each dwelling must contain at least one living unit.","ruleLogic":"If ImprovementType = ‘Dwelling’ and there are no instances of PROPERTY_UNIT","severity":"Fatal","propertyAffected":"Subject","reportSection":"Unit Interior","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"PROPERTY_UNIT","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/"},{"uniqueId":"1500.0186; 1500.0189","dataElement":"ValuationCommentText","messageId":"UAD1765","message":"The commentary provided for the specified field exceeds the allowable limit of 140 characters.","ruleLogic":"If ValuationAnalysisCategoryType = (\\"HazardZones\\" or \\"PropertyNonResidentialUses\\") and ValuationCommentText length exceeds 140 characters","severity":"Fatal","propertyAffected":"N/A","reportSection":"Site","reportSubsection":"Site Features and Impact to Value / Marketability","reportLabel":"Comment","dataPointName":"ValuationCommentText","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/","relatedValues":"ValuationAnalysisCategoryType (%RV1%)"},{"uniqueId":"","dataElement":"ValuationCommentText","messageId":"UAD1766","message":"The commentary provided for the specified field exceeds the allowable limit of 210 characters.","ruleLogic":"If ValuationAnalysisCategoryType = (\\"ProjectDeveloperOrSponsorControlsProjectManagement\\" or \\"IncompleteProject\\" or \\"ProjectConversion\\" or \\"SingleEntityGreatestNumberOfUnitsOwned\\" or \\"SingleEntityGreatestNumberOfSharesOwned\\" or \\"ProjectCommercialSpace\\" or \\"ProjectLegalAction\\" or \\"ProjectSpecialAssessmentsAttributedToSubjectProperty\\" or \\"TransferFeeAttributedToSubjectProperty\\" or \\"PropertyTaxAbatementsOrExemptions\\") and ValuationCommentText length exceeds 210 characters","severity":"Fatal","propertyAffected":"N/A","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"ValuationCommentText","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/","relatedValues":"ValuationAnalysisCategoryType (%RV1%)"},{"uniqueId":"0100.0050","dataElement":"ValuationCommentText","messageId":"UAD1767","message":"The commentary provided for the specified field exceeds the allowable limit of 540 characters.","ruleLogic":"If ValuationAnalysisCategoryType = \\"PropertySpecialTaxAssessments\\" and ValuationCommentText length exceeds 540 characters","severity":"Fatal","propertyAffected":"N/A","reportSection":"Subject Property","reportSubsection":"{No Subsection}","reportLabel":"Description of Special Tax Assessments and Impact to Value / Marketability","dataPointName":"ValuationCommentText","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/","relatedValues":"ValuationAnalysisCategoryType (%RV1%)"},{"uniqueId":"","dataElement":"ValuationCommentText","messageId":"UAD1768","message":"The commentary provided for the specified field exceeds the allowable limit of 2500 characters.","ruleLogic":"If ValuationAnalysisCategoryType = (\\"ProjectFactors\\" or \\"Project\\" or \\"WaterFrontages\\" or \\"SiteFeatures\\" or \\"SiteViews\\" or \\"SiteInfluences\\") and ValuationCommentText length exceeds 2500 characters","severity":"Fatal","propertyAffected":"N/A","reportSection":"(unspecified)","reportSubsection":"{No Subsection}","reportLabel":"","dataPointName":"ValuationCommentText","xpath":"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_COMMENTARIES/VALUATION_COMMENTARY/","relatedValues":"ValuationAnalysisCategoryType (%RV1%)"},{"uniqueId":"1800.0233","dataElement":"SiteInfluenceType","messageId":"UAD1769","message":"Provide 'Site Influence (Location)' for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (at least one instance of SITE_INFLUENCE_DETAIL is not provided or SiteInfluenceType is not provided in a given instance of SITE_INFLUENCE_DETAIL)","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Site Influence (Location)","dataPointName":"SiteInfluenceType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/SITE_INFLUENCE_DETAIL/"},{"uniqueId":"1800.0234","dataElement":"SiteInfluenceTypeOtherDescription","messageId":"UAD1770","message":"Provide a description when 'Site Influence (Location)' = 'Other'.","ruleLogic":"If SiteInfluenceType = \\"Other\\" and SiteInfluenceTypeOtherDescription is not provided in a given instance of SITE_INFLUENCE_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Site","reportLabel":"Site Influence (Location)","dataPointName":"SiteInfluenceTypeOtherDescription","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SITE/SITE_INFLUENCES/SITE_INFLUENCE/SITE_INFLUENCE_DETAIL/"},{"uniqueId":"1800.0274","dataElement":"SaleType","messageId":"UAD1771","message":"Provide the 'Transfer Terms' for the associated transaction.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and OwnershipTransferTransactionType = \\"Sale\\" and SaleType is not provided in a given instance of SALES_HISTORY","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Transfer Terms","dataPointName":"SaleType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/SALES_HISTORIES/SALES_HISTORY/","relatedValues":"OwnershipTransferDate (%RV1%)"},{"uniqueId":"1800.0154","dataElement":"FloorIdentifier","messageId":"UAD1772","message":"Provide 'Floor Number' for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and  ImprovementType = \\"Dwelling\\" and AttachmentType = \\"Attached\\" and StructuralDesignType = (\\"Lowrise\\" or \\"Highrise\\" or \\"Midrise\\"), and FloorIdentifier is not provided in a given instance of PROPERTY_UNIT_DETAIL","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Floor Number","dataPointName":"FloorIdentifier","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_DETAIL/"},{"uniqueId":"1800.0337","dataElement":"PropertyEstateType","messageId":"UAD1773","message":"Provide 'Property Rights Appraised' for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (PropertyInProjectIndicator = \\"false\\" or (PropertyInProjectIndicator = \\"true\\" and ProjectLegalStructureType = \\"Condominium\\")), and PropertyEstateType is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"General Information","reportLabel":"Property Rights Appraised","dataPointName":"PropertyEstateType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/PROPERTY_DETAIL/"},{"uniqueId":"1800.0171","dataElement":"ConstructionMethodType","messageId":"UAD1774","message":"Provide 'Construction Method' (e.g., Site Built, Manufactured, Modular) for each dwelling of the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ((ImprovementType = \\"Dwelling\\" and AttachmentType = \\"Detached\\") or (ImprovementType = \\"Dwelling\\" and AttachmentType = \\"Attached\\" and StructuralDesignType = \\"RowhouseTownhouse\\" or \\"SemiDetached\\" or \\"Other\\")), and (at least one instance of CONSTRUCTION_METHOD is not provided or ConstructionMethodType is not provided in a given instance of CONSTRUCTION_METHOD)","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Construction Method","dataPointName":"ConstructionMethodType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/STRUCTURE/CONSTRUCTION_METHODS/CONSTRUCTION_METHOD/"},{"uniqueId":"1800.0379","dataElement":"ManufacturedHomeWidthType","messageId":"UAD1775","message":"Provide the 'Manufactured Home Width' (i.e., Single Wide, Multi Wide) for the sales comparable.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ImprovementType = \\"Dwelling\\" and ConstructionMethodType = \\"Manufactured\\" and ManufacturedHomeWidthType is not provided","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Dwelling(s)","reportLabel":"Manufactured Home Width","dataPointName":"ManufacturedHomeWidthType","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/MANUFACTURED_HOME/MANUFACTURED_HOME_DETAIL/"},{"uniqueId":"1800.0394","dataElement":"UnitBelowGradeUnfinishedAreaMeasure","messageId":"UAD1776","message":"Provide the 'Unfinished Area Below Grade' for the sales comparable, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and (ImprovementType = \\"Dwelling\\" or (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\")), and UnitBelowGradeUnfinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Unfinished Area Below Grade","dataPointName":"UnitBelowGradeUnfinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/","relatedValues":"ImprovementType (%RV1%)"},{"uniqueId":"1800.0399","dataElement":"UnitNonStandardBelowGradeFinis
11hedAreaMeasure","messageId":"UAD1777","message":"Provide the 'Finished Area Below Grade (Nonstandard)' for the sales comparable, even if the value is 0.","ruleLogic":"If @ValuationUseType = \\"SalesComparable\\" and ((ImprovementType = \\"Dwelling\\" and UnitNonStandardBelowGradeFinishedAreaMeasure > 0 for @ValuationUseType = \\"SubjectProperty\\") \\r\\nor (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\" and UnitNonStandardBelowGradeFinishedAreaMeasure > 0 for @ValuationUseType = \\"SubjectProperty\\")), and UnitNonStandardBelowGradeFinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Finished Area Below Grade (Nonstandard)","dataPointName":"UnitNonStandardBelowGradeFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/"},{"uniqueId":"1800.0392","dataElement":"UnitAboveGradeUnfinishedAreaMeasure","messageId":"UAD1778","message":"Provide the 'Unfinished Area Above Grade' for the sales comparable, even if the value is 0.","ruleLogic":"IF @ValuationUseType = \\"SalesComparable\\" and ((ImprovementType = \\"Dwelling\\" and UnitAboveGradeUnfinishedAreaMeasure > 0 for @ValuationUseType = \\"SubjectProperty\\") \\r\\nor (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\" and UnitAboveGradeUnfinishedAreaMeasure > 0 for @ValuationUseType = \\"SubjectProperty\\")), and UnitAboveGradeUnfinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Unfinished Area Above Grade","dataPointName":"UnitAboveGradeUnfinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/"},{"uniqueId":"1800.0391","dataElement":"UnitNonStandardAboveGradeFinishedAreaMeasure","messageId":"UAD1779","message":"Provide the 'Finished Area Above Grade (Nonstandard)' for the sales comparable, even if the value is 0.","ruleLogic":"IF @ValuationUseType = \\"SalesComparable\\" and ((ImprovementType = \\"Dwelling\\" and UnitNonStandardAboveGradeFinishedAreaMeasure > 0 for @ValuationUseType = \\"SubjectProperty\\") \\r\\nor (ImprovementType = \\"Outbuilding\\" and OutbuildingRealPropertyIndicator = \\"true\\" and AccessoryDwellingUnitIndicator = \\"true\\" and UnitNonStandardAboveGradeFinishedAreaMeasure > 0 for @ValuationUseType = \\"SubjectProperty\\")), and UnitNonStandardAboveGradeFinishedAreaMeasure is not provided in a given instance of PROPERTY_UNIT_AREA","severity":"Fatal","propertyAffected":"Sales Comparable #n","reportSection":"Sales Comparison Approach","reportSubsection":"Unit(s)","reportLabel":"Finished Area Above Grade (Nonstandard)","dataPointName":"UnitNonStandardAboveGradeFinishedAreaMeasure","xpath":"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/PROPERTY_UNITS/PROPERTY_UNIT/PROPERTY_UNIT_AREA/"}]`),Q6={rules:K6},Z6=JSON.parse('{"AboutVersionIdentifier":["urar","raur","cr"],"AccessType":["urar"],"AccessibilityFeatureType":["urar"],"AccessibilityFeatureTypeOtherDescription":["urar"],"AccessibilityModificationDescription":["urar"],"AccessibleForObservationIndicator":["urar"],"AccessoryDwellingUnitIndicator":["urar"],"AccessoryDwellingUnitLegallyRentableIndicator":["urar"],"AccessoryDwellingUnitTotalCount":["urar"],"AccessoryDwellingUnitTypicalToMarketIndicator":["urar"],"ActualRentPerUnitFinishedAreaAmount":["urar"],"AdditionalClientRequestedConditionsCommentDescription":["urar"],"AdditionalClientRequestedConditionsIndicator":["urar"],"AdditionalComparisonLineItemDescription":["urar"],"AdditionalComparisonLineItemIdentifier":["urar"],"AdditionalOpinionOfValueAmount":["urar"],"AdditionalPropertyAnalyzedNotUsedText":["urar"],"AdditionalRentalIncomeType":["urar"],"AdditionalRentalIncomeTypeOtherDescription":["urar"],"AdditionalValuationIdentifier":["urar","raur","cr"],"AdditionalValuationIdentifierType":["urar","raur","cr"],"AddressLineText":["urar","raur","cr"],"AddressUnitDesignatorType":["urar","raur","cr"],"AddressUnitIdentifier":["urar","raur","cr"],"AdjustedSalesPriceAmount":["urar"],"AdjustedSalesPricePerBedroomAmount":["urar"],"AdjustedSalesPricePerUnitAmount":["urar"],"AgencyAppraiserIdentifier":["urar","raur","cr"],"AgencyAppraiserIdentifierType":["urar","raur","cr"],"AllPropertyRightsAppraisedIndicator":["urar"],"AllowableLiveWorkSpaceIndicator":["urar"],"AllowableWorkSpaceAreaMeasure":["urar"],"AltitudeElevationLinearMeasure":["urar","raur","cr"],"AmenitiesComparisonType":["urar"],"AmenityAreaMeasure":["urar"],"AmenityAttachedToManufacturedHomeIndicator":["urar"],"AmenityCategoryType":["urar"],"AmenityCount":["urar"],"AmenityMaterialType":["urar"],"AmenityMaterialTypeOtherDescription":["urar"],"AmenityOwnershipType":["urar"],"AmenityOwnershipTypeOtherDescription":["urar"],"AmenityType":["urar"],"AmenityTypeOtherDescription":["urar"],"AmortizationType":["urar"],"AmortizationTypeOtherDescription":["urar"],"AppraisalCompletionCommentText":["cr"],"AppraisalConditionsSatisfiedVerificationDescription":["cr"],"AppraisalReportEffectiveDate":["urar"],"AppraisalSubCommitteeAppraiserIdentifier":["urar","raur","cr"],"AppraisalUpd
11ateCommentDescription":["raur"],"AppraisalUpdateReportEffectiveDate":["raur"],"AppraisedIndicator":["urar"],"AppraiserAdditionalCertificationIndicator":["urar","raur","cr"],"AppraiserCompanyName":["urar","raur","cr"],"AppraiserDesignationType":["urar","raur","cr"],"AppraiserDesignationTypeOtherDescription":["urar","raur","cr"],"AppraiserEmploymentType":["urar","raur","cr"],"AppraiserFileIdentifier":["urar","raur","cr"],"AppraiserLicenseType":["urar","raur","cr"],"AppraiserLicenseTypeOtherDescription":["urar","raur","cr"],"AppraiserPriorServicesPerformedDescription":["urar","raur"],"AppraiserPriorServicesPerformedIndicator":["urar","raur"],"AppraiserSupervisorAdditionalCertificationIndicator":["urar","raur","cr"],"ApproximateCeilingHeightType":["urar"],"ArchitecturalDesignCategoryType":["urar"],"ArchitecturalDesignCategoryTypeOtherDescription":["urar"],"ArmsLengthIndicator":["urar"],"AssociationChargeAmount":["urar"],"AssociationChargeBalanceAmount":["urar"],"AssociationChargeIncludesUtilityType":["urar"],"AssociationChargeIncludesUtilityTypeOtherDescription":["urar"],"AssociationChargePeriodType":["urar"],"AssociationChargeType":["urar"],"AssociationSpecialAssessmentStatusType":["urar"],"AttachmentType":["urar"],"AtticExistsIndicator":["urar"],"BalloonIndicator":["urar"],"BedroomCount":["urar"],"BelowGradeExteriorAccessType":["urar"],"BelowGradeExteriorAccessTypeOtherDescription":["urar"],"BodyOfWaterDescription":["urar"],"BodyOfWaterName":["urar"],"BodyOfWaterProximityType":["urar"],"BodyOfWaterType":["urar"],"BodyOfWaterTypeOtherDescription":["urar"],"BroadbandInternetAvailableIndicator":["urar"],"CarStorageAreaMeasure":["urar"],"CarStorageAttachmentType":["urar"],"CarStorageType":["urar"],"CarStorageTypeOtherDescription":["urar"],"CarStoragesComparisonType":["urar"],"CeilingStyleType":["urar"],"CeilingStyleTypeOtherDescription":["urar"],"CityName":["urar","raur","cr"],"CommunityLandTrustIndicator":["urar"],"ComparableAdjustmentAmount":["urar"],"ComparableAdjustmentType":["urar"],"ComparableToSubjectDirectionType":["urar"],"ComparableWeightType":["urar"],"CompletionReportNewDefectIndicator":["cr"],"ConsiderationRequestedIndicator":["urar"],"ConstructionMethodType":["urar"],"ConstructionMethodTypeOtherDescription":["urar"],"ConstructionStatusType":["urar"],"ContractAmountUnknownIndicator":["urar"],"ContractDateUnknownIndicator":["urar"],"ConvertedAreaExistsIndicator":["urar"],"ConvertedAreaFinishComparisonType":["urar"],"ConvertedAreaOriginalUseType":["urar"],"ConvertedAreaOriginalUseTypeOtherDescription":["urar"],"CoolingSystemExistsIndicator":["urar"],"CoolingSystemType":["urar"],"CoolingSystemTypeOtherDescription":["urar"],"CooperativeProprietaryLeaseExpirationDate":["urar"],"CoreHeatingSystemBelowGradeIndicator":["urar"],"CornerUnitIndicator":["urar"],"CostAnalysisCommentDescription":["urar"],"CostAnalysisType":["urar"],"CostApproachIndicator":["urar"],"CostMethodType":["urar"],"CostMethodTypeOtherDescription":["urar"],"CostToRepairType":["urar"],"CountyName":["urar","raur","cr"],"CumulativeDaysOnMarketCount":["urar"],"CurrentInterestRatePercent":["urar"],"DataSourceEffectiveDate":["urar"],"DataSourceIdentifier":["urar"],"DataSourceName":["urar"],"DataSourceQualityRatingCode":["urar"],"DataSourceType":["urar"],"DataSourceTypeOtherDescription":["urar"],"DaysOnMarketCount":["urar"],"DefectComponentLabelType":["urar","cr"],"DefectComponentLabelTypeOtherDescription":["urar","cr"],"DefectCostToRepairTotalAmount":["urar"],"DefectItemAffectsSoundnessStructuralIntegrityIndicator":["urar","cr"],"DefectItemDescription":["urar","cr"],"DefectItemEstimatedCostToRepairAmount":["urar"],"DefectItemLocationType":["urar","cr"],"DefectItemLocationTypeOtherDescription":["urar","cr"],"DefectItemRecommendedActionCompletedIndicator":["cr"],"DefectItemRecommendedActionCompletionDescription":["cr"],"DefectItemRecommendedActionInspectionDate":["cr"],"DefectItemRecommendedActionType":["urar","cr"],"DepreciatedCostDwellingsTotalAmount":["urar"],"DepreciatedCostOutbuildingsTotalAmount":["urar"],"DepreciationExternalAmount":["urar"],"DepreciationExternalPercent":["urar"],"DepreciationFunctionalAmount":["urar"],"DepreciationFunctionalPercent":["urar"],"DepreciationMethodType":["urar"],"DepreciationMethodTypeOtherDescription":["urar"],"DepreciationPhysicalAmount":["urar"],"DepreciationPhysicalPercent":["urar"],"DepreciationTotalAmount":["urar"],"DisasterMitigationFeatureType":["urar"],"DisasterMitigationFeatureTypeOtherDescription":["urar"],"DistanceFromPropertyLinearMeasure":["urar"],"DocumentFormIssuingEntityNameType":["urar","raur","cr"],"DocumentFormIssuingEntityVersionIdentifier":["urar","raur","cr"],"DocumentType":["urar","raur","cr"],"DwellingCount":["urar"],"DwellingExteriorDefectsExistIndicator":["urar"],"EasementDescription":["urar"],"EasementType":["urar"],"EasementTypeOtherDescription":["urar"],"EffectiveAgeDescription":["urar"],"EffectiveAgeRangeHighYearsCount":["urar"],"EffectiveAgeRangeLowYearsCount":["urar"],"EffectiveAgeYearsCount":["urar"],"EfficiencyRatingExistsIndicator":["urar"],"EfficiencyRatingName":["urar"],"EfficiencyRatingOrganizationName":["urar"],"EfficiencyRatingScoreValue":["urar"],"Ele
11ctricitySourceType":["urar"],"ElectricitySourceTypeOtherDescription":["urar"],"EncroachmentDescription":["urar"],"EncroachmentDirectionType":["urar"],"EncroachmentType":["urar"],"EncroachmentTypeOtherDescription":["urar"],"EncumbranceType":["urar"],"EnergyEfficientAndGreenDescription":["urar"],"EnvironmentalConditionIdentifiedDescription":["urar"],"EnvironmentalConditionProximityType":["urar"],"EnvironmentalConditionType":["urar"],"EnvironmentalConditionTypeOtherDescription":["urar"],"EstimatedRemainingEconomicLifeDescription":["urar"],"EstimatedRemainingEconomicLifeYearsCount":["urar"],"ExecutionDate":["urar","raur","cr"],"ExteriorConditionRatingCode":["urar"],"ExteriorQualityRatingCode":["urar"],"FHA_REOInsurabilityLevelCode":["urar"],"FactoryBuiltCertificationExaminedIndicator":["urar"],"FeeType":["urar","raur","cr"],"FinalListPriceAmount":["urar"],"FinancialRentalConcessionIndicator":["urar"],"FinanciallyFeasibleIndicator":["urar"],"FirstName":["urar","raur","cr"],"FloorIdentifier":["urar"],"FlooringType":["urar"],"FlooringTypeOtherDescription":["urar"],"FoundationMaterialType":["urar"],"FoundationMaterialTypeOtherDescription":["urar"],"FoundationType":["urar"],"FoundationTypeOtherDescription":["urar"],"FrontDoorApproximateElevationRangeType":["urar"],"FullBathroomCount":["urar"],"FullName":["urar","raur","cr"],"FunctionalIssueDescription":["urar"],"FunctionalIssueType":["urar"],"FunctionalIssueTypeOtherDescription":["urar"],"GovernmentAgencyAppraisalIndicator":["urar","raur","cr"],"GovernmentAgencyAppraisalType":["urar","raur","cr"],"GradeLevelType":["urar"],"GreenCertificationAssociationName":["urar"],"GreenCertificationExistsIndicator":["urar"],"GreenCertificationLevelAwardedYear":["urar"],"GreenCertificationLevelName":["urar"],"GreenCertificationName":["urar"],"GreenCertificationVersionIdentifier":["urar"],"GrossMonthlyRentMultiplierNumber":["urar"],"GrossRentMultiplierFactorNumber":["urar"],"HalfBathroomCount":["urar"],"HazardZoneType":["urar"],"HazardZoneTypeOtherDescription":["urar"],"HeatingFuelType":["urar"],"HeatingFuelTypeOtherDescription":["urar"],"HeatingSystemExistsIndicator":["urar"],"HeatingSystemType":["urar"],"HeatingSystemTypeOtherDescription":["urar"],"HomeownerResponsibleForExteriorMaintenanceIndicator":["urar"],"ImageCaptionCommentDescription":["urar","raur","cr"],"ImageCategoryType":["urar","raur","cr"],"ImageDatetime":["urar","raur","cr"],"ImageFileLocationIdentifier":["urar","raur","cr"],"ImprovedSurfaceMaterialType":["urar"],"ImprovedSurfaceMaterialTypeOtherDescription":["urar"],"ImprovementComponentConditionDescription":["urar"],"ImprovementComponentConditionStatusType":["urar"],"ImprovementComponentConditionSummaryDescription":["urar"],"ImprovementComponentQualityDescription":["urar"],"ImprovementComponentQualitySummaryDescription":["urar"],"ImprovementComponentType":["urar"],"ImprovementComponentTypeAdditionalDescription":["urar"],"ImprovementComponentTypeOtherDescription":["urar"],"ImprovementEstimatedTotalCostAmount":["urar"],"ImprovementInBoundaryOfEasementIndicator":["urar"],"ImprovementType":["urar"],"IncomeAnalysisCommentDescription":["urar"],"IncomeApproachIndicator":["urar"],"InfluenceMeetsPolicyRequirementsIndicator":["urar"],"InitialListPriceAmount":["urar"],"InspectionDate":["urar","raur","cr"],"InspectorFileIdentifier":["urar"],"InterestRateAvailableIndicator":["urar"],"InteriorConditionRatingCode":["urar"],"InteriorQualityRatingCode":["urar"],"InvestorRequestedIdentificationCode":["urar","raur","cr"],"LackOfHeatingSystemTypicalToMarketIndicator":["urar"],"LandOwnedInCommonIndicator":["urar"],"LastName":["urar","raur","cr"],"LatitudeIdentifier":["urar","raur","cr"],"LavaFlowZoneCode":["urar"],"LeaseStartDate":["urar"],"LegalActionIndicator":["urar"],"LegallyPermissibleIndicator":["urar"],"LevelCount":["urar"],"LevelFinishedAreaMeasure":["urar"],"LevelType":["urar"],"LevelUnfinishedAreaMeasure":["urar"],"LicenseExpirationDate":["urar","raur","cr"],"LicenseIdentifier":["urar","raur","cr"],"LicenseIssuingAuthorityStateCode":["urar","raur","cr"],"LienPriorityType":["urar"],"LineOfCreditDrawnAmount":["urar"],"LineOfCreditDrawnProRataShareAttributableToUnitAmount":["urar"],"LineOfCreditIndicator":["urar"],"LineOfCreditMaximumAmount":["urar"],"LineOfCreditMaximumProRataShareAttributableToUnitAmount":["urar"],"LineOfCreditProRataShareSelectionMethodType":["urar"],"ListedWithinPreviousYearIndicator":["urar"],"ListingEndDate":["urar"],"ListingIdentifier":["urar"],"ListingStartDate":["urar"],"ListingStatusType":["urar"],"ListingType":["urar"],"ListingTypeOtherDescription":["urar"],"LivingUnitCount":["urar"],"LivingUnitExcludingADUCount":["urar"],"LoanRemainingMaturityTermMonthsCount":["urar"],"LongitudeIdentifier":["urar","raur","cr"],"LotSizeAreaMeasure":["urar"],"MIMETypeIdentifier":["urar","raur","cr"],"MISMOReferenceModelIdentifier":["urar","raur","cr"],"ManufacturedHomeAttachedToFoundationIndicator":["urar"],"ManufacturedHomeFinancingProgramEligibilityIdentifier":["urar"],"ManufacturedHomeFinancingProgramEligibilityType":["urar"],"ManufacturedHomeFinancingProgramEligibilityTypeOtherDescription":["urar"],"ManufacturedHomeHUDCertificateLabelIndicator":["urar"],"ManufacturedHomeHUDCertificationLabelIdentifier":["urar"],"ManufacturedHomeHUDDataPlateAttachedIndicator":["urar"],"ManufacturedHomeHitchWheelsAxlesRemovedIndicator":["urar"],"ManufacturedHomeInstallationCostAmou
11nt":["urar"],"ManufacturedHomeInstalledDate":["urar"],"ManufacturedHomeInstalledDateEstimatedIndicator":["urar"],"ManufacturedHomeInvoiceNotReasonableDescription":["urar"],"ManufacturedHomeInvoiceReasonableIndicator":["urar"],"ManufacturedHomeInvoiceReviewedIndicator":["urar"],"ManufacturedHomeManufactureDate":["urar"],"ManufacturedHomeManufacturerName":["urar"],"ManufacturedHomeModificationIndicator":["urar"],"ManufacturedHomeModificationType":["urar"],"ManufacturedHomeModificationTypeOtherDescription":["urar"],"ManufacturedHomeModificationsDescription":["urar"],"ManufacturedHomeMovedAfterOriginalInstallationIndicator":["urar"],"ManufacturedHomePurchasedFromRetailerIndicator":["urar"],"ManufacturedHomeRetailerInvoiceReviewedIndicator":["urar"],"ManufacturedHomeRetailerName":["urar"],"ManufacturedHomeSerialNumberIdentifier":["urar"],"ManufacturedHomeValuationCommentText":["urar"],"ManufacturedHomeWidthType":["urar"],"MarketBoundariesDescription":["urar"],"MarketInventoryCount":["urar"],"MarketInventoryHighestPriceAmount":["urar"],"MarketInventoryLookbackMonthsCount":["urar"],"MarketInventoryLowestPriceAmount":["urar"],"MarketInventoryMedianDaysOnMarketCount":["urar"],"MarketInventoryMedianPriceAmount":["urar"],"MarketInventorySearchParameterDescription":["urar"],"MarketInventoryType":["urar"],"MarketSupplyTrendType":["urar"],"MarketTrendsForeclosureActivityIndicator":["urar"],"MarketingOrExposureDaysCount":["urar"],"MarketingOrExposureHighRangeDaysCount":["urar"],"MarketingOrExposureLowRangeDaysCount":["urar"],"MarketingOrExposureTimeType":["urar"],"MarketingTimeType":["urar"],"MaximallyProductiveIndicator":["urar"],"MeasurementStandardPublisherType":["urar"],"MeasurementStandardPublisherTypeOtherDescription":["urar"],"MechanicalSystemType":["urar"],"MechanicalSystemTypeOtherDescription":["urar"],"MiddleName":["urar","raur","cr"],"MineralRightsLeasedIndicator":["urar"],"MonthToMonthLeaseIndicator":["urar"],"MonthlyActualAdditionalIncomeAmount":["urar"],"MonthlyEstimatedAdditionalIncomeAmount":["urar"],"MortgageType":["urar"],"MortgageTypeOtherDescription":["urar"],"NativeAmericanLandsIndicator":["urar"],"NativeAmericanLandsType":["urar"],"NativeAmericanLandsTypeOtherDescription":["urar"],"NeighborhoodName":["urar"],"NewConstructionIndicator":["urar"],"NoFinancingTransactionIndicator":["urar"],"NonArmsLengthCommentText":["urar"],"NonContinuousFinishedAreaIndicator":["urar"],"NonResidentialModificationIndicator":["urar"],"NonResidentialUseDescription":["urar"],"NonResidentialUseType":["urar"],"NonResidentialUseTypeOtherDescription":["urar"],"ObjectURL":["urar","raur","cr"],"OpinionOfValueAmount":["urar"],"OriginalAppraisalEffectiveDate":["raur","cr"],"OriginalAppraisalMarketingOrExposureDaysCount":["raur"],"OriginalAppraisalMarketingOrExposureHighRangeDaysCount":["raur"],"OriginalAppraisalMarketingOrExposureLowRangeDaysCount":["raur"],"OriginalAppraisedValueAmount":["raur","cr"],"OriginalAppraiserFileIdentifier":["raur","cr"],"OriginalAppraiserUnparsedName":["raur","cr"],"OriginalLenderUnparsedName":["raur","cr"],"OutbuildingDefectsExistIndicator":["urar"],"OutbuildingRealPropertyIndicator":["urar"],"OutbuildingType":["urar"],"OutbuildingTypeOtherDescription":["urar"],"OverallBathroomsQualityDescription":["urar"],"OverallBathroomsUpdateStatusType":["urar"],"OverallConditionRatingCode":["urar"],"OverallFlooringUpdateStatusType":["urar"],"OverallQualityRatingCode":["urar"],"OwnershipTransferAmountNotAvailableReasonType":["urar"],"OwnershipTransferAmountNotAvailableReasonTypeOtherDescription":["urar"],"OwnershipTransferDate":["urar"],"OwnershipTransferFeeIndicator":["urar"],"OwnershipTransferTransactionAmount":["urar"],"OwnershipTransferTransactionType":["urar"],"PUDIndicator":["urar"],"ParcelAreaMeasure":["urar"],"ParcelCount":["urar"],"ParcelDescriptionClassificationType":["urar"],"ParcelDescriptionClassificationTypeOtherDescription":["urar"],"ParcelIdentificationType":["urar"],"ParcelIdentifier":["urar"],"ParcelIdentifierOwnerName":["urar"],"ParcelSeparatorType":["urar"],"ParcelSeparatorTypeOtherDescription":["urar"],"ParcelsContiguousIndicator":["urar"],"ParcelsLegalDescription":["urar","raur","cr"],"ParkingSpacesCount":["urar"],"PartyRoleType":["urar","raur","cr"],"PartyRoleTypeAdditionalDescription":["urar","raur"],"PartyRoleTypeOtherDescription":["urar","raur","cr"],"PaymentAmountAvailableIndicator":["urar"],"PaymentFrequencyType":["urar"],"PersonalInspectionPerformedIndicator":["cr"],"PersonalPropertyIncludedIndicator":["urar"],"PhysicallyPossibleIndicator":["urar"],"PostalCode":["urar","raur","cr"],"PricePerAreaAmount":["urar"],"PricePerTotalStandardAboveGradeFinis
11hedAreaAmount":["urar"],"PricePerUnitOfMeasureTypeForTotalFinishedAreaOfAllLivingUnitsIncludingADUAmount":["urar"],"PriceTrendsAnalysisDescription":["urar"],"PrimaryOccupationType":["urar"],"PrimaryOccupationTypeOtherDescription":["urar"],"PriorSalesOrTransfersIndicator":["urar"],"PrivateAccessIndicator":["urar"],"PrivateStreetMaintenanceAgreementExistIndicator":["urar"],"ProRataSharePercent":["urar"],"ProjectAnalysisGroundRentAmount":["urar"],"ProjectAnalysisGroundRentDescription":["urar"],"ProjectAnalysisGroundRentExpirationDate":["urar"],"ProjectAnalysisGroundRentIndicator":["urar"],"ProjectBlanketFinancingIndicator":["urar"],"ProjectCommercialSpaceIndicator":["urar"],"ProjectCommercialSpacePercent":["urar"],"ProjectCompletedIndicator":["urar"],"ProjectComponentCategoryType":["urar"],"ProjectComponentCategoryTypeOtherDescription":["urar"],"ProjectComponentCompletedIndicator":["urar"],"ProjectConditionAndQualityDescription":["urar"],"ProjectConversionIndicator":["urar"],"ProjectConversionOriginalUseType":["urar"],"ProjectConversionOriginalUseTypeOtherDescription":["urar"],"ProjectDeficiencyObservedIndicator":["urar"],"ProjectDeveloperOrSponsorControlsProjectManagementIndicator":["urar"],"ProjectDwellingUnitCount":["urar"],"ProjectDwellingUnitsForSaleCount":["urar"],"ProjectDwellingUnitsRentedCount":["urar"],"ProjectDwellingUnitsRentedEstimateDescription":["urar"],"ProjectDwellingUnitsRentedEstimateIndicator":["urar"],"ProjectDwellingUnitsSoldCount":["urar"],"ProjectLegalStructureType":["urar","raur"],"ProjectName":["urar"],"ProjectParkingSpaceAssignmentType":["urar"],"ProjectTotalSharesIssuedAndOutstandingCount":["urar"],"PropertyAccessDescription":["urar"],"PropertyAccessTypicalToMarketIndicator":["urar"],"PropertyAmenityExistsIndicator":["urar"],"PropertyAsIsConditionRatingCode":["urar"],"PropertyCooperativeSharesCount":["urar"],"PropertyDataReportIndicator":["urar"],"PropertyEstateType":["urar","raur"],"PropertyEstateTypeOtherDescription":["urar","raur"],"PropertyExteriorInspectionMethodType":["urar","raur","cr"],"PropertyGroundLeaseAnnualAmount":["urar"],"PropertyGroundLeaseExpirationDate":["urar"],"PropertyGroundLeaseRenewableIndicator":["urar"],"PropertyGroundLeaseTermYearsCount":["urar"],"PropertyGroundRentDescription":["urar"],"PropertyImprovementsCompletedIndicator":["cr"],"PropertyImprovementsCompletedPerPlansIndicator":["cr"],"PropertyInProjectIndicator":["urar","raur"],"PropertyInteriorInspectionMethodType":["urar","raur","cr"],"PropertyMarketValueDecreasedIndicator":["raur"],"PropertyMixedUsageIndicator":["urar"],"PropertyOrdinalNumber":["urar"],"PropertyPartialInterestType":["urar"],"PropertyPartialInterestTypeOtherDescription":["urar"],"PropertyPrimarilyResidentialUseIndicator":["urar"],"PropertyPrimaryEntryExitMethodType":["urar"],"PropertyPrimaryEntryExitMethodTypeOtherDescription":["urar"],"PropertyRentControlStatusType":["urar"],"PropertyRightsNotAppraisedDescription":["urar"],"PropertyStructureBuiltYear":["urar"],"PropertyStructureBuiltYearEstimatedIndicator":["urar"],"PropertyTaxAbatementsOrExemptionsIndicator":["urar"],"PropertyValuationConditionalConclusionType":["urar","cr"],"PropertyValuationMethodType":["urar"],"ProvidedServiceActualCostAmount":["urar","raur","cr"],"ProximityToSubjectDistanceLinearMeasure":["urar"],"PublicSewerUtilityAvailableNotConnectedIndicator":["urar"],"PublicWaterUtilityAvailableNotConnectedIndicator":["urar"],"ReasonPropertyNotUsedType":["urar"],"ReasonPropertyNotUsedTypeOtherDescription":["urar"],"ReconsiderationOfValueCommentDescription":["urar"],"ReconsiderationOfValueIndicator":["urar"],"ReconsiderationOfValueRequestedByType":["urar"],"ReconsiderationOfValueResultDate":["urar"],"ReconsiderationOfValueResultType":["urar"],"RenewableEnergyComponentExistsIndicator":["urar"],"RenewableEnergyComponentFinancedIndicator":["urar"],"RenewableEnergyComponentOwnershipType":["urar"],"RenewableEnergyComponentOwnershipTypeOtherDescription":["urar"],"RenewableEnergyComponentType":["urar"],"RenewableEnergyComponentTypeOtherDescription":["urar"],"RentControlDescription":["urar"],"RentControlStatusType":["urar"],"RentScheduleIndicator":["urar"],"RentalUnitAdjustedRentAmount":["urar"],"RentalUnitToSubjectComparisonType":["urar"],"ReplacementOrReproductionCostAmou
11nt":["urar"],"ReplacementOrReproductionCostAreaMeasure":["urar"],"ReplacementOrReproductionCostAreaType":["urar"],"ReplacementOrReproductionCostAreaTypeOtherDescription":["urar"],"ResidentialUsePercent":["urar"],"RestrictionDescription":["urar"],"RestrictionType":["urar"],"RestrictionTypeOtherDescription":["urar"],"RevisionCategoryType":["urar"],"RevisionDate":["urar"],"RevisionText":["urar"],"RoofEstimatedAgeRangeType":["urar"],"RoofLoadZoneCode":["urar"],"RoofMaterialType":["urar"],"RoofMaterialTypeOtherDescription":["urar"],"RoofObservableIndicator":["urar"],"RoomConditionAdditionalDescription":["urar"],"RoomConditionStatusType":["urar"],"RoomQualityDescription":["urar"],"RoomQualitySummaryDescription":["urar"],"RoomType":["urar"],"RoomTypeOtherDescription":["urar"],"RoomUpdateStatusType":["urar"],"RoomUpdatedTimeframeType":["urar"],"RowhouseTownhouseBackToBackIndicator":["urar"],"RowhouseTownhouseEndUnitIndicator":["urar"],"RowhouseTownhouseLocationType":["urar"],"RowhouseTownhouseStackedIndicator":["urar"],"SalePriceNetTotalAdjustmentAmount":["urar"],"SaleToListPriceRatioPercent":["urar"],"SaleType":["urar"],"SaleTypeOtherDescription":["urar"],"SalesComparisonApproachIndicator":["urar"],"SalesComparisonCommentDescription":["urar"],"SalesConcessionAmountKnownIndicator":["urar"],"SalesConcessionIndicator":["urar"],"SalesConcessionsTypicalToMarketIndicator":["urar"],"SalesContractAmount":["urar"],"SalesContractDate":["urar"],"SalesContractExistsIndicator":["urar"],"SalesContractReviewedIndicator":["urar"],"SameBuilderAsSubjectIndicator":["urar"],"SameProjectAsSubjectIndicator":["urar"],"SeparatePostalAddressIndicator":["urar"],"ServiceType":["urar","raur","cr"],"SewerSystemType":["urar"],"SewerSystemTypeOtherDescription":["urar"],"SingleEntityGreatestNumberOfSharesCount":["urar"],"SingleEntityGreatestNumberOfUnitsCount":["urar"],"SiteDefectsExistIndicator":["urar"],"SiteDimensionsDescription":["urar"],"SiteDrainageReasonType":["urar"],"SiteDrainageReasonTypeOtherDescription":["urar"],"SiteEstimatedValueAmount":["urar"],"SiteEstimatedValueCommentDescription":["urar"],"SiteFeatureDescription":["urar"],"SiteFeatureType":["urar"],"SiteFeatureTypeOtherDescription":["urar"],"SiteHighestBestUseIndicator":["urar"],"SiteImprovementAsIsCostAmount":["urar"],"SiteImprovementDescription":["urar"],"SiteInfluenceDescription":["urar"],"SiteInfluenceProximityType":["urar"],"SiteInfluenceType":["urar"],"SiteInfluenceTypeOtherDescription":["urar"],"SiteInfluencesComparisonType":["urar"],"SiteOtherImprovementsAsIsAmount":["urar"],"SiteUtilityDescription":["urar"],"SiteUtilityOwnershipType":["urar"],"SiteValuationMethodType":["urar"],"SiteValuationMethodTypeOtherDescription":["urar"],"SiteValueIndicator":["urar"],"SiteZoningClassificationDescription":["urar"],"SiteZoningClassificationIdentifier":["urar"],"SiteZoningComplianceDescription":["urar"],"SiteZoningComplianceIllegalReasonType":["urar"],"SiteZoningComplianceIllegalReasonTypeOtherDescription":["urar"],"SiteZoningComplianceType":["urar"],"SketchExistsIndicator":["urar"],"SkirtingExistsIndicator":["urar"],"SkirtingMaterialType":["urar"],"SkirtingMaterialTypeOtherDescription":["urar"],"SpecialAirportHazardZoneType":["urar"],"SpecialAirportHazardZoneTypeOtherDescription":["urar"],"SpecialTaxAssessmentsIndicator":["urar"],"StateCode":["urar","raur","cr"],"StoriesCount":["urar"],"StreetAccessType":["urar"],"StreetAccessTypeOtherDescription":["urar"],"StructuralDesignType":["urar"],"StructuralDesignTypeOtherDescription":["urar"],"StructureAreaMeasure":["urar"],"StructureExcludingVehicleStorageAndADUFinishedAreaMeasure":["urar"],"StructureExcludingVehicleStorageAndADUUnfinishedAreaMeasure":["urar"],"StructureIdentifier":["urar"],"StructureNonContinuousFinishedAreaMeasure":["urar"],"StructureValuationCommentText":["urar"],"StructureVolumeMeasure":["urar"],"SubjectBuildingCompletedIndicator":["urar"],"SubjectPropertyAmenitiesDefectsExistIndicator":["urar"],"SubjectToCompletionFeatureComparisonType":["cr"],"SubjectToCompletionFeatureDescription":["cr"],"SubjectToCompletionFeatureIncompleteOrInconsistentDescription":["cr"],"SubjectToCompletionFeatureLocationDescription":["cr"],"SuffixName":["urar","raur","cr"],"SwimmingPoolFeatureType":["urar"],"SwimmingPoolFeatureTypeOtherDescription":["urar"],"TaxAbatementsOrExemptionsAnnualAmount":["urar"],"TaxAbatementsOrExemptionsExpirationDate":["urar"],"TenOrMoreParkingSpacesIndicator":["urar"],"ThermalZoneCode":["urar"],"TopographyType":["urar"],"TopographyTypeOtherDescription":["urar"],"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure":["urar"],"TotalMonthlyActualAdditionalIncomeAmount":["urar"],"TotalMonthlyActualIncomeAmount":["urar"],"TotalMonthlyActualRentAmount":["urar"],"TotalMonthlyActualRentAmountEstimatedIndicator":["urar"],"TotalMonthlyEstimatedAdditionalIncomeAmount":["urar"],"TotalMonthlyEstimatedIncomeAmount":["urar"],"TotalMonthlyMarketRentAmount":["urar"],"TotalOfAllDwellingsVolumeMeasure":["urar"],"TotalPaymentAmount":["urar"],"TotalRoomCount":["urar"],"TotalSalesConcessionAmount":["urar"],"TotalWindowSurfaceAreaOfAllDwellingsAreaMeasure":["urar"],"UPBAmount":["urar"],"UPBProRataShareAttributableToUnitAmount":["urar"],"UnitAboveGradeUnfinishedAreaMeasure":["urar"],"UnitBelowGradeFinis
11hComparisonType":["urar"],"UnitBelowGradeUnfinishedAreaMeasure":["urar"],"UnitChargesIncludeUtilitiesIndicator":["urar"],"UnitFurnishedIndicator":["urar"],"UnitIdentifier":["urar"],"UnitIncludedInRentScheduleIndicator":["urar"],"UnitInteriorDefectsExistIndicator":["urar"],"UnitMixedUsageIndicator":["urar"],"UnitMonthlyActualRentAmount":["urar"],"UnitMonthlyMarketRentAmount":["urar"],"UnitNonStandardAboveGradeFinishedAreaMeasure":["urar"],"UnitNonStandardBelowGradeFinishedAreaMeasure":["urar"],"UnitOccupancyType":["urar"],"UnitRentedIndicator":["urar"],"UnitStandardAboveGradeFinishedAreaMeasure":["urar"],"UnitStandardBelowGradeFinishedAreaMeasure":["urar"],"UnitTotalFinishedAreaMeasure":["urar"],"UnitUtilitiesOperatingIndicator":["urar"],"UnitValuationCommentText":["urar"],"UtilitiesMeteredSeparatelyIndicator":["urar"],"UtilityMeetsDistanceRequirementIndicator":["urar"],"UtilitySharedIndicator":["urar"],"UtilityType":["urar"],"UtilityTypeOtherDescription":["urar"],"ValuationAdditionalCertificationIncludedByType":["urar","raur","cr"],"ValuationAdditionalCertificationText":["urar","raur","cr"],"ValuationAdditionalIntendedUserDescription":["urar","raur","cr"],"ValuationAdditionalIntendedUserIndicator":["urar","raur","cr"],"ValuationAdditionalScopeOfWorkIndicator":["urar","raur"],"ValuationAnalysisCategoryType":["urar","raur","cr"],"ValuationApproachExclusionReasonType":["urar"],"ValuationApproachExclusionReasonTypeOtherDescription":["urar"],"ValuationAssignmentType":["urar"],"ValuationAssignmentTypeOtherDescription":["urar"],"ValuationCommentText":["urar","raur","cr"],"ValuationIntendedUseDescription":["urar","raur","cr"],"ValuationReconciliationSummaryCommentDescription":["urar"],"ValuationReportContentIdentifier":["urar","raur","cr"],"ValuationReportInspectionCertificationType":["urar","raur"],"ValuationScopeOfWorkDescription":["urar","raur"],"ValuationSoftwareProductIdentifier":["urar","raur","cr"],"ValuationSoftwareProductName":["urar","raur","cr"],"ValuationSoftwareProductVersionIdentifier":["urar","raur","cr"],"ValuationSoftwareVendorName":["urar","raur","cr"],"ValuationUseType":["urar","raur","cr"],"ValueIndicatedByCostApproachAmount":["urar"],"ValueIndicatedByIncomeApproachAmount":["urar"],"ValueIndicatedBySalesComparisonAmount":["urar"],"ValueMarketabilityImpactType":["urar"],"VehicleStorageDefectsExistIndicator":["urar"],"ViewPrimaryIndicator":["urar"],"ViewRangeType":["urar"],"ViewRangeTypeOtherDescription":["urar"],"ViewType":["urar"],"ViewTypeOtherDescription":["urar"],"ViewsComparisonType":["urar"],"VisualObservationCompletedIndicator":["urar"],"WallMaterialType":["urar"],"WallMaterialTypeOtherDescription":["urar"],"WaterAccessDepthType":["urar"],"WaterAccessDepthTypeOtherDescription":["urar"],"WaterAccessRightType":["urar"],"WaterAccessRightTypeOtherDescription":["urar"],"WaterFrontageTotalLengthLinearMeasure":["urar"],"WaterSourceType":["urar"],"WaterSourceTypeOtherDescription":["urar"],"WaterWellType":["urar"],"WaterWellTypeOtherDescription":["urar"],"WaterfrontDevelopmentRightsIndicator":["urar"],"WaterfrontFeatureType":["urar"],"WaterfrontFeatureTypeOtherDescription":["urar"],"WindZoneCode":["urar"],"WindowSurfaceAreaMeasure":["urar"],"ZoningPermitRebuildToCurrentDensityIndicator":["urar"],"xlink:arcrole":["urar","raur","cr"],"xlink:from":["urar","raur","cr"],"xlink:label":["urar","raur","cr"],"xlink:to":["urar","raur","cr"]}'),J6={byFieldName:Z6},X6=J6.byFieldName;function eG(t,a){const s=X6[t];return s?s.includes(a):!0}const tG={"Subject Property":"subjectProperty","Subject Property Amenities":"subjectPropertyAmenities","Dwelling Exterior":"improvements","Unit Interior":"improvements",Outbuilding:"outbuildings","Cost Approach":"costApproach","Sales Comparison Approach":"salesComparisonGrid","Manufactured Home":"manufacturedHome","Sales Contract":"salesContract","Prior Sale and Transfer History":"priorSaleHistory","Subject Listing Information":"subjectListingInfo","Assignment Information":"reportIdentification","Income Approach":"incomeApproach",Reconciliation:"reconciliationValue",Site:"siteCharacteristics","Overall Quality and Condition":"improvements","Rental Information":"rentalInformation",Certifications:"certification","Project Information":"projectInformation","Energy Efficient and Green Features":"energyEfficiency",Market:"market","Highest and Best Use":"highestAndBestUse","Vehicle Storage":"garage",Sketch:"sketch","Fu
11nctional Obsolescence":"analysisApproaches","Disaster Mitigation":"additionalFeatures","Appraiser Info":"appraiserInfo","Report Identification":"reportIdentification","Revision History":"reportIdentification","Does Not Display":"metadata","(unspecified)":"metadata"};function Nh(t,a,s){const r=t[a];return!r||typeof r!="object"?null:r[s]?.value??null}function Dp(t){return tG[t]||"metadata"}function Dm(t,a){const s=t.containerInstances;if(!s)return[];const r=a.toUpperCase().replace(/IMRPOVEMENT/g,"IMPROVEMENT"),n=s[r];return Array.isArray(n)?n:[]}function dd(t,a){const s=t[a];return s?s.value??null:null}function mj(t){return t==null?!1:typeof t=="string"?t.trim().length>0:!0}function aG(t){return Array.from(t.matchAll(/"([^"]+)"/g)).map(a=>a[1])}const sG=[{pattern:/^If\s+ValuationAnalysisCategoryType\s*=\s*\(?\s*((?:"[^"]+"\s*(?:or\s*)?)+)\)?\s+and\s+ValuationCommentText\s+length\s+exceeds\s+(\d+)\s+characters/i,generator:t=>{const a=aG(t[1]),s=parseInt(t[2],10);return r=>{const n=Dm(r,"VALUATION_COMMENTARY");if(n.length===0)return!0;for(const i of n){const l=dd(i,"ValuationAnalysisCategoryType");if(l&&a.includes(l)){const c=dd(i,"ValuationCommentText");if(typeof c=="string"&&c.length>s)return!1}}return!0}}},{pattern:/^If\s+@?(\w+)\s*=\s*"([^"]+)"\s*,?\s+and\s+(\w+)\s+is\s+not\s+provided\s+(?:in\s+)+(?:a\s+given\s+|the\s+)?instances?\s+of\s+(\w+)/i,generator:t=>{const a=t[1],s=t[2],r=t[3],n=t[4];return i=>{const l=Dm(i,n);if(l.length===0)return!0;for(const c of l)if(dd(c,a)===s){const p=dd(c,r);if(!mj(p))return!1}return!0}}},{pattern:/^If\s+@?(\w+)\s+is\s+not\s+provided\s+(?:in\s+)+(?:a\s+given\s+|the\s+)?instances?\s+of\s+(\w+)/i,generator:t=>{const a=t[1],s=t[2];return r=>{const n=Dm(r,s);if(n.length===0)return!0;for(const i of n){const l=dd(i,a);if(!mj(l))return!1}return!0}}},{pattern:/^If\s+@?(\w+)\s+is\s+not\s+"([^"]+)"\s+(?:in\s+)+(?:a\s+given\s+|the\s+)?instances?\s+of\s+(\w+)/i,generator:t=>{const a=t[1],s=t[2],r=t[3];return n=>{const i=Dm(n,r);if(i.length===0)return!0;for(const l of i){const c=dd(l,a);if(mj(c)&&c!==s)return!1}return!0}}},{pattern:/^If\s+(\w+)\s+is\s+not\s+provided$/i,generator:(t,a)=>{const s=t[1],r=Dp(a.reportSection);return n=>{const i=Nh(n,r,s);return i==null?!1:typeof i=="string"?i.trim().length>0:!0}}},{pattern:/^If\s+(\w+)\s+is\s+not\s+in\s+the\s+required\s+format/i,generator:(t,a)=>{const s=t[1],r=Dp(a.reportSection);return n=>{const i=Nh(n,r,s);return i?s==="PostalCode"?/^\d{5}(-\d{4})?$/.test(i):s.includes("Date")?/^\d{4}-\d{2}-\d{2}$/.test(i)||/^\d{2}\/\d{2}\/\d{4}$/.test(i):!0:!0}}},{pattern:/^If\s+(\w+)\s+is\s+not\s+(a\s+)?valid/i,generator:(t,a)=>{const s=t[1],r=Dp(a.reportSection);return n=>{const i=Nh(n,r,s);return i&&s==="StateCode"?["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","DC","PR","VI","GU","AS","MP"].includes(i.toUpperCase()):!0}}},{pattern:/(\w+)\s+length\s+exceeds\s+(\d+)\s+characters/i,generator:(t,a)=>{const s=t[1],r=parseInt(t[2],10),n=Dp(a.reportSection);return i=>{const l=Nh(i,n,s);return typeof l!="string"?!0:l.length<=r}}},{pattern:/^If\s+(\w+)\s+is\s+(less|greater)\s+than\s+(\d+)/i,generator:(t,a)=>{const s=t[1],r=t[2].toLowerCase(),n=parseFloat(t[3]),i=Dp(a.reportSection);return l=>{const c=Nh(l,i,s);return c===null?!0:r==="less"?c>=n:c<=n}}},{pattern:/^If\s+(\w+)\s+is\s+not\s+in\s+the\s+valid\s+enumeration/i,generator:(t,a)=>{const s=t[1],r=Dp(a.reportSection);return n=>{const i=Nh(n,r,s);return i?i.trim().length>0:!0}}},{pattern:/^If\s+(\w+)\s+(?:is\s+)?(.*?)\s+and\s+(\w+)\s+(?:is\s+)?(.*)$/i,generator:(t,a)=>(Dp(a.reportSection),s=>!0)},{pattern:/^If\s+(\w+)\s+(?:is\s+)?(.*?)\s+or\s+(\w+)\s+(?:is\s+)?(.*)$/i,generator:(t,a)=>(Dp(a.reportSection),s=>!0)},{pattern:/^If\s+(\w+)\s+(?:equals|=)\s+['"]?([^'"]+)['"]?$/i,generator:(t,a)=>{const s=t[1],r=t[2],n=Dp(a.reportSection);return i=>Nh(i,n,s)!==r}},{pattern:/^If\s+(\w+)\s+does\s+not\s+equal\s+['"]?([^'"]+)['"]?$/i,generator:(t,a)=>{const s=t[1],r=t[2],n=Dp(a.reportSection);return i=>{const l=Nh(i,n,s);return l?l===r:!0}}}];function rG(t){const a=t.ruleLogic;for(const{pattern:s,generator:r}of sG){const n=a.match(s);if(n)return r(n,t)}return()=>!0}const nG=Q6;function iG(t,a){const s=t.metadata?.[a];if(!s||typeof s!="object")return null;const r=s.value;if(r==null)return null;const n=String(r).trim();return n.length>0?n:null}function Up(t,a){const s=t.reportIdentification?.[a];if(!s||typeof s!="object")return null;const r=s.value;if(r==null)return null;const n=String(r).trim();return n.length>0?n:null}const oG=[{jsonRule:{uniqueId:"ECHO-2064.0001",dataElement:"DocumentType",messageId:"ECHO2064-DOC-TYPE",message:"Provide the document type for the report header.",ruleLogic:"If DocumentType is not provided",severity:"Fatal",propertyAffected:"N/A",reportSection:"Report Identification",reportSubsection:"Header",reportLabel:"Document Type",dataPointName:"DocumentType",xpath:"../VA
11LUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},validate:t=>Up(t,"DocumentType")!==null},{jsonRule:{uniqueId:"ECHO-2064.0002",dataElement:"DocumentFormIssuingEntityNameType",messageId:"ECHO2064-DOC-ISSUER",message:"Provide the document form issuing entity name for the report footer.",ruleLogic:"If DocumentFormIssuingEntityNameType is not provided",severity:"Fatal",propertyAffected:"N/A",reportSection:"Report Identification",reportSubsection:"Footer",reportLabel:"Document Form Issuing Entity",dataPointName:"DocumentFormIssuingEntityNameType",xpath:"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},validate:t=>Up(t,"DocumentFormIssuingEntityNameType")!==null},{jsonRule:{uniqueId:"ECHO-2064.0003",dataElement:"DocumentFormIssuingEntityVersionIdentifier",messageId:"ECHO2064-DOC-ISSUER-VER",message:"Provide the document form issuing entity version identifier for the report footer.",ruleLogic:"If DocumentFormIssuingEntityVersionIdentifier is not provided",severity:"Fatal",propertyAffected:"N/A",reportSection:"Report Identification",reportSubsection:"Footer",reportLabel:"Issuing Entity Version",dataPointName:"DocumentFormIssuingEntityVersionIdentifier",xpath:"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},validate:t=>Up(t,"DocumentFormIssuingEntityVersionIdentifier")!==null},{jsonRule:{uniqueId:"ECHO-2064.0004",dataElement:"AboutVersionIdentifier",messageId:"ECHO2064-ABOUT-VER",message:"Provide the document about-version identifier for the report footer.",ruleLogic:"If AboutVersionIdentifier is not provided",severity:"Fatal",propertyAffected:"N/A",reportSection:"Report Identification",reportSubsection:"Footer",reportLabel:"About Version",dataPointName:"AboutVersionIdentifier",xpath:"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},validate:t=>Up(t,"AboutVersionIdentifier")!==null},{jsonRule:{uniqueId:"ECHO-2064.0005",dataElement:"AppraiserFileIdentifier",messageId:"ECHO2064-APPR-FILE-ID",message:"Provide the appraiser file identifier for the report footer.",ruleLogic:"If AppraiserFileIdentifier is not provided",severity:"Fatal",propertyAffected:"N/A",reportSection:"Report Identification",reportSubsection:"Footer",reportLabel:"Appraiser File Identifier",dataPointName:"AppraiserFileIdentifier",xpath:"../VALUATION_ANALYSIS/VALUATION_REPORT/VALUATION_REPORT_DETAIL/"},validate:t=>Up(t,"AppraiserFileIdentifier")!==null},{jsonRule:{uniqueId:"ECHO-2064.0006",dataElement:"ReconsiderationOfValueResultDate",messageId:"ECHO2064-ROV-RESULT-DATE",message:"Provide the date the appraiser completed the reconsideration of value.",ruleLogic:'If ReconsiderationOfValueIndicator = "true" and ReconsiderationOfValueResultDate is not provided',severity:"Fatal",propertyAffected:"N/A",reportSection:"Revision History",reportSubsection:"Reconsideration of Value",reportLabel:"Date",dataPointName:"ReconsiderationOfValueResultDate",xpath:"../VALUATION_ANALYSIS/VALUATION_REPORT/RECONSIDERATIONS_OF_VALUE/RECONSIDERATION_OF_VALUE/"},validate:t=>iG(t,"ReconsiderationOfValueIndicator")!=="true"?!0:Up(t,"ReconsiderationOfValueResultDate")!==null},{jsonRule:{uniqueId:"ECHO-GSECRULE.0001",dataElement:"OverallConditionRatingCode",messageId:"ECHO-GSECRULE-C6-CASCADE",message:"When any component is rated C6 (Substantial Damage), the 'Overall Condition Rating' must also be C6.",ruleLogic:'If any ExteriorConditionRatingCode, InteriorConditionRatingCode, or per-feature condition code = "C6" and OverallConditionRatingCode is not "C6"',severity:"Fatal",propertyAffected:"Subject",reportSection:"Overall Quality and Condition",reportSubsection:"Condition",reportLabel:"Overall Condition Rating",dataPointName:"OverallConditionRatingCode",xpath:"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},validate:t=>{const a=Up(t,"DocumentType");if(a&&a!=="AppraisalReport")return!0;const s=Dm(t,"IMPROVEMENT_DETAIL");if(s.length===0)return!0;const r=["ExteriorConditionRatingCode","InteriorConditionRatingCode","RoofConditionRatingCode","GuttersConditionRatingCode","WindowsConditionRatingCode","ScreensConditionRatingCode","ManufacturedHomeSectionConditionRatingCode"];let n=!1;for(const l of s){for(const c of r)if(dd(l,c)==="C6"){n=!0;break}if(n)break}if(!n)return!0;const i=t.improvements?.OverallConditionRatingCode?.value??null;if(i==="C6")return!0;
11if(typeof i=="string")return!1;for(const l of s){const c=dd(l,"OverallConditionRatingCode");if(c!==null)return c==="C6"}return!1}},{jsonRule:{uniqueId:"ECHO-GSECRULE.0002",dataElement:"OverallConditionRatingCode",messageId:"ECHO-GSECRULE-C1-CASCADE",message:"When 'Overall Condition Rating' is C1, all kitchens and bathrooms must be rated 'New or Like New' / 'Fully Updated', and 'New Construction' must be indicated.",ruleLogic:'If OverallConditionRatingCode = "C1" and (any ROOM_DETAIL kitchen/bathroom is not NewOrLikeNew+FullyUpdated, or NewConstructionIndicator is not "true")',severity:"Fatal",propertyAffected:"Subject",reportSection:"Overall Quality and Condition",reportSubsection:"Condition",reportLabel:"Overall Condition Rating",dataPointName:"OverallConditionRatingCode",xpath:"../VALUATION_ANALYSIS/PROPERTIES/PROPERTY/IMPROVEMENTS/IMPROVEMENT/IMPROVEMENT_DETAIL/"},validate:t=>{const a=Up(t,"DocumentType");if(a&&a!=="AppraisalReport")return!0;const s=t.improvements?.OverallConditionRatingCode?.value??null,r=Dm(t,"IMPROVEMENT_DETAIL");let n=s;if(n===null)for(const d of r){const p=dd(d,"OverallConditionRatingCode");if(p!==null){n=p;break}}if(n!=="C1")return!0;const i=t.improvements?.NewConstructionIndicator?.value??null;if(i!=="true"&&i!==!0)return!1;const l=Dm(t,"ROOM_DETAIL");if(l.length===0)return!0;const c=new Set(["Kitchen","Bathroom","FullBath","HalfBath","ThreeQuarterBath"]);for(const d of l){const p=dd(d,"RoomType");if(!p||!c.has(p))continue;const u=dd(d,"RoomConditionStatusType"),m=dd(d,"RoomUpdateStatusType");if(u!=="NewOrLikeNew"||m!=="FullyUpdated")return!1}return!0}},{jsonRule:{uniqueId:"ECHO-GSECRULE.0003",dataElement:"PropertyValuationConditionalConclusionType",messageId:"ECHO-GSECRULE-SUBJTO-INVERSE",message:"An 'As-Is' appraisal conclusion is not permitted when defects require Repair, Completion, or Inspection.",ruleLogic:'If any DEFECT_DETAIL has DefectItemRecommendedActionType in ("Repair", "Completion", "Inspection") and PropertyValuationConditionalConclusionType = "AsIs" in any VALUATION_CONDITION instance',severity:"Fatal",propertyAffected:"Subject",reportSection:"Reconciliation",reportSubsection:"Valuation Condition",reportLabel:"Valuation Condition",dataPointName:"PropertyValuationConditionalConclusionType",xpath:"../VALUATION_ANALYSIS/VALUATION_CONDITIONS/VALUATION_CONDITION/"},validate:t=>{const a=Up(t,"DocumentType");if(a&&a!=="AppraisalReport")return!0;const s=Dm(t,"DEFECT_DETAIL");if(s.length===0)return!0;const r=new Set(["Repair","Completion","Inspection"]);let n=!1;for(const l of s){const c=dd(l,"DefectItemRecommendedActionType");if(c&&r.has(c)){n=!0;break}}if(!n)return!0;const i=Dm(t,"VALUATION_CONDITION");if(i.length===0)return!0;for(const l of i)if(dd(l,"PropertyValuationConditionalConclusionType")==="AsIs")return!1;return!0}}];function lG(){const a=nG.rules.map(s=>({...s,validate:rG(s)}));for(const s of oG)a.push({...s.jsonRule,validate:s.validate});return a}const cG=lG();function dG(t){const a=[],s=S$(Up(t,"DocumentType"));for(const i of cG)if(!(s&&i.dataPointName&&!eG(i.dataPointName,s)))try{i.validate(t)||a.push({passed:!1,messageId:i.messageId,message:i.message,severity:i.severity,section:i.reportSection,subsection:i.reportSubsection,dataElement:i.dataElement,reportLabel:i.reportLabel})}catch(l){console.warn(`Rule ${i.messageId} failed to execute:`,l)}const r=a.filter(i=>i.severity==="Fatal").length,n=a.filter(i=>i.severity==="Warning").length;return{isValid:r===0,fatalCount:r,warningCount:n,results:a,timestamp:new Date().toISOString()}}const bk=[{id:"subject",name:"Subject",hasFieldMapping:!0},{id:"contract",name:"Contract",hasFieldMapping:!0},{id:"neighborhood",name:"Neighborhood",hasFieldMapping:!0},{id:"site",name:"Site",hasFieldMapping:!0},{id:"improvements",name:"Improvements",hasFieldMapping:!0},{id:"salesComparison",name:"Sales Comparison",hasFieldMapping:!0},{id:"reconciliation",name:"Reconciliation",hasFieldMapping:!0},{id:"values",name:"Values",hasFieldMapping:!1},{id:"signature",name:"Signature",hasFieldMapping:!1},{id:"attachments",name:"Attachments",hasFieldMapping:!1}],uG=bk.map(t=>
11t.id);function pG({orderData:t,propertyData:a,selectedComps:s,reconciliationData:r,appraiserInfo:n,qcRules:i}){const[l,c]=o.useState("subject"),[d,p]=o.useState({}),[u,m]=o.useState({censusTract:null,county:null,coordinates:null,loading:!1,error:null}),[h,f]=o.useState({floodZone:null,femaMapNumber:null,femaMapDate:null,isSpecialFloodHazardArea:!1,loading:!1,error:null}),v=o.useCallback(_=>{uG.includes(_)&&c(_)},[]),S=o.useRef({}),N=o.useCallback((_,$)=>{S.current[_]=$},[]),x=o.useCallback(_=>{const $=S.current[_];$&&($.scrollIntoView({behavior:"smooth",block:"center"}),$.focus?.(),$.classList.add("ring-2","ring-blue-500"),setTimeout(()=>{$.classList.remove("ring-2","ring-blue-500")},2e3))},[]),y=o.useCallback(_=>{if(!_)return{street:"",city:"",state:"",zip:""};const $=_.split(",").map(z=>z.trim());if($.length>=3){const z=$[0],V=$[1],le=$[2].split(" ").filter(Boolean),W=le[0]||"",me=le[1]||"";return{street:z,city:V,state:W,zip:me}}else if($.length===2){const z=$[0],V=$[1].split(" ").filter(Boolean),le=V.slice(0,-2).join(" "),W=V[V.length-2]||"",me=V[V.length-1]||"";return{street:z,city:le,state:W,zip:me}}return{street:_,city:"",state:"",zip:""}},[]),b=o.useMemo(()=>{const _=t?.subjectAddress?.value||"";return y(_)},[t?.subjectAddress?.value,y]),j=o.useMemo(()=>(t?.assignmentType?.value||"").toLowerCase().includes("purchase"),[t?.assignmentType?.value]);o.useEffect(()=>{const _=t?.subjectAddress?.value;if(!_||u.censusTract||u.loading)return;(async()=>{m(z=>({...z,loading:!0,error:null}));try{const V=await(await fetch(`/api/census/geocode?onelineaddress=${encodeURIComponent(_)}`)).json();if(V.success&&V.censusTract){const le=V.censusTract.tract,W=le?`${le.slice(0,4)}.${le.slice(4)}`:V.censusTract.name?.replace("Census Tract ","")||null;m({censusTract:W,county:V.county?.name||null,coordinates:V.coordinates||null,loading:!1,error:null})}else V.success&&V.coordinates?m({censusTract:null,county:V.county?.name||null,coordinates:V.coordinates,loading:!1,error:null}):m(le=>({...le,loading:!1,error:V.error||"No census data found"}))}catch(z){console.error("[Census] Fetch error:",z),m(V=>({...V,loading:!1,error:z instanceof Error?z.message:"Failed to fetch census data"}))}})()},[t?.subjectAddress?.value,u.censusTract,u.loading]),o.useEffect(()=>{const _=u.coordinates;if(!_||h.floodZone||h.loading)return;(async()=>{f(z=>({...z,loading:!0,error:null}));try{const V=await(await fetch(`/api/fema/floodzone?lat=${_.y}&lng=${_.x}`)).json();V.success?f({floodZone:V.floodZone||null,femaMapNumber:V.femaMapNumber||null,femaMapDate:V.femaMapDate||null,isSpecialFloodHazardArea:V.isSpecialFloodHazardArea||!1,loading:!1,error:null}):f(le=>({...le,loading:!1,error:V.error||"No flood data found"}))}catch(z){console.error("[FEMA] Fetch error:",z),f(V=>({...V,loading:!1,error:z instanceof Error?z.message:"Failed to fetch flood data"}))}})()},[u.coordinates,h.floodZone,h.loading]);const T=o.useMemo(()=>!s||s.length===0?[]:s.map((_,$)=>{const z=_.mlsData,V=_.publicRecordData,le=_.rawPublicRecordData,W=_.distance?`${_.distance.toFixed(2)} miles`:_.distanceLabel||"",me=z?.RoomsTotal??z?.TotalRooms??z?.totalRooms??z?.RoomsTotalNumeric??z?.NumRooms??_.totalRooms??null,Z=z?.BedroomsTotal??z?.bedrooms??_.bedrooms??_.beds??null,pe=z?.BathroomsFull??z?.fullBaths??_.fullBaths??_.fullBathrooms,se=z?.BathroomsHalf??z?.halfBaths??_.halfBaths??_.halfBathrooms??0,fe=z?.BathroomsTotalInteger??z?.bathrooms??_.bathrooms??_.baths,ue=pe!=null?pe+se*.5:fe??null,be=le?.BelowGradeTotalArea??V?.BelowGradeTotalArea??z?.BasementArea??z?.BasementSqFt??z?.basementSqft??_.basementSqft??_.basementArea??null,H=le?.BelowGradeFinishedArea??V?.BelowGradeFinishedArea??_.prBasementFinishedArea??z?.BasementFinishedArea??z?.FinishedBasementArea??z?.basementFinishedSqft??_.basementFinishedSqft??_.basementFinishedArea??null,ye=z?.BasementPercentFinished??z?.BasementFinishedPercent??null,de=z?.basement??z?.Basement??_.basement??null,ge=z?.BasementAccess??z?.BasementType??z?.BasementEntry??z?.basementAccess??_.basementAccess??null,Be=z?.BasementBedrooms??z?.BedroomsBelowGrade??z?.BelowGradeBedrooms??z?.belowGradeRooms??_.bedroomsBelowGrade??0,He=z?.BasementBathroomsFull??z?.BathroomsFullBasement??z?.BelowGradeBathroomsFull??_.basementFullBaths??0,Ie=z?.BasementBathroomsHalf??z?.BathroomsHalfBasement??z?.BelowGradeBathroomsHalf??_.basementHalfBaths??0,ce=z?.BasementRecRoom??z?.RecreationRoom??z?.RecR
11oom??z?.RecreationRooms??z?.FamilyRoomBasement??z?.BasementFamilyRoom??_.recRooms??0,Pe=z?.DaysOnMarket??z?.DOM??z?.MarketTime??z?.daysOnMarket??z?.CumulativeDaysOnMarket??_.daysOnMarket??null,We=z?.GarageSpaces??z?.garageSpaces??_.garageSpaces??null,Re=z?.GarageType??z?.garageType??_.garageType??null,ne=z?.LotSizeSquareFeet??z?.lotSize??_.lotSize??null,Me=z?.LotSizeUnits??z?.lotSizeUnits??_.lotSizeUnits??"sqft",lt=z?.Heating??z?.heating??_.heating??null,Tt=z?.Cooling??z?.cooling??_.cooling??null,je=z?.YearBuilt??z?.yearBuilt??_.yearBuilt??null,Le=z?.StoriesTotal??z?.stories??_.stories,ut=z?.PatioAndPorchFeatures??z?.PorchFeatures??z?.ExteriorFeatures??z?.ExteriorAmenities??z?.Patio??z?.Deck??z?.porchPatioDeck??_.porchPatioDeck??null;return{id:_.id||`comp-${$}`,address:_.address||"",proximityToSubject:W,salePrice:_.salePrice||0,pricePerSqFt:_.pricePerSqFt||(_.salePrice&&_.squareFeet?Math.round(_.salePrice/_.squareFeet):0),dataSources:_.mlsNumber?`MLS#${_.mlsNumber}`:"Public Record",verificationSources:_.mlsNumber?"MLS;DOM":"PubRec",saleOrFinancingConcessions:_.financingConcessions||"Conv;0",dateOfSale:Mm(_.saleDate,_.contractDate),daysOnMarket:Pe??"",location:_.location||"N;Res",leaseholdFeeSimple:_.leasehold||"Fee Simple",site:sb(ne,Me),view:_.view||"N;Res",design:z?.designStyle||_.designStyle||(Le?`${Le}Sty`:""),quality:_.quality||"Q4",actualAge:CV(je),condition:_.condition||"C3",aboveGradeTotal:jv(me,Z,ue,pe,se),aboveGradeBedrooms:Z||0,aboveGradeBathrooms:Uh(pe,se,ue),gla:_.squareFeet||z?.gla||z?.LivingArea||0,basement:(()=>{console.log(`[UAD] Comp ${$} basement data:`,{basementSqft:be,basementFinished:H,basementDescription:de});const st=uy(be,H,ye,ge);return console.log(`[UAD] Comp ${$} formatted basement:`,st),st==="0"?de||"None":st})(),belowGrade:sD(ce,Be,He,Ie),functionalUtility:_.functionalUtility||"Average",heatingCooling:aD(lt,Tt),energyEfficient:_.energyEfficient||"None",garageCarport:IV(We,Re),porchPatioDeck:wI(ut),rawData:_}}),[s]),O=o.useMemo(()=>({address:b.street,fullAddress:t?.subjectAddress?.value,city:b.city,state:b.state,zipCode:b.zip,cityStateZip:`${b.city}, ${b.state} ${b.zip}`.trim(),county:u.county||a?.county?.value||a?.rawPublicRecordData?.CountyName||"",taxYear:a?.taxYear?.value||a?.rawPublicRecordData?.TaxAssessmentRollYear||"",taxes:a?.taxes?.value||a?.rawPublicRecordData?.AnnualTaxes||"",owner:t?.owner?.value||a?.owner?.value||a?.rawPublicRecordData?.OwnerName||"",legalDescription:a?.legalDescription?.value||a?.rawPublicRecordData?.LegalDescription||"",pinNumber:a?.pinNumber?.value||a?.rawPublicRecordData?.ParcelNumber||"",neighborhoodName:a?.neighborhoodName?.value||a?.rawMlsData?.SubdivisionName||"",censusTract:u.censusTract||"",mapReference:a?.mapReference?.value||a?.plat?.value||(u.county&&u.censusTract?`${u.county} / ${u.censusTract}`:""),occupancy:t?.occupancy?.value||a?.occupancy?.value||"",assignmentType:t?.assignmentType?.value||"",hoaFees:a?.hoaFees?.value||"",hoaFeeFrequency:a?.hoaFeeFrequency?.value||"Monthly",isPud:a?.pud?.value==="Yes"||a?.pud?.value===!0,specialAssessments:a?.specialAssessments?.value||"",propertyRights:t?.propertyRights?.value||"Fee Simple",isLoading:u.loading}),[b,t,a,u]),E=o.useCallback(_=>{if(!_)return null;const $={orderData:t,propertyData:a,comps:T,uadComps:T,reconciliation:r,appraiser:n,subject:{...O,location:a?.location?.value||"N;Res",view:a?.view?.value||"N;
11Res",site:a?.lotSize?.value||a?.lotSize,design:a?.designStyle?.value||a?.designStyle,quality:a?.quality?.value||"Q4",condition:a?.condition?.value||"C3",actualAge:a?.actualAge?.value||(a?.yearBuilt?.value?(new Date().getFullYear()-parseInt(a.yearBuilt.value)).toString():""),salePrice:j&&t?.contractPrice?.value||""},contract:{isPurchase:j,contractPrice:j&&t?.contractPrice?.value||"",contractDate:j&&t?.contractDate?.value||"",didNotAnalyze:!j},site:{dimensions:a?.lotDimensions?.value||a?.lotDimensions||"",area:a?.lotSize?.value||a?.lotSize||"",shape:a?.lotShape?.value||"Rectangular",zoningClassification:a?.zoningClassification?.value||"",zoningDescription:a?.zoningDescription?.value||"",zoningCompliance:a?.zoningCompliance?.value||"Legal",femaFloodZone:h.floodZone||a?.femaFloodZone?.value||a?.femaFloodZone||"",femaMapNumber:h.femaMapNumber||a?.femaMapNumber?.value||a?.femaMapNumber||"",femaMapDate:h.femaMapDate||a?.femaMapDate?.value||a?.femaMapDate||"",isSpecialFloodHazardArea:h.isSpecialFloodHazardArea,isPud:a?.pud?.value==="Yes"||a?.pud?.value===!0,hoaFees:a?.hoaFees?.value||"",hoaFeeFrequency:a?.hoaFeeFrequency?.value||"Monthly"},improvements:{stories:a?.stories?.value||a?.stories||a?.mlsData?.stories||"",designStyle:a?.designStyle?.value||a?.design||a?.mlsData?.designStyle||"",yearBuilt:a?.yearBuilt?.value||"",effectiveAge:a?.effectiveAge?.value||a?.effectiveAge||"",foundationWalls:a?.foundationWalls||a?.mlsData?.foundation||"",exteriorWalls:a?.exteriorWalls||a?.mlsData?.exteriorMaterial||"",roofSurface:a?.roofSurface||a?.mlsData?.roofType||"",guttersDownspouts:a?.guttersDownspouts||"",windowType:a?.windowType||"",stormSash:a?.stormSash||"",screens:a?.screens||"",basementArea:a?.basementArea?.value||a?.basementArea||a?.mlsData?.basementArea||"",basementFinish:a?.basementFinish?.value||a?.basementFinish||a?.mlsData?.basementFinishedArea||"",interiorFloors:a?.interiorFloors||a?.mlsData?.flooring||"",interiorWalls:a?.interiorWalls||"",trimFinish:a?.trimFinish||"",bathFloor:a?.bathFloor||"",bathWainscot:a?.bathWainscot||"",totalRooms:a?.totalRooms?.value||a?.totalRooms||a?.mlsData?.totalRooms||"",bedrooms:a?.bedrooms?.value||a?.bedrooms||a?.mlsData?.bedrooms||"",bathrooms:(()=>{const z=a?.fullBaths?.value??a?.fullBathrooms?.value??a?.fullBaths??a?.mlsData?.fullBaths??a?.mlsData?.BathroomsFull??null,V=a?.halfBaths?.value??a?.halfBathrooms?.value??a?.halfBaths??a?.mlsData?.halfBaths??a?.mlsData?.BathroomsHalf??null,le=a?.bathrooms?.value??a?.bathrooms??null;return Uh(z!=null?Number(z):null,V!=null?Number(V):null,le!=null?Number(le):null)})(),fullBaths:(()=>{const z=a?.fullBaths?.value??a?.fullBathrooms?.value??a?.fullBaths??a?.mlsData?.fullBaths??a?.mlsData?.BathroomsFull??null;if(z!=null)return z;const V=a?.bathrooms?.value??a?.bathrooms??null;return V!=null?Math.floor(Number(V)):""})(),halfBaths:(()=>{const z=a?.halfBaths?.value??a?.halfBathrooms?.value??a?.halfBaths??a?.mlsData?.halfBaths??a?.mlsData?.BathroomsHalf??null;if(z!=null)return z;const V=a?.bathrooms?.value??a?.bathrooms??null;if(V!=null){const le=Number(V);return Math.round((le-Math.floor(le))*2)}return""})(),basementFullBaths:a?.basementFullBaths?.value??a?.basementFullBaths??a?.mlsData?.BasementBathroomsFull??a?.mlsData?.BathroomsFullBasement??"",basementHalfBaths:a?.basementHalfBaths?.value??a?.basementHalfBaths??a?.mlsData?.BasementBathroomsHalf??a?.mlsData?.BathroomsHalfBasement??"",gla:a?.gla?.value||a?.gla||a?.squareFeet?.value||a?.mlsData?.gla||"",heatingFuel:a?.heatingFuel?.value||a?.heatingFuel||a?.mlsData?.heatingFuel||"",heatingType:a?.heatingType?.value||a?.heatingType||a?.mlsData?.heatingType||"",coolingType:a?.coolingType?.value||a?.coolingType||a?.mlsData?.coolingType||"",garageType:(()=>{const z=(a?.garageType?.value||a?.garageType||a?.mlsData?.garageType||"").toLowerCase();return z.includes("attached")?"Attached":z.includes("detached")?"Detached":z.includes("built-in")||z.includes("builtin")?"Built-in":z.includes("carport")?"Carport":z||""})(),garageCars:a?.garageCars?.value||a?.garageCars||a?.mlsData?.garageCars||"",drivewaySurface:a?.drivewaySurface||a?.mlsData?.driveway||""},marketData:a?.marketData||{}};try{const z=_.split(".");let V=$;
11for(const le of z){if(le.includes("[")){const[W,me]=le.split("["),Z=parseInt(me.replace("]",""));V=V?.[W]?.[Z]}else V=V?.[le];if(V===void 0)return null}return typeof V=="object"&&V?.value!==void 0?V.value:V}catch{return null}},[t,a,s,T,r,n,b,j,u,h]),R=o.useCallback((_,$)=>d[_]!==void 0?d[_]:E($),[d,E]),G=o.useCallback((_,$)=>{p(z=>({...z,[_]:$}))},[]),U=o.useCallback(_=>{if(!_)return[];const $=[];if(_.includes("orderData")){const z=E(_);z&&$.push({name:"Order",value:z})}if(_.includes("propertyData")){const z=E(_);z&&$.push({name:"PropMix",value:z})}return $},[E]),C=o.useCallback(_=>{if(_.length<=1)return!1;const $=_.map(z=>String(z.value).toLowerCase().trim());return new Set($).size>1},[]),F=o.useCallback(()=>{const _={};return Yp.forEach($=>{$.fields.forEach(z=>{const V=`${$.id}.${z.pdfFieldName}`,le=R(V,z.wizardDataPath),W=U(z.wizardDataPath),me=C(W);let Z="complete";!le&&z.required?Z="missing":me?Z="conflict":le||(Z="complete"),_[V]={value:le,status:Z,sources:W,conflict:me}})}),_},[R,U,C]),A=o.useCallback(_=>{const $=s?.length||0,z=NY($),V=Yp.map(le=>{const W=z.find(be=>be.sectionId===le.id);if(le.id==="contract"&&!j)return{sectionId:le.id,sectionName:le.name,totalFields:W?.interactiveFields||0,filledFields:W?.interactiveFields||0,requiredFields:0,missingRequired:0,issues:[],conflicts:0};const me=new Set;let Z=0,pe=0,se=0;const fe=[],ue={};return le.fields.forEach(be=>{if(!be.wizardDataPath||!be.group)return;const H=`${le.id}.${be.pdfFieldName}`;_[H]?.value&&(ue[be.group]=!0)}),le.fields.forEach(be=>{if(!be.wizardDataPath)return;const H=be.wizardDataPath.match(/comps\[(\d+)\]/);if(H&&parseInt(H[1])>=$)return;if(be.group){if(me.has(be.group))return;me.add(be.group);const ge=ue[be.group]===!0;ge&&Z++,be.required&&!ge&&(pe++,fe.push({sectionId:le.id,fieldName:be.label,pdfFieldName:be.pdfFieldName,severity:"error",message:`${be.label} is required`,suggestion:`Please select an option for ${be.label}`}));return}const ye=`${le.id}.${be.pdfFieldName}`,de=_[ye];de?.value&&Z++,be.required&&!de?.value&&(pe++,fe.push({sectionId:le.id,fieldName:be.label,pdfFieldName:be.pdfFieldName,severity:"error",message:`${be.label} is required`,suggestion:`Please provide a value for ${be.label}`})),de?.conflict&&se++}),{sectionId:le.id,sectionName:le.name,totalFields:W?.interactiveFields||0,filledFields:Z,requiredFields:W?.requiredFields||0,missingRequired:pe,issues:fe,conflicts:se}});return V.push({sectionId:"values",sectionName:"Values",totalFields:4,filledFields:r?.finalOpinionOfValue>0?4:0,requiredFields:1,missingRequired:r?.finalOpinionOfValue>0?0:1,issues:[],conflicts:0}),V.push({sectionId:"signature",sectionName:"Signature",totalFields:5,filledFields:n?.signatureImage?5:4,requiredFields:1,missingRequired:n?.signatureImage?0:1,issues:[],conflicts:0}),V.push({sectionId:"attachments",sectionName:"Attachments",totalFields:0,filledFields:0,requiredFields:0,missingRequired:0,issues:[],conflicts:0}),V},[r,n,s,j]),M=o.useCallback((_,$)=>{const z=[];let V=0;const le=new Set;return AY.forEach(W=>{if(W.sectionId==="contract"&&!j)return;_[W.fieldId]?.value||(le.add(W.fieldId),z.push({id:`issue-${V++}`,sectionId:W.sectionId,fieldId:W.fieldId,fieldName:W.label,severity:"hard-stop",type:"missing",message:`${W.label} is required for UAD 2.6 compliance`,suggestion:`Please provide a value for ${W.label}`}))}),Yp.forEach(W=>{W.id==="contract"&&!j||W.fields.forEach(me=>{const Z=`${W.id}.${me.pdfFieldName}`,pe=_[Z];
11le.has(Z)||(me.required&&!pe?.value&&z.push({id:`issue-${V++}`,sectionId:W.id,fieldId:Z,fieldName:me.label,severity:"hard-stop",type:"missing",message:`${me.label} is required`,suggestion:`Please provide a value for ${me.label}`}),pe?.conflict&&z.push({id:`issue-${V++}`,sectionId:W.id,fieldId:Z,fieldName:me.label,severity:"soft-stop",type:"conflict",message:`Data conflict: ${pe.sources?.map(se=>`${se.name}: ${se.value}`).join(" vs ")}`,suggestion:"Select the correct value"}))})}),(!r?.finalOpinionOfValue||r.finalOpinionOfValue<=0)&&z.push({id:`issue-${V++}`,sectionId:"values",fieldId:"values.finalOpinionOfValue",fieldName:"Final Opinion of Value",severity:"hard-stop",type:"missing",message:"Final Opinion of Market Value is required",suggestion:"Enter a positive value in the Reconciliation or Values section"}),n?.signatureImage||z.push({id:`issue-${V++}`,sectionId:"signature",fieldId:"signature.appraiserSignature",fieldName:"Appraiser Signature",severity:"hard-stop",type:"missing",message:"Appraiser signature is required",suggestion:"Draw or upload your signature in the Signature section"}),i.forEach(W=>{if(!W.enabled)return;const me=W.targetField,Z=W.section||"subject";if(!me)return;const pe=Object.keys(_).filter(fe=>fe.includes(me)||fe.endsWith(`.${me}`));let se=!1;for(const fe of pe){const ue=_[fe];if(W.condition==="required"||W.condition==="missing"){if(!ue?.value){se=!0;break}}else if(W.condition==="conflict"&&ue?.conflict){se=!0;break}}se&&z.push({id:`qc-${W.ruleId}`,ruleId:W.ruleId,sectionId:Z,fieldId:pe[0],fieldName:me,severity:W.severity==="hard-stop"?"hard-stop":"soft-stop",type:"qc-rule",message:W.title||`QC Rule: ${W.ruleId}`,suggestion:W.revisionRequest,agency:W.agency})}),z},[i,r,n,j]),B=o.useMemo(()=>{const _=F(),$=A(_),z=M(_,$);return{fields:_,sections:$,issues:z,activeSection:l,isDirty:Object.keys(d).length>0}},[F,A,M,l,d]),oe=o.useCallback(_=>B.issues.filter($=>$.sectionId===_),[B.issues]),ae=o.useMemo(()=>B.issues.some(_=>_.severity==="hard-stop"),[B.issues]),D=o.useCallback(_=>B.issues.filter($=>!(_.severity?.length&&!_.severity.includes($.severity)||_.type?.length&&!_.type.includes($.type)||_.sectionId&&$.sectionId!==_.sectionId)),[B.issues]);return{state:B,activeSection:l,setActiveSection:v,getFieldValue:R,setFieldValue:G,registerFieldRef:N,scrollToField:x,getSectionIssues:oe,getFilteredIssues:D,hasHardStops:ae,fieldOverrides:d,uadComps:T,subjectData:O}}function mG({orderData:t,propertyData:a,subjectData:s,onChange:r,registerFieldRef:n,orderId:i}){const l=o.useCallback(S=>N=>{n&&n(S,N)},[n]),c=S=>S?typeof S=="object"&&"value"in S?S.value||"":String(S):"",[d,p]=o.useState({address:"",city:"",state:"",zipCode:"",county:"",borrower:"",owner:"",legalDescription:"",apn:"",taxYear:"",taxes:"",neighborhoodName:"",mapReference:"",censusTract:"",specialAssessments:"",hoaFees:"",lenderClient:"",lenderAddress:"",occupancy:"",assignmentType:"",propertyRights:"Fee Simple",isPud:!1,hoaFrequency:"per month"});o.useEffect(()=>{const S={};if(s){if(s.address&&(S.address=s.address),s.city&&(S.city=s.city),s.state&&(S.state=s.state),s.zipCode&&(S.zipCode=s.zipCode),s.county&&(S.county=s.county),s.owner&&(S.owner=s.owner),s.legalDescription&&(S.legalDescription=s.legalDescription),s.pinNumber&&(S.apn=s.pinNumber),s.taxYear&&(S.taxYear=String(s.taxYear)),s.taxes&&(S.taxes=u(s.taxes)),s.neighborhoodName&&(S.neighborhoodName=s.neighborhoodName),s.censusTract&&(S.censusTract=s.censusTract),s.mapReference&&(S.mapReference=s.mapReference),s.hoaFees&&(S.hoaFees=s.hoaFees),s.specialAssessments&&(S.specialAssessments=s.specialAssessments),s.isPud&&(S.isPud=s.isPud),s.occupancy){const N=s.occupancy.toLowerCase();N.includes("owner")?S.occupancy="Owner":N.includes("tenant")?S.occupancy="Tenant":N.includes("vacant")&&(S.occupancy="Vacant")}if(s.assignmentType){const N=s.assignmentType.toLowerCase();N.includes("purchase")?S.assignmentType="Purchase":N.includes("refin")?S.assignmentType="Refinance":S.assignmentType="Other"}if(s.propertyRights){const N=s.propertyRights.toLowerCase();N.includes("leasehold")?S.propertyRights="Leasehold":N.includes("fee")?S.propertyRights="Fee Simple":S.propertyRights="Other"}}c(t?.borrower)&&(S.borrower=c(t.borrower)),(c(t?.client)||c(t?.lender))&&(S.lenderClient=c(t?.client)||c(t?.lender)),c(t?.lenderAddress)&&(S.lenderAddress=c(t.lenderAddress)),p(N=>({...N,...S}
11)),Object.entries(S).forEach(([N,x])=>{r(N,x)})},[s,t]);const u=S=>{if(!S)return"";const N=typeof S=="string"?parseFloat(S.replace(/[^0-9.-]/g,"")):S;return isNaN(N)?String(S):new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(N)},m=(S,N)=>{p(x=>({...x,[S]:N})),r(S,N)},h=S=>!d[S],f=S=>h(S)?"border-red-300 bg-red-50":"border-slate-200 bg-slate-50",v=s?.isLoading||!1;return e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Subject"})}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-4",children:[e.jsxs("div",{className:"col-span-4",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Property Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.Property Address"),value:d.address,onChange:S=>m("address",S.target.value),className:`mt-1 h-10 text-sm ${f("address")}`,"data-testid":"input-property-address"}),h("address")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-3",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["City ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.City"),value:d.city,onChange:S=>m("city",S.target.value),className:`mt-1 h-10 text-sm ${f("city")}`,"data-testid":"input-city"}),h("city")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["State ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.State"),value:d.state,onChange:S=>m("state",S.target.value),className:`mt-1 h-10 text-sm ${f("state")}`,maxLength:2,"data-testid":"input-state"}),h("state")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Zip Code ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.Zip Code"),value:d.zipCode,onChange:S=>m("zipCode",S.target.value),className:`mt-1 h-10 text-sm ${f("zipCode")}`,"data-testid":"input-zip"}),h("zipCode")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-3",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["County ",e.jsx("span",{className:"text-red-500",children:"*"}),v&&e.jsx(za,{className:"inline w-3 h-3 ml-1 animate-spin"})]}),e.jsx(ze,{ref:l("subject.County"),value:d.county,onChange:S=>m("county",S.target.value),className:`mt-1 h-10 text-sm ${f("county")}`,"data-testid":"input-county"}),h("county")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-4",children:[e.jsxs("div",{className:"col-span-6",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Borrower ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.Borrower"),value:d.borrower,onChange:S=>m("borrower",S.target.value),className:`mt-1 h-10 text-sm ${f("borrower")}`,"data-testid":"input-borrower"}),h("borrower")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-6",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Owner of Public Record ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.Owner of Public Record"),value:d.owner,onChange:S=>m("owner",S.target.value),className:`mt-1 h-10 text-sm ${f("owner")}`,"data-testid":"input-owner"}),h("owner")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Legal Description ",e.jsx("span",{className:"text-red-500",children:"*"})]}
11),e.jsx(yi,{ref:l("subject.Legal Description"),value:d.legalDescription,onChange:S=>m("legalDescription",S.target.value),className:`mt-1 min-h-[60px] text-sm ${f("legalDescription")}`,"data-testid":"input-legal-description"}),h("legalDescription")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-4",children:[e.jsxs("div",{className:"col-span-4",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Assessor's Parcel # ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.Assessors Parcel"),value:d.apn,onChange:S=>m("apn",S.target.value),className:`mt-1 h-10 text-sm ${f("apn")}`,"data-testid":"input-apn"}),h("apn")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Tax Year ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.Tax Year"),value:d.taxYear,onChange:S=>m("taxYear",S.target.value),className:`mt-1 h-10 text-sm ${f("taxYear")}`,"data-testid":"input-tax-year"}),h("taxYear")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["R.E. Taxes $ ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.R.E. Taxes"),value:d.taxes,onChange:S=>m("taxes",S.target.value),className:`mt-1 h-10 text-sm ${f("taxes")}`,"data-testid":"input-taxes"}),h("taxes")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-4",children:[e.jsxs("div",{className:"col-span-4",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Neighborhood Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.Neighborhood Name"),value:d.neighborhoodName,onChange:S=>m("neighborhoodName",S.target.value),className:`mt-1 h-10 text-sm ${f("neighborhoodName")}`,"data-testid":"input-neighborhood-name"}),h("neighborhoodName")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-4",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Map Reference ",e.jsx("span",{className:"text-red-500",children:"*"}),v&&e.jsx(za,{className:"inline w-3 h-3 ml-1 animate-spin"})]}),e.jsx(ze,{ref:l("subject.Map Reference"),value:d.mapReference,onChange:S=>m("mapReference",S.target.value),className:`mt-1 h-10 text-sm ${f("mapReference")}`,"data-testid":"input-map-reference"}),h("mapReference")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-4",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Census Tract ",e.jsx("span",{className:"text-red-500",children:"*"}),v&&e.jsx(za,{className:"inline w-3 h-3 ml-1 animate-spin"})]}),e.jsx(ze,{ref:l("subject.Census Tract"),value:d.censusTract,onChange:S=>m("censusTract",S.target.value),className:`mt-1 h-10 text-sm ${f("censusTract")}`,"data-testid":"input-census-tract"}),h("censusTract")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-4 items-end",children:[e.jsxs("div",{className:"col-span-3",children:[e.jsxs("label",{className:`text-xs font-semibold block mb-2 ${d.occupancy?"text-slate-500":"text-red-500"}`,children:["Occupant ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:`flex items-center gap-4 p-2 rounded ${d.occupancy?"":"bg-red-50 border border-red-300"}`,children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"occupant-owner",checked:d.occupancy==="Owner",onCheckedChange:S=>m("occupancy",S?"Owner":""),"data-testid":"checkbox-occupant-owner"}),e.jsx("span",{className:"text-slate-700",children:"Owner"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"occupant-tenant",checked:d.occupancy==="Tenant",onCheckedChange:S=>m("occupancy",S?"Tenant":""),"data-testid":"checkbox-occupant-tenant"}),e.jsx("span",{className:"text-slate-700",children:"Tenant"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"occupant-vacant",checked:d.occupancy==="Vacant",onCheckedChange:S=>m("occupancy",S?"Vacant":""),"data-testid":"checkbox-occupant-vacant"}),e.jsx("span",{className:"text-slate-700",children:"Vacant"})]})]}),!d.occupancy&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Select one"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Special Assessments $"}),e.jsx(ze,{value:d.specialAssessments,onChange:S=>m("specialAssessments",S.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200",placeholder:"$0","data-testid":"input-special-assessments"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"HOA $"}),e.jsx(ze,{value:d.hoaFees,onChange:S=>m("hoaFees",S.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200",placeholder:"$0","data-testid":"input-hoa-fees"})]}),e.jsx("div",{className:"col-span-1",children:e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer h-10",children:[e.jsx(Pa,{id:"pud",checked:d.isPud,onCheckedChange:S=>m("isPud",!!S),"data-testid":"checkbox-pud"}),e.jsx("span",{className:"text-slate-700",children:"PUD"})]})}),e.jsx("div",{className:"col-span-2",children:e.jsxs("div",{className:"flex items-center gap-3 h-10",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"hoa-per-year",checked:d.hoaFrequency==="per year",onCheckedChange:S=>m("hoaFrequency",S?"per year":"per month"),"data-testid":"checkbox-hoa-per-year"}),e.jsx("span",{className:"text-slate-700",children:"per year"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"hoa-per-month",checked:d.hoaFrequency==="per month",onCheckedChange:S=>m("hoaFrequency",S?"per month":"per year"),"data-testid":"checkbox-hoa-per-month"}),e.jsx("span",{className:"text-slate-700",children:"per month"})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 
11w-40",children:"Property Rights Appraised"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"rights-fee-simple",checked:d.propertyRights==="Fee Simple",onCheckedChange:S=>m("propertyRights",S?"Fee Simple":""),"data-testid":"checkbox-fee-simple"}),e.jsx("span",{className:"text-slate-700",children:"Fee Simple"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"rights-leasehold",checked:d.propertyRights==="Leasehold",onCheckedChange:S=>m("propertyRights",S?"Leasehold":""),"data-testid":"checkbox-leasehold"}),e.jsx("span",{className:"text-slate-700",children:"Leasehold"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"rights-other",checked:d.propertyRights==="Other",onCheckedChange:S=>m("propertyRights",S?"Other":""),"data-testid":"checkbox-rights-other"}),e.jsx("span",{className:"text-slate-700",children:"Other (describe)"})]}),e.jsx(ze,{placeholder:"",className:"h-10 text-sm bg-slate-50 border-slate-200 flex-1 max-w-[200px]","data-testid":"input-rights-other-describe"})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:`text-xs font-semibold w-40 ${d.assignmentType?"text-slate-500":"text-red-500"}`,children:["Assignment Type ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:`flex items-center gap-4 p-2 rounded ${d.assignmentType?"":"bg-red-50 border border-red-300"}`,children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"assignment-purchase",checked:d.assignmentType==="Purchase",onCheckedChange:S=>m("assignmentType",S?"Purchase":""),"data-testid":"checkbox-assignment-purchase"}),e.jsx("span",{className:"text-slate-700",children:"Purchase Transaction"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"assignment-refinance",checked:d.assignmentType==="Refinance",onCheckedChange:S=>m("assignmentType",S?"Refinance":""),"data-testid":"checkbox-assignment-refinance"}),e.jsx("span",{className:"text-slate-700",children:"Refinance Transaction"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"assignment-other",checked:d.assignmentType==="Other",onCheckedChange:S=>m("assignmentType",S?"Other":""),"data-testid":"checkbox-assignment-other"}),e.jsx("span",{className:"text-slate-700",children:"Other (describe)"})]}),e.jsx(ze,{placeholder:"",className:"h-10 text-sm bg-slate-50 border-slate-200 flex-1 max-w-[200px]","data-testid":"input-assignment-other-describe"})]})]}),!d.assignmentType&&e.jsx("p",{className:"text-xs text-red-500 -mt-4",children:"Select one"}),e.jsxs("div",{className:"grid grid-cols-12 gap-4",children:[e.jsxs("div",{className:"col-span-4",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Lender/Client ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:l("subject.Lender Client"),value:d.lenderClient,onChange:S=>m("lenderClient",S.target.value),className:`mt-1 h-10 text-sm ${f("lenderClient")}`,"data-testid":"input-lender-client"}),h("lenderClient")&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Required"})]}),e.jsxs("div",{className:"col-span-6",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Address"}),e.jsx(ze,{ref:l("subject.Lender Address"),value:d.lenderAddress,onChange:S=>m("lenderAddress",S.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-lender-address"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Is the subject property currently offered for sale or has it been offered for sale in the twelve months prior to the effective date of this appraisal?"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"offered-yes","data-testid":"checkbox-offered-yes"}),e.jsx("span",{className:"text-slate-700",children:"Yes"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"offered-no",defaultChecked:!0,"data-testid":"checkbox-offered-no"}),e.jsx("span",{className:"text-slate-700",children:"No"})]})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Report data source(s) used, offering price(s), and date(s). ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(yi,{ref:l("subject.Offering Data Sources"),placeholder:"Enter data sources, offering prices, and dates...",className:"mt-1 min-h-[60
11px] text-sm bg-slate-50 border-slate-200","data-testid":"input-offering-data-sources"})]})]})]})}function hG({orderData:t,propertyData:a,onChange:s,registerFieldRef:r,orderId:n}){const i=o.useCallback(f=>v=>{r&&r(f,v)},[r]),l=f=>f?typeof f=="object"&&"value"in f?f.value||"":String(f):"",[c,d]=o.useState("refinance"),[p,u]=o.useState({contractPrice:"",contractDate:"",seller:"",didAnalyze:!0,analysisExplanation:"Arm's length transaction.",sellerIsOwner:!0,dataSource:"",hasFinancialAssistance:!1,financialAssistanceDesc:""});o.useEffect(()=>{if(t||a){const f=l(t?.assignmentType);(f==="Purchase Transaction"||f==="Purchase")&&d("purchase");const v={};l(t?.contractPrice)&&(v.contractPrice=l(t.contractPrice)),l(t?.contractDate)&&(v.contractDate=l(t.contractDate)),l(t?.owner)&&(v.seller=l(t.owner)),l(t?.offeredForSaleDataSource)&&(v.dataSource=l(t.offeredForSaleDataSource)),t?.financialAssistance?.value===!0&&(v.hasFinancialAssistance=!0),l(t?.financialAssistanceAmount)&&(v.financialAssistanceDesc=l(t.financialAssistanceAmount)),u(S=>({...S,...v})),Object.entries(v).forEach(([S,N])=>{N!=null&&N!==""&&s(S,N)})}},[t,a]);const m=(f,v)=>{u(S=>({...S,[f]:v})),s(f,v)},h=c==="purchase";return e.jsxs("div",{className:"space-y-0",children:[e.jsxs("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg flex items-center justify-between",children:[e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Contract"}),e.jsxs("div",{className:"flex bg-blue-800 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>d("purchase"),className:`px-4 py-1.5 text-sm font-medium rounded-md transition-colors ${h?"bg-white text-slate-700 shadow-sm":"text-blue-200 hover:text-white"}`,"data-testid":"btn-purchase",children:"Purchase"}),e.jsx("button",{onClick:()=>d("refinance"),className:`px-4 py-1.5 text-sm font-medium rounded-md transition-colors ${h?"text-blue-200 hover:text-white":"bg-white text-slate-700 shadow-sm"}`,"data-testid":"btn-refinance",children:"Refinance / Other"})]})]}),e.jsx("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6",children:h?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center flex-wrap gap-2 text-sm",children:[e.jsx("span",{className:"text-slate-700",children:"I"}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer",children:[e.jsx(Pa,{checked:p.didAnalyze,onCheckedChange:f=>m("didAnalyze",f),"data-testid":"checkbox-contract-did"}),e.jsx("span",{className:p.didAnalyze?"font-medium text-slate-900":"text-slate-500",children:"did"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer",children:[e.jsx(Pa,{checked:!p.didAnalyze,onCheckedChange:f=>m("didAnalyze",!f),"data-testid":"checkbox-contract-didnot"}),e.jsx("span",{className:p.didAnalyze?"text-slate-500":"font-medium text-slate-900",children:"did not"})]}),e.jsx("span",{className:"text-slate-700",children:"analyze the contract for sale for the subject purchase transaction. Explain the results of the analysis of the contract for sale or why the analysis was not performed."})]}),e.jsx(yi,{value:p.analysisExplanation,onChange:f=>
11m("analysisExplanation",f.target.value),className:"min-h-[60px] text-sm bg-slate-50 border-slate-200","data-testid":"input-contract-analysis"})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-4",children:[e.jsxs("div",{className:"col-span-3",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Contract Price $ ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:i("contract.Contract Price"),value:p.contractPrice,onChange:f=>m("contractPrice",f.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-contract-price"})]}),e.jsxs("div",{className:"col-span-3",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Date of Contract ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:i("contract.Date of Contract"),value:p.contractDate,onChange:f=>m("contractDate",f.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-contract-date"})]}),e.jsxs("div",{className:"col-span-6 flex items-end gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 whitespace-nowrap",children:"Is the property seller the owner of public record?"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{checked:p.sellerIsOwner,onCheckedChange:f=>m("sellerIsOwner",f),"data-testid":"checkbox-seller-owner-yes"}),e.jsx("span",{className:"text-slate-700",children:"Yes"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{checked:!p.sellerIsOwner,onCheckedChange:f=>m("sellerIsOwner",!f),"data-testid":"checkbox-seller-owner-no"}),e.jsx("span",{className:"text-slate-700",children:"No"})]})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Data Source(s)"}),e.jsx(ze,{ref:i("contract.Data Source"),value:p.dataSource,onChange:f=>m("dataSource",f.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-seller-owner-source"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center flex-wrap gap-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Is there any financial assistance (loan charges, sale concessions, gift or downpayment assistance, etc.) to be paid by any party on behalf of the borrower?"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{checked:p.hasFinancialAssistance,onCheckedChange:f=>m("hasFinancialAssistance",f),"data-testid":"checkbox-financial-yes"}),e.jsx("span",{className:"text-slate-700",children:"Yes"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{checked:!p.hasFinancialAssistance,onCheckedChange:f=>m("hasFinancialAssistance",!f),"data-testid":"checkbox-financial-no"}),e.jsx("span",{className:"text-slate-700",children:"No"})]})]})]}),e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"If Yes, report the total dollar amount and describe the items to be paid."}),e.jsx(yi,{value:p.financialAssistanceDesc,onChange:f=>m("financialAssistanceDesc",f.target.value),placeholder:"Description of financial assistance...",className:"min-h-[60
11px] text-sm bg-slate-50 border-slate-200","data-testid":"input-financial-assistance"})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(kr,{className:"h-6 w-6 text-green-600 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Not a Purchase Transaction"}),e.jsx("span",{className:"px-2 py-0.5 bg-slate-100 text-slate-600 text-xs font-medium rounded",children:"Refinance / Other"})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-1",children:"This appraisal is for a refinance or other non-purchase transaction."}),e.jsx("p",{className:"text-sm text-slate-600",children:'Contract analysis is not applicable - "Did Not" will be marked on the form.'})]})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg border border-slate-200 p-4 mt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-slate-700",children:"I"}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer",children:[e.jsx(Pa,{disabled:!0,className:"opacity-50"}),e.jsx("span",{className:"text-slate-400",children:"did"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer",children:[e.jsx(Pa,{defaultChecked:!0,disabled:!0}),e.jsx("span",{className:"font-medium text-slate-700",children:"did not"})]}),e.jsx("span",{className:"text-slate-700",children:"analyze the contract for sale for the subject purchase transaction."})]}
11),e.jsx(yi,{className:"mt-3 min-h-[60px] text-sm bg-white border-slate-200",value:"This is not a purchase transaction. Contract analysis was not performed.",disabled:!0})]})]})})]})}function fG({propertyData:t,marketLabState:a,onChange:s,registerFieldRef:r}){const n=o.useCallback(p=>u=>{r&&r(p,u)},[r]),i=a?.neighborhoodGrid,[l,c]=o.useState({location:i?.location||"Suburban",builtUp:i?.builtUp||"Over75",growth:i?.growth||"Stable",propertyValues:i?.propertyValues||"Stable",demandSupply:i?.demandSupply||"InBalance",marketingTime:i?.marketingTime||"3to6Months",priceLow:i?.priceLow?.toString()||"",priceHigh:i?.priceHigh?.toString()||"",pricePred:i?.pricePredominant?.toString()||"",ageLow:i?.ageLow?.toString()||"",ageHigh:i?.ageHigh?.toString()||"",agePred:i?.agePredominant?.toString()||"",landuseOneUnit:i?.landUseOneUnit?.toString()||"75",landuse24Unit:i?.landUseTwoToFour?.toString()||"10",landuseMultifamily:i?.landUseMultiFamily?.toString()||"5",landuseCommercial:i?.landUseCommercial?.toString()||"5",landuseOther:i?.landUseOther?.toString()||"5",boundaries:i?.neighborhoodBoundaries||"",description:i?.neighborhoodDescription||"",marketConditions:i?.marketConditions||""});o.useEffect(()=>{if(!i)return;const p={};i.location&&(p.location=i.location),i.builtUp&&(p.builtUp=i.builtUp),i.growth&&(p.growth=i.growth),i.propertyValues&&(p.propertyValues=i.propertyValues),i.demandSupply&&(p.demandSupply=i.demandSupply),i.marketingTime&&(p.marketingTime=i.marketingTime),i.priceLow&&(p.priceLow=i.priceLow.toString()),i.priceHigh&&(p.priceHigh=i.priceHigh.toString()),i.pricePredominant&&(p.pricePred=i.pricePredominant.toString()),i.ageLow&&(p.ageLow=i.ageLow.toString()),i.ageHigh&&(p.ageHigh=i.ageHigh.toString()),i.agePredominant&&(p.agePred=i.agePredominant.toString()),i.landUseOneUnit&&(p.landuseOneUnit=i.landUseOneUnit.toString()),i.landUseTwoToFour&&(p.landuse24Unit=i.landUseTwoToFour.toString()),i.landUseMultiFamily&&(p.landuseMultifamily=i.landUseMultiFamily.toString()),i.landUseCommercial&&(p.landuseCommercial=i.landUseCommercial.toString()),i.landUseOther&&(p.landuseOther=i.landUseOther.toString()),i.neighborhoodBoundaries&&(p.boundaries=i.neighborhoodBoundaries),i.neighborhoodDescription&&(p.description=i.neighborhoodDescription),i.marketConditions&&(p.marketConditions=i.marketConditions),c(u=>({...u,...p})),Object.entries(p).forEach(([u,m])=>{s(u,m)})},[i]);const d=(p,u)=>{c(m=>({...m,[p]:u})),s(p,u)};return e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Neighborhood"})}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"Neighborhood Characteristics"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 block mb-2",children:"Location"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"location-urban",checked:l.location==="Urban",onCheckedChange:()=>d("location","Urban"),"data-testid":"checkbox-location-urban"}),e.jsx("span",{className:"text-slate-700",children:"Urban"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"location-suburban",checked:l.location==="Suburban",onCheckedChange:()=>d("location","Suburban"),"data-testid":"checkbox-location-suburban"}),e.jsx("span",{className:"text-slate-700",children:"Suburban"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"location-rural",checked:l.location==="Rural",onCheckedChange:()=>d("location","Rural"),"data-testid":"checkbox-location-rural"}),e.jsx("span",{className:"text-slate-700",children:"Rural"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 block mb-2",children:"Built-Up"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"builtup-over75",checked:l.builtUp==="Over75",onCheckedChange:()=>d("builtUp","Over75"),"data-testid":"checkbox-builtup-over75"}),e.jsx("span",{className:"text-slate-700",children:"Over 75%"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"builtup-25-75",checked:l.builtUp==="25to75",onCheckedChange:()=>d("builtUp","25to75"),"data-testid":"checkbox-builtup-25-75"}),e.jsx("span",{className:"text-slate-700",children:"25-75%"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"builtup-under25",checked:l.builtUp==="Under25",onCheckedChange:()=>d("builtUp","Under25"),"data-testid":"checkbox-builtup-under25"}),e.jsx("span",{className:"text-slate-700",children:"Under 25%"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 block mb-2",children:"Growth"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"growth-rapid",checked:l.growth==="Rapid",onCheckedChange:()=>d("growth","Rapid"),"data-testid":"checkbox-growth-rapid"}),e.jsx("span",{className:"text-slate-700",children:"Rapid"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"growth-stable",checked:l.growth==="Stable",onCheckedChange:()=>d("growth","Stable"),"data-testid":"checkbox-growth-stable"}),e.jsx("span",{className:"text-slate-700",children:"Stable"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"growth-slow",checked:l.growth==="Slow",onCheckedChange:()=>d("growth","Slow"),"data-testid":"checkbox-growth-slow"}),e.jsx("span",{className:"text-slate-700",children:"Slow"})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"One-Unit Housing Trends"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 block mb-2",children:"Property Values"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"values-increasing",checked:l.propertyValues==="Increasing",onCheckedChange:()=>d("propertyValues","Increasing"),"data-testid":"checkbox-values-increasing"}),e.jsx("span",{className:"text-slate-700",children:"Increasing"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"values-stable",checked:l.propertyValues==="Stable",onCheckedChange:()=>d("propertyValues","Stable"),"data-testid":"checkbox-values-stable"}),e.jsx("span",{className:"text-slate-700",children:"Stable"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"values-declining",checked:l.propertyValues==="Declining",onCheckedChange:()=>d("propertyValues","Declining"),"data-testid":"checkbox-values-declining"}),e.jsx("span",{className:"text-slate-700",children:"Declining"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 block mb-2",children:"Demand/Supply"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"demand-shortage",checked:l.demandSupply==="Shortage",onCheckedChange:()=>d("demandSupply","Shortage"),"data-testid":"checkbox-demand-shortage"}),e.jsx("span",{className:"text-slate-700",children:"Shortage"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"demand-balance",checked:l.demandSupply==="InBalance",onCheckedChange:()=>d("demandSupply","InBalance"),"data-testid":"checkbox-demand-balance"}),e.jsx("span",{className:"text-slate-700",children:"In Balance"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"demand-oversupply",checked:l.demandSupply==="OverSupply",onCheckedChange:()=>d("demandSupply","OverSupply"),"data-testid":"checkbox-demand-oversupply"}),e.jsx("span",{className:"text-slate-700",children:"Over Supply"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 block mb-2",children:"Marketing Time"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"marketing-under3",checked:l.marketingTime==="Under3Months",onCheckedChange:()=>d("marketingTime","Under3Months"),"data-testid":"checkbox-marketing-under3"}),e.jsx("span",{className:"text-slate-700",children:"Under 3 mths"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"marketing-3-6",checked:l.marketingTime==="3to6Months",onCheckedChange:()=>d("marketingTime","3to6Months"),"data-testid":"checkbox-marketing-3-6"}),e.jsx("span",{className:"text-slate-700",children:"3-6 mths"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"marketing-over6",checked:l.marketingTime==="Over6Months",onCheckedChange:()=>d("marketingTime","Over6Months"),"data-testid":"checkbox-marketing-over6"}),e.jsx("span",{className:"text-slate-700",children:"Over 6 mths"})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"One-Unit Housing"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Price Low ($000)"}),e.jsx(ze,{value:l.priceLow,onChange:p=>d("priceLow",p.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-price-low"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Price High ($000)"}),e.jsx(ze,{value:l.priceHigh,onChange:p=>d("priceHigh",p.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-price-high"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Price Pred. ($000)"}),e.jsx(ze,{value:l.pricePred,onChange:p=>d("pricePred",p.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-price-pred"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Age Low (Yrs)"}),e.jsx(ze,{value:l.ageLow,onChange:p=>d("ageLow",p.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-age-low"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Age High (Yrs)"}),e.jsx(ze,{value:l.ageHigh,onChange:p=>d("ageHigh",p.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-age-high"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Age Pred. (Yrs)"}),e.jsx(ze,{value:l.agePred,onChange:p=>d("agePred",p.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-age-pred"})]})]})]})]}),e.jsxs("div",{className:"border-t border-slate-200 pt-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider mb-3",children:"Present Land Use %"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 
11whitespace-nowrap",children:"One-Unit"}),e.jsx(ze,{value:l.landuseOneUnit,onChange:p=>d("landuseOneUnit",p.target.value),className:"w-16 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-landuse-oneunit"}),e.jsx("span",{className:"text-xs text-slate-500",children:"%"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 whitespace-nowrap",children:"2-4 Unit"}),e.jsx(ze,{value:l.landuse24Unit,onChange:p=>d("landuse24Unit",p.target.value),className:"w-16 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-landuse-2-4unit"}),e.jsx("span",{className:"text-xs text-slate-500",children:"%"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 whitespace-nowrap",children:"Multi-Family"}),e.jsx(ze,{value:l.landuseMultifamily,onChange:p=>d("landuseMultifamily",p.target.value),className:"w-16 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-landuse-multifamily"}),e.jsx("span",{className:"text-xs text-slate-500",children:"%"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 whitespace-nowrap",children:"Commercial"}),e.jsx(ze,{value:l.landuseCommercial,onChange:p=>d("landuseCommercial",p.target.value),className:"w-16 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-landuse-commercial"}),e.jsx("span",{className:"text-xs text-slate-500",children:"%"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 whitespace-nowrap",children:"Other"}),e.jsx(ze,{value:l.landuseOther,onChange:p=>d("landuseOther",p.target.value),className:"w-16 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-landuse-other"}),e.jsx("span",{className:"text-xs text-slate-500",children:"%"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Neighborhood Boundaries"}),e.jsx(yi,{ref:n("neighborhood.Neighborhood Boundaries"),value:l.boundaries,onChange:p=>d("boundaries",p.target.value),placeholder:"North, South, East, West boundaries...",className:"mt-1 min-h-[60px] text-sm bg-slate-50 border-slate-200","data-testid":"input-neighborhood-boundaries"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Neighborhood Description"}),e.jsx(yi,{ref:n("neighborhood.Neighborhood Description"),value:l.description,onChange:p=>d("description",p.target.value),placeholder:"Describe neighborhood characteristics...",className:"mt-1 min-h-[80px] text-sm bg-slate-50 border-slate-200","data-testid":"input-neighborhood-description"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Market Conditions"}),e.jsx(yi,{ref:n("neighborhood.Market Conditions"),value:l.marketConditions,onChange:p=>d("marketConditions",p.target.value),placeholder:"Describe market conditions (including support for the above conclusions)...",className:"mt-1 min-h-[80px] text-sm bg-slate-50 border-slate-200","data-testid":"input-market-conditions"})]})]})]})]})}function gG({propertyData:t,onChange:a,registerFieldRef:s}){const r=o.useCallback(d=>p=>{s&&s(d,p)},[s]),n=d=>d?typeof d=="object"&&"value"in d?d.value||"":String(d):"",[i,l]=o.useState({dimensions:"",lotSize:"",shape:"Rectangular",view:"Residential",zoningClassification:"",zoningDescription:"Single Family Residential",femaZone:"X",femaMapNumber:"",femaMapDate:""});o.useEffect(()=>{if(t){const d={};n(t?.lotDimensions)&&(d.dimensions=n(t.lotDimensions)),n(t?.lotSize)&&(d.lotSize=n(t.lotSize)),n(t?.lotShape)&&(d.shape=n(t.lotShape)),n(t?.view)&&(d.view=n(t.view)),n(t?.zoningClassification)&&(d.zoningClassification=n(t.zoningClassification)),n(t?.zoningDescription)&&(d.zoningDescription=n(t.zoningDescription)),n(t?.femaFloodZone)&&(d.femaZone=n(t.femaFloodZone)),n(t?.femaMapNumber)&&(d.femaMapNumber=n(t.femaMapNumber)),n(t?.femaMapDate)&&(d.femaMap
11Date=n(t.femaMapDate)),l(p=>({...p,dimensions:d.dimensions||p.dimensions,lotSize:d.lotSize||p.lotSize,shape:d.shape||p.shape,view:d.view||p.view,zoningClassification:d.zoningClassification||p.zoningClassification,zoningDescription:d.zoningDescription||p.zoningDescription,femaZone:d.femaZone||p.femaZone,femaMapNumber:d.femaMapNumber||p.femaMapNumber,femaMapDate:d.femaMapDate||p.femaMapDate})),Object.entries(d).forEach(([p,u])=>{a(p,u)})}},[t]);const c=(d,p)=>{l(u=>({...u,[d]:p})),a(d,p)};return e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Site"})}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-4",children:[e.jsxs("div",{className:"col-span-3",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Dimensions"}),e.jsx(ze,{value:i.dimensions,onChange:d=>c("dimensions",d.target.value),placeholder:"75 x 100",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-dimensions"})]}),e.jsxs("div",{className:"col-span-3",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Area"}),e.jsx(ze,{value:i.lotSize,onChange:d=>c("lotSize",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-lot-area"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Shape"}),e.jsx(ze,{value:i.shape,onChange:d=>c("shape",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-shape"})]}),e.jsxs("div",{className:"col-span-4",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"View"}),e.jsx(ze,{value:i.view,onChange:d=>c("view",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-view"})]})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-4 items-end",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Zoning Classification ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:r("site.Specific Zoning Classification"),value:i.zoningClassification,onChange:d=>c("zoningClassification",d.target.value),className:`mt-1 h-10 text-sm bg-slate-50 ${i.zoningClassification?"border-slate-200":"border-red-300"}`,"data-testid":"input-zoning-classification"}),!i.zoningClassification&&e.jsx("p",{className:"text-xs text-red-500 mt-1",children:"Zoning Classification is required"})]}),e.jsxs("div",{className:"col-span-4",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Zoning Description"}),e.jsx(ze,{ref:r("site.Zoning Description"),value:i.zoningDescription,onChange:d=>c("zoningDescription",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-zoning-description"})]}),e.jsxs("div",{className:"col-span-6",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 block mb-2",children:"Zoning Compliance"}),e.jsxs("div",{className:"flex items-center gap-4 h-10",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"zoning-legal",defaultChecked:!0,"data-testid":"checkbox-zoning-legal"}),e.jsx("span",{className:"text-slate-700",children:"Legal"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"zoning-nonconforming","data-testid":"checkbox-zoning-nonconforming"}),e.jsx("span",{className:"text-slate-700",children:"Legal Non-Conforming"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"zoning-illegal","data-testid":"checkbox-zoning-illegal"}),e.jsx("span",{className:"text-slate-700",children:"Illegal"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Is the highest and best use of the subject property as improved (or as proposed per plans and specifications) the present use?"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"hbu-yes",defaultChecked:!0,"data-testid":"checkbox-hbu-yes"}),e.jsx("span",{className:"text-slate-700",children:"Yes"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"hbu-no","data-testid":"checkbox-hbu-no"}),e.jsx("span",{className:"text-slate-700",children:"No"})]})]}),e.jsx(ze,{placeholder:"If No, describe",className:"h-10 text-sm bg-slate-50 border-slate-200 flex-1 max-w-[300px]","data-testid":"input-hbu-describe"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-6 border-t border-slate-200 pt-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider mb-3",children:"Utilities"}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-slate-200",children:[e.jsx("th",{className:"text-left py-2 font-semibold text-slate-500 text-xs w-32"}),e.jsx("th",{className:"text-center py-2 font-semibold text-slate-500 text-xs",children:"Public"}),e.jsx("th",{className:"text-center py-2 font-semibold text-slate-500 text-xs",children:"Other"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-slate-100",children:[e.jsx("td",{className:"py-3 text-slate-700",children:"Electricity"}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"elec-public",defaultChecked:!0,"data-testid":"checkbox-elec-public"})}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"elec-other","data-testid":"checkbox-elec-other"})})]}),e.jsxs("tr",{className:"border-b border-slate-100",children:[e.jsx("td",{className:"py-3 text-slate-700",children:"Gas"}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"gas-public",defaultChecked:!0,"data-testid":"checkbox-gas-public"})}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"gas-other","data-testid":"checkbox-gas-other"})})]}),e.jsxs("tr",{className:"border-b border-slate-100",children:[e.jsx("td",{className:"py-3 text-slate-700",children:"Water"}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"water-public",defaultChecked:!0,"data-testid":"checkbox-water-public"})}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"water-other","data-testid":"checkbox-water-other"})})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"py-3 text-slate-700",children:"Sanitary Sewer"}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"sewer-public",defaultChecked:!0,"data-testid":"checkbox-sewer-public"})}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"sewer-other","data-testid":"checkbox-sewer-other"})})]})]})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider mb-3",children:"Off-site Improvements"}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-slate-200",children:[e.jsx("th",{className:"text-left py-2 font-semibold text-slate-500 text-xs w-32",children:"Type"}),e.jsx("th",{className:"text-center py-2 font-semibold text-slate-500 text-xs",children:"Public"}),e.jsx("th",{className:"text-center py-2 font-semibold text-slate-500 text-xs",children:"Private"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-slate-100",children:[e.jsx("td",{className:"py-3 text-slate-700",children:"Street"}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"street-public",defaultChecked:!0,"data-testid":"checkbox-street-public"})}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"street-private","data-testid":"checkbox-street-private"})})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"py-3 text-slate-700",children:"Alley"}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"alley-public","data-testid":"checkbox-alley-public"})}),e.jsx("td",{className:"py-3 text-center",children:e.jsx(Pa,{id:"alley-private","data-testid":"checkbox-alley-private"})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-4 border-t border-slate-200 pt-4 items-end",children:[e.jsxs("div",{className:"col-span-3",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 block mb-2",children:"FEMA Special Flood Hazard Area"}),e.jsxs("div",{className:"flex items-center gap-3 h-10",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"fema-yes","data-testid":"checkbox-fema-yes"}),e.jsx("span",{className:"text-slate-700",children:"Yes"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"fema-no",defaultChecked:!0,"data-testid":"checkbox-fema-no"}),e.jsx("span",{className:"text-slate-700",children:"No"})]})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"FEMA Flood Zone"}),e.jsx(ze,{value:i.femaZone,onChange:d=>c("femaZone",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-fema-zone"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"FEMA Map Date"}
11),e.jsx(ze,{value:i.femaMapDate,onChange:d=>c("femaMapDate",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-fema-date"})]}),e.jsxs("div",{className:"col-span-3",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"FEMA Map Number"}),e.jsx(ze,{value:i.femaMapNumber,onChange:d=>c("femaMapNumber",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-fema-number"})]})]}),e.jsxs("div",{className:"border-t border-slate-200 pt-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Are there any adverse site conditions or external factors (easements, encroachments, environmental conditions, land uses, etc.)?"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"adverse-yes","data-testid":"checkbox-adverse-yes"}),e.jsx("span",{className:"text-slate-700",children:"Yes"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"adverse-no",defaultChecked:!0,"data-testid":"checkbox-adverse-no"}),e.jsx("span",{className:"text-slate-700",children:"No"})]})]})]}),e.jsx(yi,{placeholder:"Describe any adverse site conditions...",className:"min-h-[60
11px] text-sm bg-slate-50 border-slate-200","data-testid":"input-adverse-conditions"})]})]})]})}function xG({propertyData:t,onChange:a,registerFieldRef:s}){const r=o.useCallback(d=>p=>{s&&s(d,p)},[s]),n=d=>d?typeof d=="object"&&"value"in d?d.value||"":String(d):"",[i,l]=o.useState({stories:"2",type:"Det.",design:"Colonial",existingConstructed:"Existing",yearBuilt:"1995",effectiveAge:"20",foundation:"Poured Concrete",exteriorWalls:"Brick/Frame",roofSurface:"Asphalt Shingle",heating:"FWA",heatingFuel:"Gas",cooling:"Central Air",basementArea:"1,000",basementFinished:"50",gla:"",bedrooms:"",fullBaths:"",halfBaths:"",garageCars:""});o.useEffect(()=>{if(!t)return;const d={};n(t?.yearBuilt)&&(d.yearBuilt=n(t.yearBuilt)),n(t?.gla)&&(d.gla=n(t.gla)),n(t?.bedrooms)&&(d.bedrooms=n(t.bedrooms)),n(t?.fullBaths)&&(d.fullBaths=n(t.fullBaths)),n(t?.halfBaths)&&(d.halfBaths=n(t.halfBaths)),n(t?.garageCars)&&(d.garageCars=n(t.garageCars)),l(p=>({...p,...d})),Object.entries(d).forEach(([p,u])=>{a(p,u)})},[t]);const c=(d,p)=>{l(u=>({...u,[d]:p})),a(d,p)};return e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Improvements"})}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"# of Units"}),e.jsx(ze,{defaultValue:"1",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-units"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"# of Stories"}),e.jsx(ze,{value:i.stories,onChange:d=>c("stories",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-stories"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Type"}),e.jsx(ze,{value:i.type,onChange:d=>c("type",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-type"})]}),e.jsxs("div",{className:"col-span-3",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Design (Style)"}),e.jsx(ze,{value:i.design,onChange:d=>c("design",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-design"})]}),e.jsxs("div",{className:"col-span-3",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500 block mb-2",children:"Existing/Proposed"}),e.jsxs("div",{className:"flex items-center gap-4 h-10",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"existing",defaultChecked:!0,"data-testid":"checkbox-existing"}),e.jsx("span",{className:"text-slate-700",children:"Existing"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"proposed","data-testid":"checkbox-proposed"}),e.jsx("span",{className:"text-slate-700",children:"Proposed"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"under-const","data-testid":"checkbox-under-const"}),e.jsx("span",{className:"text-slate-700",children:"Under Const."})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-12 gap-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Year Built ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:r("improvements.Year Built"),value:i.yearBuilt,onChange:d=>c("yearBuilt",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-year-built"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Effective Age (Yrs) ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:r("improvements.Effective Age"),value:i.effectiveAge,onChange:d=>c("effectiveAge",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-effective-age"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-6 border-t border-slate-200 pt-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"Exterior Description"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Foundation"}),e.jsx(ze,{value:i.foundation,onChange:d=>c("foundation",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-foundation"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Exterior Walls"}),e.jsx(ze,{value:i.exteriorWalls,onChange:d=>c("exteriorWalls",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-exterior-walls"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Roof Surface"}),e.jsx(ze,{value:i.roofSurface,onChange:d=>c("roofSurface",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-roof-surface"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Gutters & Dwnspots"}),e.jsx(ze,{defaultValue:"Aluminum",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-gutters"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Window Type"}),e.jsx(ze,{defaultValue:"Double Hung",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-window-type"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Storm Sash/Insul."}),e.jsx(ze,{defaultValue:"Insulated Glass",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-storm-sash"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Screens"}),e.jsx(ze,{defaultValue:"Yes",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-screens"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"Foundation"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"foundation-slab","data-testid":"checkbox-foundation-slab"}),e.jsx("span",{className:"text-slate-700",children:"Concrete Slab"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"foundation-crawl","data-testid":"checkbox-foundation-crawl"}),e.jsx("span",{className:"text-slate-700",children:"Crawl Space"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"foundation-full",defaultChecked:!0,"data-testid":"checkbox-foundation-full"}),e.jsx("span",{className:"text-slate-700",children:"Full Basement"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"foundation-partial","data-testid":"checkbox-foundation-partial"}),e.jsx("span",{className:"text-slate-700",children:"Partial Basement"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Basement Area (sq ft)"}),e.jsx(ze,{value:i.basementArea,onChange:d=>c("basementArea",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-basement-area"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Basement % Finished"}),e.jsx(ze,{value:i.basementFinished,onChange:d=>c("basementFinished",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-basement-finished"})]}),e.jsxs("div",{className:"pt-2 border-t border-slate-200 space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"outside-entry","data-testid":"checkbox-outside-entry"}),e.jsx("span",{className:"text-slate-700",children:"Outside Entry/Exit"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"sump-pump","data-testid":"checkbox-sump-pump"}),e.jsx("span",{className:"text-slate-700",children:"Sump Pump"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"dampness","data-testid":"checkbox-dampness"}),e.jsx("span",{className:"text-slate-700",children:"Dampness"})]})]}),e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider pt-2",children:"Infestation"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"termites","data-testid":"checkbox-termites"}),e.jsx("span",{className:"text-slate-700",children:"Termites"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"settlement","data-testid":"checkbox-settlement"}),e.jsx("span",{className:"text-slate-700",children:"Settlement"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"Interior"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Floors"}),e.jsx(ze,{defaultValue:"Hardwood/Carpet",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-floors"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Walls"}),e.jsx(ze,{defaultValue:"Drywall",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-walls"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Trim/Finish"}),e.jsx(ze,{defaultValue:"Wood",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-trim-finish"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Bath Floor"}),e.jsx(ze,{defaultValue:"Ceramic Tile",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-bath-floor"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Bath Wainscot"}),e.jsx(ze,{defaultValue:"Ceramic Tile",className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-bath-wainscot"})]}),e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider pt-2",children:"Heating & Cooling"}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Type"}),e.jsx(ze,{value:i.heating,onChange:d=>c("heating",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-heating"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Fuel"}),e.jsx(ze,{value:i.heatingFuel,onChange:d=>c("heatingFuel",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-heating-fuel"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Cooling"}),e.jsx(ze,{value:i.cooling,onChange:d=>c("cooling",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-cooling"})]})]})]}),e.jsxs("div",{className:"border-t border-slate-200 pt-4",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Additional features (special energy efficie
11nt items, etc.)"}),e.jsx(yi,{placeholder:"Describe additional features...",className:"mt-1 min-h-[80px] text-sm bg-slate-50 border-slate-200","data-testid":"input-additional-features"})]}),e.jsxs("div",{className:"border-t border-slate-200 pt-4",children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Describe the condition of the property (including needed repairs, deterioration, renovations, remodeling, etc.)"}),e.jsx(yi,{placeholder:"Describe condition...",className:"mt-1 min-h-[80px] text-sm bg-slate-50 border-slate-200","data-testid":"input-condition-description"})]})]})]})}function bG({propertyData:t,selectedComps:a,onChange:s,registerFieldRef:r}){o.useCallback(N=>x=>{r&&r(N,x)},[r]);const n=N=>N?typeof N=="object"&&"value"in N?N.value||"":String(N):"",i=a?.slice(0,6)||[];console.log("[SalesComparisonSectionForm] Received comps:",i.length,i);const[l,c]=o.useState(Math.max(i.length,2)),d=N=>{if(!N)return"";const x=typeof N=="string"?parseFloat(N.replace(/[^0-9.-]/g,"")):N;return isNaN(x)?"":`$ ${x.toLocaleString()}`},p=N=>{const x=parseFloat(n(t?.gla))||2882,y=n(t?.bedrooms)||"4",b=n(t?.fullBaths)||"2",j=n(t?.halfBaths)||"1",T=parseInt(n(t?.yearBuilt))||1995,O=n(t?.lotSize)||"7,500 sf",E=n(t?.garageCars)||"2",R=n(t?.basementArea)||n(t?.rawPublicRecordData?.BelowGradeTotalArea)||t?.rawPublicRecordData?.BelowGradeTotalArea||"",G=n(t?.basementFinish)||n(t?.rawPublicRecordData?.BelowGradeFinishedArea)||t?.rawPublicRecordData?.BelowGradeFinishedArea||"",U=n(t?.basement)||n(t?.mlsData?.basement)||t?.mlsData?.basement||"";console.log("[Subject] Basement data:",{basementArea:R,basementFinished:G,basementDescription:U});const C=(()=>{const A=uy(R,G,null,null);return console.log("[Subject] Formatted basement:",A),A==="0"?U||"None":A})();return{address:"1123 Birch Lane",proximity:"---",salePrice:d(45e4),pricePerGla:d(x>0?Math.round(45e4/x):225),dataSources:"MLS, Tax",verificationSources:"Doc #12345",salesFinancing:"---",concessions:"---",dateOfSale:"---",location:"Neutral",leaseholdFee:"Fee Simple",site:O,view:"Residential",design:"Colonial",quality:"Q3",actualAge:String(new Date().getFullYear()-T),condition:"C3",roomCount:`-|${y}|${b}.${j}`,gla:`${x.toLocaleString()} sf`,basement:C,roomsBelowGrade:"",functionalUtility:"Average",heatingCooling:"FWA / CAC",energyEfficient:"None",garage:`${E} Car Att`,porchDeck:"Patio"}[N]||""},u=(N,x)=>{if(!N)return"";const y=N.gla||0,b=N.salePrice||0,j=N.pricePerSqFt||(y>0?Math.round(b/y):0),T=C=>N.cleanedFields&&Array.isArray(N.cleanedFields)?N.cleanedFields.find(A=>A.fieldKey===C)?.finalValue??null:null,O=N.view||N.viewComparison||T("view")||"N;Res",E=N.location||N.locationComparison||T("location")||"N;Res",R=N.quality||T("quality")||"",G=N.condition||T("condition")||"";return{address:N.address||"",proximity:N.proximityToSubject||N.proximity||"",salePrice:d(b),pricePerGla:d(j),dataSources:N.dataSources||"MLS",verificationSources:N.verificationSources||(N.mlsNumber?`MLS#${N.mlsNumber}`:"MLS"),salesFinancing:N.saleOrFinancingConcessions||"ArmLth",concessions:N.concessions||"None",dateOfSale:N.dateOfSale||"",daysOnMarket:N.daysOnMarket!==void 0&&N.daysOnMarket!==""?String(N.daysOnMarket):"",location:String(E),leaseholdFee:N.leaseholdFeeSimple||"Fee Simple",site:N.site||"",view:String(O),design:N.design||"",quality:String(R),actualAge:N.actualAge||"",condition:String(G),roomCount:N.aboveGradeTotal||"",gla:y?`${y.toLocaleString()} sf`:"",basement:N.basement||"None",roomsBelowGrade:N.belowGrade||"",functionalUtility:N.functionalUtility||"Average",heatingCooling:N.heatingCooling||"",energyEfficient:N.energyEfficient||"None",garage:N.garageCarport||"None",porchDeck:N.porchPatioDeck||"None"}[x]||""},m=[{id:"address",label:"Address",showAdjustment:!1},{id:"proximity",label:"Proximity to Subject",showAdjustment:!1},{id:"salePrice",label:"Sale Price",showAdjustment:!1},{id:"pricePerGla",label:"Sale Price / GLA",showAdjustment:!1},{id:"dataSources",label:"Data Source(s)",showAdjustment:!1},{id:"verificationSources",label:"Verification Source(s)",showAdjustment:!1},{id:"valueAdjustments",label:"VALUE ADJUSTMENTS",isHeader:!0},{id:"salesFinancing",label:"Sales or Financing",showAdjustment:!0},{id:"concessions",label:"Concessions",showAdjustment:!0},{id:"dateOfSale",label:"Date of Sale/Time",showAdjustment:!0},{id:"daysOnMarket",label:"Days on Market",showAdjustment:!1},{id:"location",label:"Location",showAdjustment:!0},{id:"leaseholdFee",label:"Leasehold/Fee Simple",showAdjustment:!0},{id:"site",label:"Site",showAdjustment:!0},{id:"view",label:"View",showAdjustment:!0},{id:"design",label:"Design (Style)",showAdjustment:!0},{id:"quality",label:"Quality of Construction",showAdjustment:!0},{id:"actualAge",label:"Actual Age",showAdjustment:!0},{id:"condition",label:"Condition",showAdjustment:!0},{id:"roomCount",label:"Above Grade Room Count",subLabel:"Total   Bdrms.   Baths",showAdjustment:!0},{id:"gla",label:"Gross Living Area",showAdjustment:!0},{id:"basement",label:"Basement & Finished",showAdjustment:!0},{id:"roomsBelowGrade",label:"Rooms Below Grade",showAdjustment:!0},{id:"functionalUtility",label:"Functional Utility",showAdjustment:!0},{id:"heatingCooling",label:"Heating/Cooling",showAdjustment:!0},{id:"energyEfficient",label:"Energy Efficient Items",showAdjustment:!0},{id:"garage",label:"Garage/Carport",showAdjustment:!0}
11,{id:"porchDeck",label:"Porch/Patio/Deck",showAdjustment:!0}],h=()=>{const N=[];for(let x=0;x<l;x++)N.push(e.jsx("th",{className:"text-left py-2 px-2 font-semibold text-slate-700 min-w-[140px]",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{children:["Comp ",x+1]}),x>0&&e.jsx("button",{onClick:()=>c(Math.max(1,l-1)),className:"p-1 hover:bg-slate-200 rounded",children:e.jsx(Ci,{className:"h-3 w-3 text-slate-400"})})]})},`comp-${x}-header`),e.jsx("th",{className:"text-center py-2 px-1 font-semibold text-slate-500 w-20",children:"+(-) $ Adjust"},`comp-${x}-adj`));return N},f=(N,x)=>{const y=[];for(let b=0;b<l;b++){const j=i[b];y.push(e.jsx("td",{className:"py-1 px-2",children:e.jsx(ze,{defaultValue:u(j,N.id),className:"h-7 text-xs bg-slate-50 border-slate-200","data-testid":`input-comp${b+1}-${N.id}`})},`comp-${b}-val-${x}`),e.jsx("td",{className:"py-1 px-1",children:N.showAdjustment!==!1&&e.jsx(ze,{defaultValue:N.id==="dateOfSale"&&b===0?"+5000":"0",className:"h-7 text-xs bg-slate-50 border-slate-200 text-right","data-testid":`input-comp${b+1}-${N.id}-adj`})},`comp-${b}-adj-${x}`))}return y},v=()=>{const N=[];for(let x=0;x<l;x++)N.push(e.jsx("td",{className:"py-1 px-2"},`net-${x}-val`),e.jsx("td",{className:"py-1 px-1",children:e.jsx(ze,{defaultValue:x===0?"+ 2,500":"0",className:"h-7 text-xs bg-white border-slate-200 text-right font-medium","data-testid":`input-comp${x+1}-net-adj`})},`net-${x}-adj`));return N},S=()=>{const N=[],x=[46e4,455e3,448e3];for(let y=0;y<l;y++){const j=i[y]?.adjustedPrice||x[y]||45e4;N.push(e.jsx("td",{className:"py-1 px-2"},`adj-${y}-val`),e.jsx("td",{className:"py-2 px-1",children:e.jsxs("div",{className:"text-right font-bold text-white",children:["$ ",j.toLocaleString()]})},`adj-${y}-price`))}return N};return e.jsxs("div",{className:"space-y-0",children:[e.jsxs("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg flex items-center justify-between",children:[e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Sales Comparison Approach"}),l<6&&e.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>c(l+1),className:"text-white hover:bg-blue-800 gap-1","data-testid":"btn-add-comparable",children:[e.jsx(un,{className:"h-4 w-4"}),"Add Comparable"]})]}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg overflow-hidden",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50 border-b border-slate-200",children:[e.jsx("th",{className:"text-left py-2 px-3 font-bold text-slate-700 w-[180px] uppercase tracking-wider",children:"Feature"}),e.jsx("th",{className:"text-left py-2 px-2 font-semibold text-slate-700 min-w-[140px] border-l border-slate-200",children:"Subject"}),h()]})}),e.jsxs("tbody",{children:[m.map((N,x)=>N.isHeader?e.jsx("tr",{className:"bg-slate-100 border-y border-slate-200",children:e.jsx("td",{colSpan:2+l*2,className:"py-2 px-3 font-bold text-slate-700 uppercase tracking-wider",children:N.label})},N.id):e.jsxs("tr",{className:x%2===0?"bg-white":"bg-slate-50/50",children:[e.jsxs("td",{className:"py-1 px-3 text-slate-600 font-medium border-r border-slate-100",children:[N.label,N.subLabel&&e.jsx("div",{className:"text-[10px] text-slate-400",children:N.subLabel})]}),e.jsx("td",{className:"py-1 px-2 border-r border-slate-100",children:e.jsx(ze,{defaultValue:p(N.id),className:"h-7 text-xs bg-slate-50 border-slate-200","data-testid":`input-subject-${N.id}`})}),f(N,x)]},N.id)),e.jsxs("tr",{className:"bg-slate-100 border-t-2 border-slate-300",children:[e.jsx("td",{className:"py-2 px-3 text-slate-700 font-bold",children:"Net Adjustment"}),e.jsx("td",{className:"py-1 px-2 text-slate-400",children:"---"}),v()]}),e.jsxs("tr",{className:"bg-blue-700 text-white",children:[e.jsx("td",{className:"py-2 px-3 font-bold",children:"Adjusted Sale Price"}),e.jsx("td",{className:"py-1 px-2",children:"---"}),S()]})]})]})}),e.jsxs("div",{className:"p-4 border-t border-slate-200",children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Summary of Sales Comparison Approach ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(yi,{placeholder:"Summary of sales comparison approach...",className:"mt-2 min-h-[80px] text-sm bg-slate-50 border-slate-200","data-testid":"input-sales-comparison-summary"})]})]})]})}function yG({data:t,onChange:a,registerFieldRef:s}){const r=o.useCallback(c=>d=>{s&&s(c,d)},[s]),n=(c,d)=>{a({...t,[c]:d})},i=c=>{const d=Number(c);
11return isNaN(d)||d===0?"":d.toLocaleString()},l=c=>{const d=c.replace(/[^0-9.-]/g,""),p=parseFloat(d);return isNaN(p)?0:p};return e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Reconciliation"})}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:"This appraisal is made:"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"appraisal-asis",defaultChecked:!0,"data-testid":"checkbox-appraisal-asis"}),e.jsx("span",{className:"text-slate-700",children:'"as is"'})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"appraisal-completion","data-testid":"checkbox-appraisal-completion"}),e.jsx("span",{className:"text-slate-700",children:"subject to completion per plans and specifications on the basis of a hypothetical condition that the improvements have been completed"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"appraisal-repairs","data-testid":"checkbox-appraisal-repairs"}),e.jsx("span",{className:"text-slate-700",children:"subject to the following repairs or alterations on the basis of a hypothetical condition that the repairs or alterations have been completed"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Pa,{id:"appraisal-inspection","data-testid":"checkbox-appraisal-inspection"}),e.jsx("span",{className:"text-slate-700",children:"subject to the following required inspection based on the extraordinary assumption that the condition or deficiency does not require alteration or repair"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Conditions of Appraisal"}),e.jsx(yi,{defaultValue:"The subject property is in average condition with no significant deferred maintenance noted. Value is supported by the sales comparison approach.",className:"mt-1 min-h-[80px] text-sm bg-slate-50 border-slate-200","data-testid":"input-conditions-appraisal"})]}),e.jsx("div",{className:"border-t border-slate-200 pt-6",children:e.jsxs("div",{className:"bg-slate-50 p-6 rounded-lg border border-slate-200",children:[e.jsx("p",{className:"text-sm text-slate-700 mb-4",children:"Based on a complete visual inspection of the interior and exterior areas of the subject property, defined scope of work, statement of assumptions and limiting conditions, and appraiser's certification, my (our) opinion of the market value, as defined, of the real property that is the subject of this report is:"}),e.jsxs("div",{className:"flex items-center gap-6 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Effective Date of Appraisal ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:r("reconciliation.Effective Date of Appraisal"),type:"date",value:t.effectiveDate||new Date().toISOString().split("T")[0],onChange:c=>n("effectiveDate",c.target.value),className:"mt-1 h-10 text-sm bg-white border-slate-200 w-44","data-testid":"input-effective-date"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Opinion of Market Value ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-lg font-medium",children:"$"}),e.jsx(ze,{ref:r("reconciliation.Opinion of Market Value"),value:i(t.finalOpinionOfValue),onChange:c=>n("finalOpinionOfValue",l(c.target.value)),className:`pl-8 h-12 text-xl font-bold text-blue-900 w-48 bg-white ${t.finalOpinionOfValue?"border-slate-200":"border-red-300"}`,placeholder:"0","data-testid":"input-final-value"})]})]})]}),(!t.finalOpinionOfValue||t.finalOpinionOfValue<=0)&&e.jsx("div",{className:"mt-4 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-800",children:"Final Opinion of Value is required to generate the PDF"})]})}),e.jsxs("div",{className:"border-t border-slate-200 pt-6",children:[e.jsx("div",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider mb-4",children:"Indicated Values Summary"}),e.jsxs("div",{className:"grid grid-cols-3 gap-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Indicated Value by Sales Comparison Approach"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:i(t.indicatedValueBySalesComparison),onChange:c=>n("indicatedValueBySalesComparison",l(c.target.value)),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-indicated-sales"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Indicated Value by Cost Approach"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:i(t.indicatedValueByCostApproach),onChange:c=>n("indicatedValueByCostApproach",l(c.target.value)),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-indicated-cost"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Indicated Value by Income Approach"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:i(t.indicatedValueByIncomeApproach),onChange:c=>n("indicatedValueByIncomeApproach",l(c.target.value)),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-indicated-income"})]})]})]})]})]})]})}function SG({costApproach:t,incomeApproach:a,onCostApproachChange:s,onIncomeApproachChange:r,propertyData:n,registerFieldRef:i}){o.useCallback(d=>p=>{i&&i(d,p)},[i]);const l=(d,p)=>{s({...t,[d]:p})},c=(d,p)=>{r({...a,[d]:p})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 bg-blue-50 border border-blue-200 rounded-lg",children:[e.jsx(on,{className:"h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-blue-900",children:"NOT REQUIRED BY FANNIE MAE"}),e.jsx("p",{className:"text-sm text-blue-700 mt-0.5",children:"Cost Approach and Income Approach sections are optional for most conventional appraisals. Complete these if required by the lender or if they support your value opinion."})]})]}),e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Cost Approach"})}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Provide adequate information for the lender/client to replicate the below cost figures and calculations."}),e.jsx(yi,{value:t.siteValueExplanation,onChange:d=>l("siteValueExplanation",d.target.value),placeholder:"Site value estimated via...",className:"mt-1 min-h-[80px] text-sm bg-slate-50 border-slate-200","data-testid":"input-site-value-explanation"})]}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Opinion of Site Value"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:t.opinionOfSiteValue,onChange:d=>l("opinionOfSiteValue",d.target.value),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-opinion-site-value"})]})]})}),e.jsxs("div",{className:"border-t border-slate-200 pt-6",children:[e.jsx("h3",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider mb-4",children:"Reproduction / Replacement Cost New"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Dwelling"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(ze,{value:t.dwellingSqFt,onChange:d=>l("dwellingSqFt",d.target.value),placeholder:"Sq.Ft.",className:"h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-dwelling-sqft"}),e.jsx("span",{className:"text-xs text-slate-500",children:"sf"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"@ $"}),e.jsx(ze,{value:t.dwellingCostPerSqFt,onChange:d=>l("dwellingCostPerSqFt",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-dwelling-cost"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"= $"}),e.jsx(ze,{value:t.dwellingTotal,onChange:d=>l("dwellingTotal",d.target.value),className:"mt-1 h-10 text-sm bg-white border-slate-200","data-testid":"input-dwelling-total"})]})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Basement"}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(ze,{value:t.basementSqFt,onChange:d=>l("basementSqFt",d.target.value),placeholder:"Sq.Ft.",className:"h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-basement-sqft"}),e.jsx("span",{className:"text-xs text-slate-500",children:"sf"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"@ $"}),e.jsx(ze,{value:t.basementCostPerSqFt,onChange:d=>l("basementCostPerSqFt",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-basement-cost"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"= $"}),e.jsx(ze,{value:t.basementTotal,onChange:d=>l("basementTotal",d.target.value),className:"mt-1 h-10 text-sm bg-white border-slate-200","data-testid":"input-basement-total"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 border-t border-slate-200 pt-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"As-is Value of Site Improvements"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:t.asIsValueSiteImprovements,onChange:d=>l("asIsValueSiteImprovements",d.target.value),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-as-is-value"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Total Estimate of Cost-New"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:t.totalEstimateCostNew,onChange:d=>l("totalEstimateCostNew",d.target.value),className:"pl-7 h-10 text-sm bg-white border-slate-200","data-testid":"input-total-cost-new"})]})]})]}),e.jsxs("div",{className:"border-t border-slate-200 pt-6",children:[e.jsx("h3",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider mb-4",children:"Less Depreciation"}),e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Physical"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}
11),e.jsx(ze,{value:t.depreciationPhysical,onChange:d=>l("depreciationPhysical",d.target.value),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-depreciation-physical"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Functional"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:t.depreciationFunctional,onChange:d=>l("depreciationFunctional",d.target.value),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-depreciation-functional"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"External"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:t.depreciationExternal,onChange:d=>l("depreciationExternal",d.target.value),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-depreciation-external"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Total"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:t.depreciationTotal,onChange:d=>l("depreciationTotal",d.target.value),className:"pl-7 h-10 text-sm bg-white border-slate-200","data-testid":"input-depreciation-total"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 border-t border-slate-200 pt-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Depreciated Cost of Improvements"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:t.depreciatedCostImprovements,onChange:d=>l("depreciatedCostImprovements",d.target.value),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-depreciated-cost"})]})]}),e.jsxs("div",{className:"bg-blue-50 p-4 rounded-lg border border-blue-200",children:[e.jsx("label",{className:"text-xs font-bold text-blue-900 uppercase tracking-wider",children:"Indicated Value by Cost Approach"}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-blue-700 text-lg font-medium",children:"$"}),e.jsx(ze,{value:t.indicatedValue,onChange:d=>l("indicatedValue",d.target.value),className:"pl-8 h-12 text-lg font-bold text-blue-900 bg-white border-blue-300","data-testid":"input-indicated-value-cost"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-4 border-t border-slate-200 pt-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Est. Remaining Economic Life (Years)"}),e.jsx(ze,{value:t.estimatedRemainingEconomicLife,onChange:d=>l("estimatedRemainingEconomicLife",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-economic-life"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Source of Cost Data"}),e.jsx(ze,{value:t.sourceOfCostData,onChange:d=>l("sourceOfCostData",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-cost-data-source"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Quality Rating from Cost Service"}),e.jsx(ze,{value:t.qualityRatingCostService,onChange:d=>l("qualityRatingCostService",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-quality-rating"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Effective Date of Cost Data"}),e.jsx(ze,{value:t.effectiveDateCostData,onChange:d=>l("effectiveDateCostData",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-cost-data-date"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Comments on Cost Approach"}),e.jsx(yi,{value:t.comments,onChange:d=>l("comments",d.target.value),className:"mt-1 min-h-[80px] text-sm bg-slate-50 border-slate-200","data-testid":"input-cost-approach-comments"})]})]})]}),e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Income Approach"})}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Estimated Monthly Market Rent"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-sm",children:"$"}),e.jsx(ze,{value:a.estimatedMarketRent,onChange:d=>c("estimatedMarketRent",d.target.value),className:"pl-7 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-market-rent"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs",children:"/mo"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"× Gross Rent Multiplier"}
11),e.jsx(ze,{value:a.grossRentMultiplier,onChange:d=>c("grossRentMultiplier",d.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-grm"})]}),e.jsxs("div",{className:"bg-blue-50 p-4 rounded-lg border border-blue-200",children:[e.jsx("label",{className:"text-xs font-bold text-blue-900 uppercase tracking-wider",children:"= Indicated Value"}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-blue-700 text-lg font-medium",children:"$"}),e.jsx(ze,{value:a.indicatedValue,onChange:d=>c("indicatedValue",d.target.value),className:"pl-8 h-12 text-lg font-bold text-blue-900 bg-white border-blue-300","data-testid":"input-indicated-value-income"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Summary of Income Approach (including support for market rent and GRM)"}),e.jsx(yi,{value:a.summary,onChange:d=>c("summary",d.target.value),placeholder:"Summary of income approach...",className:"mt-1 min-h-[80px] text-sm bg-slate-50 border-slate-200","data-testid":"input-income-approach-summary"})]})]})]})]})}function vG({appraiserInfo:t,onAppraiserInfoChange:a,registerFieldRef:s,orderId:r}){const n=o.useCallback(y=>b=>{s&&s(y,b)},[s]),[i,l]=o.useState("draw"),[c,d]=o.useState(!1),p=o.useRef(null),u=(y,b)=>{a({...t,[y]:b})},m=()=>{const y=p.current;if(!y)return;const b=y.getContext("2d");b&&(b.fillStyle="white",b.fillRect(0,0,y.width,y.height),b.strokeStyle="#1e3a5f",b.lineWidth=2,b.lineCap="round")};o.useEffect(()=>{i==="draw"&&m()},[i]);const h=y=>{d(!0);const b=p.current;if(!b)return;const j=b.getContext("2d");if(!j)return;const T=b.getBoundingClientRect();j.beginPath(),j.moveTo(y.clientX-T.left,y.clientY-T.top)},f=y=>{if(!c)return;const b=p.current;if(!b)return;const j=b.getContext("2d");if(!j)return;const T=b.getBoundingClientRect();j.lineTo(y.clientX-T.left,y.clientY-T.top),j.stroke()},v=()=>{d(!1),S()},S=()=>{const y=p.current;if(!y)return;const b=y.toDataURL("image/png");u("signatureImage",b)},N=()=>{m(),u("signatureImage","")},x=y=>{const b=y.target.files?.[0];if(b){const j=new FileReader;j.onload=T=>{u("signatureImage",T.target?.result)},j.readAsDataURL(b)}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Appraiser"})}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Appraiser Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:n("signature.Appraiser Name"),value:t.name,onChange:y=>u("name",y.target.value),className:`mt-1 h-10 text-sm bg-slate-50 ${t.name?"border-slate-200":"border-red-300"}`,"data-testid":"input-appraiser-name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Company Name"}),e.jsx(ze,{ref:n("signature.Company Name"),value:t.companyName,onChange:y=>u("companyName",y.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-company-name"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Phone"}),e.jsx(ze,{value:t.phone||"",onChange:y=>u("phone",y.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-appraiser-phone"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Company Address"}),e.jsx(ze,{value:t.companyAddress1||"",onChange:y=>u("companyAddress1",y.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-company-address1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"City, State, Zip"}),e.jsx(ze,{value:t.companyAddress2||"",onChange:y=>u("companyAddress2",y.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-company-address2"})]})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["State Certification # ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:n("signature.License Number"),value:t.licenseNumber,onChange:y=>u("licenseNumber",y.target.value),className:`mt-1 h-10 text-sm bg-slate-50 ${t.licenseNumber?"border-slate-200":"border-red-300"}`,"data-testid":"input-license-number"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["State ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:n("signature.License State"),value:t.licenseState,onChange:y=>u("licenseState",y.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200",maxLength:2,"data-testid":"input-license-state"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Expiration Date ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{ref:n("signature.License Expiration"),type:"date",value:t.licenseExpiration,onChange:y=>u("licenseExpiration",y.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-license-expiration"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-semibold text-slate-500",children:"Email"}),e.jsx(ze,{type:"email",value:t.email||"",onChange:y=>u("email",y.target.value),className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-appraiser-email"})]})]})]})]}),e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsxs("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:["Appraiser Signature ",e.jsx("span",{className:"text-red-300",children:"*"})]})}),e.jsxs("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsxs(De,{type:"button",variant:i==="draw"?"default":"outline",size:"sm",onClick:()=>l("draw"),className:i==="draw"?"bg-blue-700 hover:bg-blue-800":"","data-testid":"btn-signature-draw",children:[e.jsx(WO,{className:"h-4 w-4 mr-2"}),"Draw Signature"]}),e.jsxs(De,{type:"button",variant:i==="upload"?"default":"outline",size:"sm",onClick:()=>l("upload"),className:i==="upload"?"bg-blue-700 hover:bg-blue-800":"","data-testid":"btn-signature-upload",children:[e.jsx(Zx,{className:"h-4 w-4 mr-2"}),"Upload Image"]})]}),i==="draw"&&e.jsxs("div",{children:[e.jsx("div",{className:"border-2 border-dashed border-slate-300 rounded-lg p-2 bg-slate-50",children:e.jsx("canvas",{ref:p,width:500,height:150,className:"border border-slate-200 rounded bg-white cursor-crosshair w-full",onMouseDown:h,onMouseMove:f,onMouseUp:v,onMouseLeave:v,"data-testid":"canvas-signature"})}),e.jsxs("div",{className:"flex items-center justify-between mt-3",children:[e.jsx("p",{className:"text-xs text-slate-500",children:"Draw your signature in the box above using your mouse or touchpad"}),e.jsxs(De,{type:"button",variant:"outline",size:"sm",onClick:N,"data-testid":"btn-clear-signature",children:[e.jsx(Ci,{className:"h-4 w-4 mr-2"}),"Clear"]})]})]}),i==="upload"&&e.jsx("div",{children:t.signatureImage?e.jsxs("div",{className:"border border-slate-200 rounded-lg p-4 bg-slate-50",children:[e.jsx("img",{src:t.signatureImage,alt:"Uploaded Signature",className:"max-h-[150px] mx-auto","data-testid":"img-signature-preview"}),e.jsx("div",{className:"flex justify-center mt-3",children:e.jsxs(De,{type:"button",variant:"outline",size:"sm",onClick:()=>u("signatureImage",""),"data-testid":"btn-remove-signature",children:[e.jsx(Ci,{className:"h-4 w-4 mr-2"}),"Remove"]})})]}):e.jsxs("label",{className:"block border-2 border-dashed border-slate-300 rounded-lg p-8 bg-slate-50 hover:bg-slate-100 cursor-pointer transition-colors",children:[e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx(Zx,{className:"h-8 w-8 text-slate-400 mb-2"}),e.jsx("p",{className:"text-sm text-slate-600 font-medium",children:"Click to upload signature image"}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:"PNG, JPG up to 2MB"})]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:x,"data-testid":"input-signature-file"})]})}),t.signatureImage&&e.jsxs("div",{className:"mt-4 p-3 bg-green-50 border border-green-200 rounded-lg flex items-center gap-2",children:[e.jsx(kr,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm text-green-800 font-medium",children:"Signature captured successfully"})]}),!t.signatureImage&&e.jsxs("div",{className:"mt-4 p-3 bg-amber-50 border border-amber-200 rounded-lg flex items-center gap-2",children:[e.jsx(Ns,{className:"h-5 w-5 text-amber-600"}),e.jsx("span",{className:"text-sm text-amber-800",children:"Signature is required to generate the PDF"})]})]})]}),e.jsxs("div",{className:"space-y-0",children:[e.jsx("div",{className:"bg-blue-900 px-4 py-2.5 rounded-t-lg",children:e.jsx("h2",{className:"text-sm font-bold uppercase tracking-wider text-white",children:"Date of Report"})}),e.jsx("div",{className:"bg-white border border-t-0 border-slate-200 rounded-b-lg p-6",children:e.jsx("div",{className:"grid grid-cols-4 gap-4",children:e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs font-semibold text-slate-500",children:["Date of Signature ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ze,{type:"date",defaultValue:new Date().toISOString().split("T")[0],className:"mt-1 h-10 text-sm bg-slate-50 border-slate-200","data-testid":"input-signature-date"})]})})})]})]})}const NG=bk.filter(t=>t.id!=="attachments").map(t=>({id:t.id,label:t.name})),AG={subject:{address:"subject.Property Address",city:"subject.City",state:"subject.State",z
11ipCode:"subject.Zip Code",county:"subject.County",borrower:"subject.Borrower",owner:"subject.Owner of Public Record",legalDescription:"subject.Legal Description",apn:"subject.Assessors Parcel",taxYear:"subject.Tax Year",taxes:"subject.R.E. Taxes",neighborhoodName:"subject.Neighborhood Name",mapReference:"subject.Map Reference",censusTract:"subject.Census Tract",lenderClient:"subject.Lender Client",lenderAddress:"subject.Lender Address"},contract:{contractPrice:"contract.Contract Price",contractDate:"contract.Date of Contract",seller:"contract.Seller",sellerIsOwner:"contract.Seller Is Owner",dataSource:"contract.Data Source",didAnalyze:"contract.Did Analyze",analysisExplanation:"contract.Analysis Explanation",hasFinancialAssistance:"contract.Financial Assistance",financialAssistanceDesc:"contract.Financial Assistance Description"},neighborhood:{location:"neighborhood.Location",builtUp:"neighborhood.Built-Up",growth:"neighborhood.Growth",propertyValues:"neighborhood.Property Values",demandSupply:"neighborhood.Demand/Supply",marketingTime:"neighborhood.Marketing Time",priceLow:"neighborhood.Price Range Low",priceHigh:"neighborhood.Price Range High",pricePred:"neighborhood.Price Predominant",ageLow:"neighborhood.Age Range Low",ageHigh:"neighborhood.Age Range High",agePred:"neighborhood.Age Predominant",landuseOneUnit:"neighborhood.Land Use One-Unit",landuse24Unit:"neighborhood.Land Use 2-4 Unit",landuseMultifamily:"neighborhood.Land Use Multi-Family",landuseCommercial:"neighborhood.Land Use Commercial",landuseOther:"neighborhood.Land Use Other",boundaries:"neighborhood.Neighborhood Boundaries",description:"neighborhood.Neighborhood Description",marketConditions:"neighborhood.Market Conditions"},site:{dimensions:"site.Dimensions",lotSize:"site.Area",area:"site.Area",shape:"site.Shape",view:"site.View",zoningClassification:"site.Specific Zoning Classification",zoningDescription:"site.Zoning Description",femaFloodZone:"site.FEMA Flood Zone",femaZone:"site.FEMA Flood Zone",femaMapNumber:"site.FEMA Map #",femaMapDate:"site.FEMA Map Date"},improvements:{yearBuilt:"improvements.Year Built",effectiveAge:"improvements.Effective Age",stories:"improvements.Stories",type:"improvements.Type",design:"improvements.Design Style",gla:"improvements.GLA",bedrooms:"improvements.Bedrooms",fullBaths:"improvements.Bathrooms Full",halfBaths:"improvements.Bathrooms Half",garageCars:"improvements.Garage Cars",basementArea:"improvements.Basement Area",basementFinished:"improvements.Basement Finished",foundation:"improvements.Foundation",exteriorWalls:"improvements.Exterior Walls",roofSurface:"improvements.Roof Surface",heating:"improvements.Heating Type",heatingFuel:"improvements.Heating Fuel",cooling:"improvements.Cooling"},salesComparison:{subjectAddress:"salesComparison.Subject Address"},reconciliation:{effectiveDate:"reconciliation.Effective Date of Appraisal",finalOpinionOfValue:"reconciliation.Opinion of Market Value"}};function jG({open:t,onClose:a,orderId:s,orderData:r,propertyData:n,selectedComps:i,marketLabState:l,reconciliationData:c,onReconciliationChange:d,onGenerate:p}){console.log("[Form1004WizardModalNew] Props received:",{hasOrderData:!!r,hasPropertyData:!!n,propertyAddressInfo:n?.addressInfo,propMixData:n?.propMixData?"present":"missing",selectedCompsCount:i?.length||0,open:t,zoningClassification:n?.zoningClassification,zoningDescription:n?.zoningDescription});const{toast:u}=hc(),{user:m,profile:h}=ly(),f=h?.userId||m?.id||"",[v,S]=o.useState(!1),[N,x]=o.useState([]),{data:y}=Vr({queryKey:["/api/profile/active-company"],queryFn:async()=>{const je=await fetch("/api/profile/active-company",{credentials:"include"});return je.ok?je.json():{companyName:null}},staleTime:300*1e3}),[b,j]=o.useState({name:r?.appraiser?.value||"First Last",companyName:y?.companyName||"",companyAddress1:"",companyAddress2:"",phone:"",email:"",licenseNumber:r?.appraiserLicense?.value||"",licenseState:r?.appraiserLicenseState?.value||"IL",licenseExpiration:r?.appraiserLicenseExpiration?.value||"",signatureImage:""});o.useEffect(()=>{y?.companyName&&!b.companyName&&j(je=>({...je,companyName:y.companyName}))},[y?.companyName]);const[T,O]=o.useState({siteValueExplanation:"Site value estimated via allocation method due to lack of vacant land sales in the immediate area.",opinionOfSiteValue:"",dwellingSqFt:"",dwellingCostPerSqFt:"",dwellingTotal:"",basementSqFt:"",basementCostPerSqFt:"",basementTotal:"",asIsValueSiteImprovements:"",totalEstimateCostNew:"",depreciationPhysical:"",depreciationFunctional:"0",depreciationExternal:"",depreciationTotal:"",depreciatedCostImprovements:"",indicatedValue:"",estimatedRemainingEconomicLife:"45",sourceOfCostData:"Marshall & Swift",qualityRatingCostService:"Q3",effectiveDateCostData:"",comments:"Cost approach supports value derived from sales comparison approach."}
11),[E,R]=o.useState({estimatedMarketRent:"N/A",grossRentMultiplier:"N/A",indicatedValue:"N/A",summary:"Income approach is not applicable due to lack of rental data in the subject neighborhood for single family homes."}),[G,U]=o.useState([]),[C,F]=o.useState(!0),[A,M]=o.useState([]),[B,oe]=o.useState([]),[ae,D]=o.useState([]),[_,$]=o.useState(!1),z=`uad36-base-profile:${f||"anon"}`,[V,le]=o.useState(()=>typeof window>"u"?"core":localStorage.getItem(z)||"core"),W=je=>{le(je);try{localStorage.setItem(z,je)}catch{}je==="core"&&oe([])},{data:me}=Vr({queryKey:["qc-user-rules-count",f],queryFn:()=>f?fetch(`/api/qc/user-rules?userId=${f}`).then(je=>je.json()):Promise.resolve([]),enabled:!!f}),[Z,pe]=o.useState({subject:{},contract:{},neighborhood:{},site:{},improvements:{},salesComparison:{}}),se=pG({orderData:r,propertyData:n,selectedComps:i,reconciliationData:c,appraiserInfo:b,qcRules:N}),{activeSection:fe,setActiveSection:ue,scrollToField:be,hasHardStops:H,state:ye,uadComps:de}=se,ge=je=>(Le,ut)=>{pe(Xt=>({...Xt,[je]:{...Xt[je],[Le]:ut}}));const st=AG[je];if(st&&st[Le]){const Xt=st[Le];se.setFieldValue(Xt,ut)}};o.useEffect(()=>{t&&Be()},[t]);const Be=async()=>{try{const je=await fetch("/api/qc/rules?formType=1004");if(je.ok){const Le=await je.json();x(Le.filter(ut=>ut.enabled))}}catch(je){console.error("Error loading QC rules:",je)}},He=async()=>{try{const je={...Z,orderData:r,propertyData:n,comps:i,reconciliation:c,appraiser:b,costApproach:T,incomeApproach:E},Le=await fetch("/api/qc/evaluate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({formData:je,formType:"1004",userId:f})});if(Le.ok){const ut=await Le.json();M(ut.findings||[])}}catch(je){console.error("[QC] Evaluation error:",je)}};o.useEffect(()=>{if(t){const je=setTimeout(He,1e3);return()=>clearTimeout(je)}},[t,Z,b,T]),o.useEffect(()=>{if(!t||V!=="core+36")return;const je=setTimeout(()=>{try{const Le=H6({sectionData:Z,orderData:r,propertyData:n,selectedComps:i,reconciliationData:c,appraiserInfo:b,costApproachData:T,incomeApproachData:E}),ut=dG(Le);oe(W6(ut.results))}catch(Le){console.error("[QC UAD36] Live validation error:",Le),oe([])}},500);return()=>clearTimeout(je)},[t,V,Z,b,T,E,c,n,r,i]);const Ie=o.useMemo(()=>[...A,...B],[A,B]),ce=async()=>{$(!0);try{const je={...Z,orderData:r,propertyData:n,comps:i,reconciliation:c,appraiser:b},Le=await fetch("/api/qc/ai-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportData:je})});if(Le.ok){const st=((await Le.json()).findings||[]).map((Xt,ua)=>({id:`ai-${ua}`,source:"ai",title:Xt.title||"AI Finding",severity:Xt.severity||"warning",description:Xt.description||"",suggestion:Xt.suggestion,targetField:Xt.targetField,relatedFields:Xt.relatedFields||[],category:Xt.category}));D(st)}}catch(je){console.error("[QC AI] Review error:",je)}finally{$(!1)}},Pe=je=>{if(!je.targetField||!je.autoFixValue)return;const Le=je.targetField.split(".");if(Le.length>=2){const ut=Le[0],st=Le.slice(1).join(".");ge(ut)(st,je.autoFixValue),u({title:"Auto-fix applied",description:`Set ${je.targetField} to "${je.autoFixValue}"`}),He()}},We=ye.issues.filter(je=>je.severity==="hard-stop").length;ye.issues.filter(je=>je.severity==="warning").length;const Re=ye.sections.reduce((je,Le)=>je+Le.totalFields,0),ne=ye.sections.reduce((je,Le)=>je+Le.filledFields,0),Me=Re>0?Math.round(ne/Re*100):0;ye.issues.filter(je=>je.sectionId===fe),ye.issues.filter(je=>je.sectionId!==fe);const lt=()=>{const je=Number(c.finalOpinionOfValue),Le=isNaN(je)||je<=0,ut=!b.signatureImage;return!H&&!Le&&!ut},Tt=async()=>{if(!lt()){u({title:"Cannot Generate",description:"Please resolve all hard stops, enter final value, and add signature.",variant:"destructive"});return}S(!0);try{await p({orderData:r,propertyData:n,comps:i,reconciliation:c,appraiser:b,costApproach:T,incomeApproach:E,attachments:G,sectionOverrides:Z}),u({title:"Report Generated",description:"Form 1004 PDF has been generated successfully."}),a()}catch(je){u({title:"Generation Failed",description:je.message||"Failed to generate the report.",variant:"destructive"})}finally{S(!1)}};return t?e.jsxs("div",{className:"fixed inset-0 z-50 bg-slate-100","data-testid":"form1004-wizard-modal-new",children:[e.jsxs("header",{className:"bg-white border-b border-slate-200 px-6 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("button",{onClick:a,className:"p-2 hover:bg-slate-100 rounded-lg transition-colors","data-testid":"btn-close-wizard",children:e.jsx(oy,{className:"h-5 w-5 text-slate-600"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gn,{className:"h-5 w-5 text-blue-900"}),e.jsx("h1",{className:"text-xl font-bold text-slate-900",children:"Form 1004 (URAR) - Pre-Generation Wizard"})]}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:"Review and complete each section. Click on QC issues to navigate to fields."})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[We>0&&e.jsxs("span",{className:"px-3 py-1.5 bg-red-500 text-white text-sm font-semibold rounded-lg","data-testid":"badge-hard-stops",children:[We," Hard Stop",We>1?"s":""]}),e.jsxs(De,{variant:"outline",size:"sm",onClick:()=>F(!C),className:`gap-1.5 ${C?"bg-[#A18A60]/10 border-[#A18A60]/30 text-[#A18A60]":""}`,"data-testid":"btn-toggle-qc",children:[e.jsx(fN,{className:"h-4 w-4"}),"QC",e.jsx(FL,{issueCount:Ie.length+ae.length,hardStopCount:Ie.filter(je=>je.severity==="hard-stop").length})]}),e.jsxs(De,{onClick:Tt,disabled:!lt()||v,className:"bg-white border border-slate-200 text-slate-700 hover:bg-slate-50 gap-2","data-testid":"btn-generate-pdf",children:[v?e.jsx(za,{className:"h-4 w-4 animate-spin"}):e.jsx(uN,{className:"h-4 w-4"}),"Generate PDF"]}),e.jsx("button",{className:"p-2 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(fo,{className:"h-5 w-5 text-slate-600"})})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-slate-600",children:["Progress: ",ne,"/",Re," fields"]}),e.jsx("div",{className:"flex-1 h-2 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-700 transition-all duration-300",style:{width:`${Me}%`}})}),e.jsxs("span",{className:"text-sm text-slate-600",children:[Me,"% Complete"]}),e.jsxs("span",{className:"px-2 py-1 bg-red-100 text-red-600 text-xs font-medium rounded","data-testid":"badge-issues-count",children:[ye.issues.length," Issues"]})]})]}),e.jsx("nav",{className:"bg-white border-b border-slate-200 px-6",children:e.jsx("div",{className:"flex items-center gap-1 overflow-x-auto",children:NG.map(je=>{const Le=ye.sections.find(Xt=>Xt.sectionId===je.id),ut=Le?Le.totalFields-Le.filledFields:0,st=fe===je.id;return e.jsxs("button",{onClick:()=>ue(je.id),className:`
12                  relative px-4 py-3 text-sm font-medium whitespace-nowrap transition-colors
13                  ${st?"text-blue-700 bg-white border-b-2 border-blue-700":"text-slate-500 hover:text-slate-700 hover:bg-slate-50"}
14                `,"data-testid":`tab-${je.id}`,children:[je.label,e.jsxs("span",{className:`ml-1 text-xs ${ut>0?"text-amber-600":"text-green-600"}`,children:["(",ut,")"]})]},je.id)})})}),e.jsxs("div",{className:"flex h-[calc(100vh-180px)]",children:[e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Qd,{className:"h-full",children:e.jsxs("div",{className:"p-6",children:[fe==="subject"&&e.jsx(mG,{orderData:r,propertyData:n,subjectData:se.subjectData,onChange:ge("subject"),registerFieldRef:se.registerFieldRef,orderId:s}),fe==="contract"&&e.jsx(hG,{orderData:r,propertyData:n,onChange:ge("contract"),registerFieldRef:se.registerFieldRef,orderId:s}),fe==="neighborhood"&&e.jsx(fG,{propertyData:n,marketLabState:l,onCh
14ange:ge("neighborhood"),registerFieldRef:se.registerFieldRef}),fe==="site"&&e.jsx(gG,{propertyData:n,onChange:ge("site"),registerFieldRef:se.registerFieldRef}),fe==="improvements"&&e.jsx(xG,{propertyData:n,onChange:ge("improvements"),registerFieldRef:se.registerFieldRef}),fe==="salesComparison"&&e.jsx(bG,{propertyData:n,selectedComps:de,onChange:ge("salesComparison"),registerFieldRef:se.registerFieldRef}),fe==="reconciliation"&&e.jsx(yG,{data:c,onChange:d,registerFieldRef:se.registerFieldRef}),fe==="values"&&e.jsx(SG,{costApproach:T,incomeApproach:E,onCostApproachChange:O,onIncomeApproachChange:R,propertyData:n,registerFieldRef:se.registerFieldRef}),fe==="signature"&&e.jsx(vG,{appraiserInfo:b,onAppraiserInfoChange:j,registerFieldRef:se.registerFieldRef,orderId:s})]})})}),C&&e.jsx(_L,{open:C,onClose:()=>F(!1),findings:Ie,aiFindings:ae,baseProfile:V,onBaseProfileChange:W,aiLoading:_,onRunAiReview:ce,onJumpToField:je=>{const Le=je.split(".");if(Le.length>=2){const ut=Le[0];ue(ut),setTimeout(()=>be(je),200)}else be(je)},onAutoFix:Pe,onAddUserRule:()=>window.open("/profile","_blank"),userRulesCount:Array.isArray(me)?me.length:0})]})]}):null}function TG(t){return["neighborhoodName","pinNumber","legalDescription","taxYear","taxes","yearBuilt","hoaFees","pud"].some(s=>{const r=t[s];if(!r||r.isEdited)return!1;const n=r.alternatives;if(!n)return!1;const i=Object.values(n).filter(c=>c!=null&&c!=="");return i.length<=1?!1:!i.every(c=>String(c)===String(i[0]))})}function IG({orderData:t,propertyData:a,setPropertyData:s,occupancy:r,onGenerate:n,onNavigateToStep:i,conflictCount:l=0,docsReviewed:c=!0,selectedComps:d=[],marketLabState:p,isTdcxExpress:u=!1,inspectionCaptured:m=!1,enableBridgeValue:h=!1,bridgeValues:f={asIs:"",afterRepaired:"",commentary:""},onBridgeValuesChange:v,bridgeAsIsPrefill:S=null,bridgeAfterRepairedPrefill:N=null,onGenerateBridgePdf:x}){const y=o.useMemo(()=>ny(a,m),[a,m]),b=o.useMemo(()=>ny(t,m),[t,m]),{toast:j}=hc(),[,T]=bI(),[O,E]=o.useState(!1),[R,G]=o.useState(!1),[U,C]=o.useState(!1),F=new URLSearchParams(window.location.search).get("orderId"),[A,M]=o.useState(!1),[B,oe]=o.useState(null),[ae,D]=o.useState(!1),[_,$]=o.useState({indicatedValueBySalesComparison:0,indicatedValueByCostApproach:0,indicatedValueByIncomeApproach:0,finalOpinionOfValue:0,effectiveDate:b.effectiveDate?.value||new Date().toLocaleDateString("en-US")}),z=TG(y)?2:3,V=o.useRef(null);o.useEffect(()=>{if(U)return;if(y.zoningClassification?.value&&y.zoningClassification.value.trim()!==""){console.log("[Step4Review] Zoning data already present:",y.zoningClassification.value),C(!0);return}const be=b.subjectAddress?.value;if(!be||!s){console.log("[Step4Review] No address or setPropertyData, skipping zoning fetch");return}if(V.current===be)return;V.current=be;let H=!1;return console.log("[Step4Review] Zoning data missing, auto-fetching for:",be),(async()=>{try{const ye=await FI(be);if(H)return;if(ye.success&&ye.data&&ye.data.zoneCode){const de=ye.data;console.log("[Step4Review] Zoneomics returned:",de.zoneCode,de.zoneName),s(ge=>({...ge,zoningClassification:{...ge.zoningClassification,value:de.zoneCode,source:"Zoneomics",alternatives:{...ge.zoningClassification.alternatives,zoneomics:de.zoneCode}},zoningDescription:{...ge.zoningDescription,value:de.zoneName||de.zoneDescription||ge.zoningDescription.value,source:"Zoneomics",alternatives:{...ge.zoningDescription.alternatives,zoneomics:de.zoneName||de.zoneDescription}}}))}else console.log("[Step4Review] No zoning data from Zoneomics:",ye.error)}catch(ye){H||console.error("[Step4Review] Failed to fetch zoning:",ye)}finally{H||C(!0)}})(),()=>{H=!0}},[b.subjectAddress?.value,y.zoningClassification?.value,s,U]);const le=async()=>{const ue=F;if(ue){M(!0);try{const be=await fetch("/api/digital-reports/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({orderId:ue})});if(!be.ok){const de=await be.json();throw new Error(de.error||"Failed to generate share link")}const H=await be.json(),ye=`${window.location.origin}/digital-report/${H.shareId}`;oe(ye),D(!0),j({title:H.alreadyExists?"Share Link Ready":"Digital Report Created",description:"Your shareable report link has been generated."})}catch(be){console.error("Error generating share link:",be),j({title:"Share Failed",description:be instanceof Error?be.message:"Could not generate share link",variant:"destructive"})}finally{M(!1)}}},W=async()=>
14{if(B)try{await navigator.clipboard.writeText(B),j({title:"Link Copied!",description:"Share this link with your client."})}catch{const ue=document.createElement("textarea");ue.value=B,ue.style.position="fixed",ue.style.left="-9999px",document.body.appendChild(ue),ue.select(),document.execCommand("copy"),document.body.removeChild(ue),j({title:"Link Copied!",description:"Share this link with your client."})}},me=()=>{G(!0)},Z=async ue=>{E(!0);try{const be=b.subjectAddress?.value||"",H=be.split(",").map(Re=>Re.trim()),ye=y,de=b,ge=y.yearBuilt?.value,Be=ge&&!isNaN(parseInt(ge))?(new Date().getFullYear()-parseInt(ge)).toString():"",He={fileNumber:de.fileNumber?.value||de.orderNumber||"",borrowerName:b.borrower?.value||"",ownerOfPublicRecord:de.owner?.value||ye.owner?.value||"",lenderClient:b.client?.value||"",subject:{address:H[0]||be,city:H[1]||de.city||"",state:H[2]?.split(" ")[0]||de.state||"",zipCode:H[2]?.split(" ")[1]||de.zipCode||"",county:ye.county?.value||"",legalDescription:y.legalDescription?.value||"",neighborhoodName:y.neighborhoodName?.value||"",mapReference:ye.mapReference?.value||ye.plat?.value||"",censusTract:ye.censusTract?.value||ye.tract?.value||"",quality:ye.quality?.value||"",condition:ye.condition?.value||"",actualAge:Be,yearBuilt:ge||"",gla:ye.gla?.value||ye.livingArea?.value||ye.squareFootage?.value||"",site:ye.lotSize?.value||ye.lotSizeAcres?.value||ye.siteArea?.value||"",view:ye.view?.value||"",design:ye.style?.value||ye.architecturalStyle?.value||ye.design?.value||"",leaseholdFeeSimple:de.propertyRights?.value||"Fee Simple",aboveGradeTotal:ye.totalRooms?.value||ye.rooms?.value||"",aboveGradeBedrooms:ye.bedrooms?.value||ye.bedroomCount?.value||"",aboveGradeBathrooms:Uh(ye.fullBaths?.value!=null?Number(ye.fullBaths.value):null,ye.halfBaths?.value!=null?Number(ye.halfBaths.value):null,ye.bathrooms?.value||ye.bathroomCount?.value||null),basement:ye.basement?.value||ye.basementDescription?.value||"",functionalUtility:ye.functionalUtility?.value||"None",heatingCooling:`${ye.heating?.value||""} / ${ye.cooling?.value||""}`.trim().replace(/^\/\s*|\s*\/$/g,"")||"",energyEfficient:ye.energyEfficient?.value||"",garageCarport:ye.garage?.value||ye.garageType?.value||ye.parking?.value||"",porchPatioDeck:ye.porch?.value||ye.patio?.value||ye.deck?.value||"",occupancy:r||de.occupancy?.value||"",pinNumber:y.pinNumber?.value||"",taxYear:y.taxYear?.value||"",taxes:y.taxes?.value||"",hoaFees:y.hoaFees?.value||"",zoningClassification:ye.zoningClassification?.value||"",zoningCompliance:ye.zoningCompliance?.value||"",utilities:ye.utilities?.value||"",offSiteImprovements:ye.offSiteImprovements?.value||"",salePrice:de.contractPrice?.value||de.salePrice?.value||"",dateOfSale:de.contractDate?.value||"",location:ye.location?.value||"N;Res"},comps:d.slice(0,3).map(Re=>({id:Re.id,address:Re.address,proximityToSubject:Re.proximityToSubject||Re.distance||"",salePrice:Re.salePrice,pricePerSqFt:Re.pricePerSqFt||(Re.salePrice&&Re.gla?Math.round(Re.salePrice/Re.gla):""),dataSources:Re.dataSources||"MLS;DOM",verificationSources:Re.verificationSources||"",saleOrFinancingConcessions:Re.saleOrFinancingConcessions||Re.concessions||"",dateOfSale:Re.dateOfSale,location:Re.location,leaseholdFeeSimple:Re.leaseholdFeeSimple||"Fee Simple",view:Re.view,quality:Re.quality,condition:Re.condition,design:Re.design,gla:Re.gla,site:Re.site||Re.lotSize||"",actualAge:Re.actualAge||Re.yearBuilt?(new Date().getFullYear()-parseInt(Re.yearBuilt)).toString():"",aboveGradeTotal:Re.aboveGradeTotal,aboveGradeBedrooms:Re.aboveGradeBedrooms,aboveGradeBathrooms:Re.aboveGradeBathrooms,basement:Re.basement||"",functionalUtility:Re.functionalUtility||"None",heatingCooling:Re.heatingCooling||"",energyEfficient:Re.energyEfficient||"",garageCarport:Re.garageCarport||Re.garage||"",porchPatioDeck:Re.porchPatioDeck||"",adjustments:Re.adjustments})),appraiser:{name:ue.appraiser.name,companyName:ue.appraiser.companyName,companyAddress1:ue.appraiser.companyAddress1,companyAddress2:ue.appraiser.companyAddress2,phone:ue.appraiser.phone,email:ue.appraiser.email,licenseNumber:ue.appraiser.licenseNumber,licenseState:ue.appraiser.licenseState,licenseExpiration:ue.appraiser.licenseExpiration,signatureDate:new Date().toLocaleDateString("en-US"),signatureImage:ue.appraiser.signatureImage},reconciliation:{indicatedValueBySalesComparison:ue.reconciliation?.indicatedValueBySalesComparison,indicatedValueByCostApproach:ue.reconciliation?.indicatedValueByCostApproach,indicatedValueByIncomeApproach:ue.reconciliation?.indicatedValueByIncomeApproach,finalOpinionOfValue:ue.reconciliation?.f
14inalOpinionOfValue,effectiveDate:ue.reconciliation?.effectiveDate||b.effectiveDate?.value||new Date().toLocaleDateString("en-US")}},Ie=await fetch("/api/reports/1004",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(He)});if(!Ie.ok){const Re=await Ie.json();throw new Error(Re.error||"Failed to generate Form 1004")}const ce=await Ie.blob(),Pe=window.URL.createObjectURL(ce),We=document.createElement("a");We.href=Pe,We.download=He.fileNumber?`${He.fileNumber}_Form1004.pdf`:"Form1004_URAR.pdf",document.body.appendChild(We),We.click(),window.URL.revokeObjectURL(Pe),document.body.removeChild(We),j({title:"Form 1004 Generated",description:"The PDF has been downloaded to your device."}),G(!1)}catch(be){console.error("Error generating Form 1004:",be),j({title:"Generation Failed",description:be instanceof Error?be.message:"Failed to generate Form 1004",variant:"destructive"})}finally{E(!1)}},pe=[{id:"order",label:"Order details confirmed",checked:!0},{id:"subject",label:"Subject data verified",checked:!0},{id:"zoning",label:"Zoning analyzed",checked:!0},{id:"docs",label:"Required docs reviewed",checked:c,warning:!c,warningMessage:"PR card and MLS sheet not yet viewed"},{id:"history",label:"Subject sale/listing history checked",checked:!0},{id:"conflicts",label:l>0?`${l} conflict${l>1?"s":""} unresolved`:"No conflicts to resolve",checked:l===0,warning:l>0,warningMessage:"Review and resolve data conflicts",stepToNavigate:z}],se=pe.every(ue=>ue.checked),fe=pe.some(ue=>ue.warning);return e.jsxs("div",{className:"space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-300 pb-8",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-2xl font-serif font-bold text-accent",children:u?"TDCX Express":"Review & Generate File"}),e.jsx("p",{className:"text-slate-500 text-sm mt-1",children:u?"Quick export to TOTAL — confirm subject data and download your .tdcx file.":"Confirm everything is ready before generating the TOTAL (.tdcx) file."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-white border border-slate-200 rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-slate-100 bg-slate-50/50 flex items-center justify-between gap-2",children:[e.jsxs("h3",{className:"text-[11px] font-bold uppercase tracking-wider text-slate-600 flex items-center gap-2",children:[e.jsx(gn,{className:"w-3.5 h-3.5"}),"Assignment Summary"]}),e.jsx(Z0,{})]}),e.jsxs("div",{className:"divide-y divide-slate-100",children:[e.jsx(pS,{icon:e.jsx(Fo,{className:"w-3.5 h-3.5 text-slate-400"}),label:"Subject Property",value:b.subjectAddress.value,source:S0({smartFieldSource:b.subjectAddress?.source,hasDefault:!!b.subjectAddress?.value})}),e.jsx(pS,{icon:e.jsx(T5,{className:"w-3.5 h-3.5 text-slate-400"}),label:"Appraiser",value:b.appraiser.value,source:S0({smartFieldSource:b.appraiser?.source,hasDefault:!!b.appraiser?.value})}),e.jsx(pS,{icon:e.jsx(lp,{className:"w-3.5 h-3.5 text-slate-400"}),label:"Client",value:b.client.value,source:S0({smartFieldSource:b.client?.source,hasDefault:!!b.client?.value})}),e.jsx(pS,{label:"Assignment Type",value:b.assignmentType.value,source:S0({smartFieldSource:b.assignmentType?.source,hasDefault:!!b.assignmentType?.value})})]})]}),e.jsxs("div",{className:"bg-white border border-slate-200 rounded-xl overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-slate-100 bg-slate-50/50",children:e.jsxs("h3",{className:"text-[11px] font-bold uppercase tracking-wider text-slate-600 flex items-center gap-2",children:[e.jsx(Bs,{className:"w-3.5 h-3.5"}),"Readiness Checklist"]})}),e.jsx("div",{className:"p-4 space-y-2",children:pe.map(ue=>e.jsxs("div",{className:Q("flex items-center gap-3 py-2 px-3 rounded-lg transition-colors",ue.warning&&"bg-amber-50 cursor-pointer hover:bg-amber-100",ue.checked&&!ue.warning&&"bg-green-50/50"),onClick:()=>ue.stepToNavigate&&i?.(ue.stepToNavigate),children:[e.jsx("div",{className:Q("w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0",ue.warning?"bg-amber-100 text-amber-600":ue.checked?"bg-green-100 text-green-600":"bg-slate-100 text-slate-400"),children:ue.warning?e.jsx(Ns,{className:"w-3 h-3"}):e.jsx(Bs,{className:"w-3 h-3"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:Q("text-sm font-medium block",ue.warning?"text-amber-800":ue.checked?"text-slate-700":"text-slate-500"),children:ue.label}),ue.warning&&ue.warningMessage&&e.jsx("span",{className:"text-[10px] text-amber-600 block mt-0.5",children:ue.warningMessage})]}),ue.stepToNavigate&&ue.warning&&e.jsx("span",{className:"text-[10px] font-medium text-amber-600 underline",children:"Review"})]},ue.id))})]})]}),e.jsx("div",{className:"bg-slate-50/80 rounded-xl border border-slate-100 p-5 mt-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-xs font-bold uppercase text-slate-400 mb-3 tracking-wider",children:"Next Steps"}),e.jsxs("ul",{className:"space-y-2 text-sm text-slate-600",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-5 h-5 rounded-full bg-slate-200 text-slate-600 flex items-center justify-center flex-shrink-0 text-[10px] font-bold mt-0.5",children:"1"}),e.jsx("span",{children:"We'll generate the .tdcx file."})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-5 h-5 rounded-full bg-slate-200 text-slate-600 flex items-center justify-center flex-shrink-0 text-[10px] font-bold mt-0.5",children:"2"}),e.jsx("span",{children:"It will auto-download instantly."})]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-5 h-5 rounded-full bg-slate-200 text-slate-600 flex items-center justify-center flex-shrink-0 text-[10px] font-bold mt-0.5",children:"3"}),e.jsx("span",{children:"Double-click it to open directly in TOTAL."})]})]})]}),h&&e.jsxs("div",{className:"flex-shrink-0 rounded-xl border-2 border-[#C5A572]/40 bg-[#faf8f4] p-5 mb-1","data-testid":"panel-bridge-value",children:[e.jsx("div",{className:"flex items-start justify-between gap-3 mb-1",children:e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-[#072034]",children:"Bridge Value"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:"An internal two-value summary (As-Is and After-Repaired) for dual-scenario orders."})]})}),e.jsx("p",{className:"text-[11px] text-slate-500 italic mb-4",children:"For internal use only — this is not an appraisal, evaluation, or BPO."}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:"As-Is Value"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-sm",children:"$"}),e.jsx("input",{type:"number",inputMode:"numeric",className:"w-full h-10 pl-7 pr-3 rounded-lg border border-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-[#C5A572]/50",value:f.asIs,placeholder:S!=null?S.toLocaleStr
14ing():"—",onChange:ue=>v?.({...f,asIs:ue.target.value}),"data-testid":"input-bridge-as-is"})]}),S!=null&&f.asIs.trim()===""&&e.jsxs("button",{type:"button",className:"mt-1 text-[11px] text-[#9c7d42] hover:underline",onClick:()=>v?.({...f,asIs:String(S)}),"data-testid":"button-bridge-as-is-prefill",children:["Use indicated $",S.toLocaleString()]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:"After-Repaired Value (ARV)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-sm",children:"$"}),e.jsx("input",{type:"number",inputMode:"numeric",className:"w-full h-10 pl-7 pr-3 rounded-lg border border-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-[#C5A572]/50",value:f.afterRepaired,placeholder:N!=null?N.toLocaleString():"—",onChange:ue=>v?.({...f,afterRepaired:ue.target.value}),"data-testid":"input-bridge-after-repaired"})]}),N!=null&&f.afterRepaired.trim()===""&&e.jsxs("button",{type:"button",className:"mt-1 text-[11px] text-[#9c7d42] hover:underline",onClick:()=>v?.({...f,afterRepaired:String(N)}),"data-testid":"button-bridge-after-repaired-prefill",children:["Use indicated $",N.toLocaleString()]})]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:"Reconciliation Commentary"}),e.jsx("textarea",{rows:3,className:"w-full px-3 py-2 rounded-lg border border-slate-300 text-sm focus:outline-none focus:ring-2 focus:ring-[#C5A572]/50 resize-y",value:f.commentary,placeholder:"Explain how you reconciled the two values (optional).",onChange:ue=>v?.({...f,commentary:ue.target.value}),"data-testid":"input-bridge-commentary"})]}),e.jsxs(De,{size:"lg",className:"h-11 px-6 text-sm font-semibold bg-[#072034] hover:bg-[#0a2f4c] text-white",onClick:()=>x?.(),"data-testid":"button-generate-bridge-value",children:[e.jsx(gn,{className:"w-4 h-4 mr-2"}),"Generate Bridge Value PDF"]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col gap-3",children:[e.jsxs(De,{size:"lg",className:Q("h-12 px-8 text-base font-semibold shadow-md",se&&!fe?"bg-primary hover:bg-primary/90":"bg-amber-500 hover:bg-amber-600"),onClick:n,"data-testid":"button-generate-total",children:[e.jsx(eT,{className:"w-5 h-5 mr-2"}),u?"Download TDCX File":se&&!fe?"Generate TOTAL File":"Generate Anyway"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[!u&&e.jsxs(De,{size:"lg",variant:"outline",className:"h-12 px-6 text-sm font-semibold border-2 border-blue-500 text-blue-600 hover:bg-blue-50 flex-1 min-w-0",onClick:me,disabled:O,"data-testid":"button-push-to-1004",children:[O?e.jsx(za,{className:"w-4 h-4 mr-1.5 animate-spin"}):e.jsx(I5,{className:"w-4 h-4 mr-1.5"}),O?"Generating...":"Push to Form 1004"]}),F&&!u&&e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsxs(De,{size:"lg",variant:"outline",className:"h-12 px-6 text-sm font-semibold border-2 border-emerald-500 text-emerald-600 hover:bg-emerald-50 w-full",onClick:le,disabled:A,"data-testid":"button-share-digital-report",children:[A?e.jsx(za,{className:"w-4 h-4 mr-1.5 animate-spin"}):e.jsx(C5,{className:"w-4 h-4 mr-1.5"}),A?"Generating...":"Share Report"]}),ae&&B&&e.jsxs("div",{className:"absolute top-full mt-2 right-0 bg-white border border-slate-200 rounded-xl shadow-lg p-4 z-50 min-w-[320px]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-600",children:"Shareable Link"}),e.jsx("button",{onClick:()=>D(!1),className:"text-slate-400 hover:text-slate-600 text-xs",children:"Close"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:B,readOnly:!0,className:"flex-1 text-xs bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 truncate","data-testid":"input-share-link"}),e.jsxs(De,{size:"sm",variant:"outline",className:"shrink-0",onClick:W,"data-testid":"button-copy-share-link",children:[e.jsx(jr,{className:"w-3.5 h-3.5 mr-1"}),"Copy"]})]}),e.jsxs("a",{href:B,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-xs text-indigo-600 hover:underline mt-2","data-testid":"link-open-digital-report",children:[e.jsx(rf,{className:"w-3 h-3"}),"Open in new tab"]})]})]})]}),F&&e.jsxs(De,{size:"lg",variant:"outline",className:"h-12 px-8 text-base font-semibold border-2 border-indigo-500 text-indigo-600 hover:bg-indigo-50",onClick:()=>T(`/report-preview/${F}`),"data-testid":"button-preview-report",children:[e.jsx(of,{className:"w-5 h-5 mr-2"}),"Preview Report"]}),fe&&e.jsx("p",{className:"text-[10px] text-amber-600 mt-1 text-center",children:"Some items need attention"})]})]})}),F&&F!=="new"&&e.jsx("div",{className:"mt-6","data-testid":"parties-panel-step4",children:e.jsx(v$,{orderId:F,embedMode:"compact",readOnly:!0})}),e.jsx(jG,{open:R,onClose:()=>G(!1),orderId:F||void 0,orderData:b,propertyData:y,selectedComps:d,marketLabState:p,reconciliationData:_,onReconciliationChange:$,onGenerate:Z})]})}function pS({icon:t,label:a,value:s,source:r}){return e.jsxs("div",{className:"flex items-center gap-3 py-3 px-4",children:[t&&e.jsx("div",{className:"flex-shrink-0",children:t}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium text-slate-500 uppercase tracking-wide block",children:a}),r&&e.jsx(pd,{source:r})]}),e.jsx("span",{className:"text-sm font-semibold text-slate-900 truncate block",children:s})]})]})}function CG(t,a){return t||a||null}function hj(t){return t==="no-id"||t===400?{title:"Save the order first",description:"Save or reopen this order before generating the Bridge Value report.",retriable:!1}:t===401?{title:"Session expired",description:"Your session expired — sign in again to continue.",retriable:!1}:t===403?{title:"No access",description:"You don't have access to this order.",retriable:!1}:t===404?{title:"Order not found",description:"This order couldn't be found — try reopening it.",retriable:!1}:{title:"Error",description:"Something went wrong on our end — please try again.",retriable:!0}}function Pc(t){if(t.mlsNumber)return String(t.mlsNumber);const a=t.mlsData;return a?.mlsNumber?String(a.mlsNumber):a?.MlsListingNumber?String(a.MlsListingNumber):a?.ListingId?String(a.ListingId):t.snapshotId?String(t.snapshotId):t.id?String(t.id):null}function fj(t){const a=[],s=t.mlsNumber??t.mlsData?.mlsNumber??t.mlsData?.MlsListingNumber??t.mlsData?.ListingId??null;s!=null&&String(s).trim()!==""&&a.push(`mls:${String(s)}`);const r=t.snapshotId;r!=null&&String(r).trim()!==""&&a.push(`snap:${String(r)}`);const n=t.id;
14return n!=null&&String(n).trim()!==""&&a.push(`id:${String(n)}`),a}const sP=2,rP=1500,nP=10,RG=12e3;function EG({properties:t,enabled:a=!0,batchScoresLoaded:s=!0,alreadyFetchedMlsNumbers:r,compAiCacheRef:n,prioritizedIds:i,onAnalysisComplete:l}){const c=o.useRef(new Set),d=o.useRef(!1),[p,u]=o.useState(!1),m=o.useRef(t);m.current=t;const h=o.useRef(l);h.current=l;const f=o.useRef(r);f.current=r;const v=o.useRef(i);v.current=i;const S=o.useRef(!1),N=o.useRef(!1);return o.useEffect(()=>(N.current=!1,()=>{N.current=!0}),[]),o.useEffect(()=>{if(!a||!s||S.current||d.current)return;const x=m.current;if(x.length===0)return;const y=f.current,b=v.current;let j=0,T=0,O=0,E=0,R=0,G=0;const U=x.filter($=>{const z=Pc($);if(!z)return j++,!1;if(c.current.has(z))return T++,!1;if(y?.has(z))return O++,!1;if($.qualityRating||$.conditionRating)return E++,!1;const V=$.snapshotId||$.id;return n?.current?.has(V)?(R++,!1):!$.photos||$.photos.length===0?(G++,!1):!0});if(U.length===0){console.log(`[OnDemandAI] No properties need analysis. Skipped: noMls=${j} analyzed=${T} fetched=${O} hasRating=${E} inCache=${R} noPhotos=${G} total=${x.length}`),u(!0);return}const C=$=>!b||b.size===0?!1:!!($.snapshotId&&b.has($.snapshotId)||$.id&&b.has($.id)||$.mlsNumber&&b.has($.mlsNumber)),F=new Map;U.forEach(($,z)=>F.set($,z));const A=[...U].sort(($,z)=>{const V=C($)?0:1,le=C(z)?0:1;return V!==le?V-le:(F.get($)??0)-(F.get(z)??0)}),M=A.slice(0,nP),B=A.slice(nP),oe=A.filter(C).length;S.current=!0,d.current=!0,u(!1),console.log(`[OnDemandAI] Starting analysis: ${U.length} properties (concurrency=${sP}, stagger=${rP}ms, prioritized=${oe}, initialBurst=${M.length}, deferred=${B.length}) (skipped: noMls=${j} analyzed=${T} fetched=${O} hasRating=${E} inCache=${R} noPhotos=${G})`);const ae=async $=>{const z=Pc($);if(!z)return;const V=$.snapshotId||$.id,le=2;for(let W=0;W<=le;W++)try{const me=await fetch("/api/ai/analyze-property-photos",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({mlsNumber:z,compId:V,propertyAddress:$.address,photoUrls:$.photos?.slice(0,4)||[]})});if(me.status===429&&W<le){const Z=me.headers.get("Retry-After"),pe=Z?parseInt(Z,10):NaN,se=!isNaN(pe)&&pe>0?Math.min(pe*1e3,3e4):2e3*Math.pow(2,W);console.log(`[OnDemandAI] 429 for ${z}, retry ${W+1} after ${se}ms`),await new Promise(fe=>setTimeout(fe,se));continue}if(me.ok){const Z=await me.json(),pe=Z.data?.condition?.rating,se=Z.data?.quality?.rating;c.current.add(z),(pe||se)&&(console.log(`[OnDemandAI] Analyzed ${z}: C=${pe}, Q=${se}`),h.current?.(V,z,pe,se))}else console.warn(`[OnDemandAI] HTTP ${me.status} for ${z}`),c.current.add(z);break}catch(me){W===le&&(console.warn(`[OnDemandAI] Failed to analyze ${z}:`,me),c.current.add(z))}},D=async $=>{let z=0;const V=[],le=[];let W=0;const me=async()=>{for(;z>=sP;)await new Promise(pe=>V.push(pe));z++},Z=()=>{z--;const pe=V.shift();pe&&pe()};for(const pe of $){if(N.current)break;const se=Pc(pe);if(se&&c.current.has(se))continue;if(await me(),N.current){Z();break}const fe=ae(pe).finally(()=>{W++,Z()});if(le.push(fe),await new Promise(ue=>setTimeout(ue,rP)),N.current)break}return le.length>0&&await Promise.allSettled(le),W};(async()=>{const $=await D(M);if(console.log(`[OnDemandAI] Initial burst complete: ${$} processed`),B.length>0){if(await new Promise(V=>setTimeout(V,RG)),N.current){console.log(`[OnDemandAI] Unmounted before deferred batch (${B.length} skipped)`),d.current=!1;return}const z=await D(B);console.log(`[OnDemandAI] Deferred batch complete: ${z} processed`)}d.current=!1,N.current||u(!0),console.log(`[OnDemandAI] All analysis complete. ${c.current.size} total analyzed`)})()},[a,s]),{analysisComplete:p}}const wG=3e3,iP=20,PG=2e3;function OG({properties:t,enabled:a=!0,batchScoresLoaded:s=!0,isStreaming:r=!1,compAiCacheRef:n,onRatingReceived:i}){const[l,c]=o.useState(!1),d=o.useRef(i);d.current=i;const p=o.useRef(t);p.current=t;const u=2e3,[m,h]=o.useState(r);o.useEffect(()=>{if(r){h(!0);return}const N=setTimeout(()=>h(!1),u);return()=>clearTimeout(N)},[r]);const f=o.useRef(null),v=o.useMemo(()=>
14{if(m)return f.current??"";const N=t.map(y=>Pc(y)).filter(Boolean).sort().join(","),x=`${t.length}:${N.slice(0,200)}`;return f.current=x,x},[t,m]),S=o.useRef(v);return o.useEffect(()=>{S.current!==v&&(S.current=v,c(!1))},[v]),o.useEffect(()=>{if(m)return;const N=p.current;if(!a||N.length===0){c(!0);return}if(!s)return;const x=new Set;let y=!1,b=0,j=null;const T=R=>{const G=[];for(const U of R){const C=Pc(U);if(!C)continue;const F=U.snapshotId||U.id;if(x.has(F))continue;if(U.conditionRating&&U.qualityRating){x.add(F);continue}if(n?.current?.has(F)){const M=n.current.get(F);if(M?.condition&&M?.quality){x.add(F);continue}}if((U.photos||[]).length===0){x.add(F);continue}G.push({mlsNumber:C,propId:F})}return G},O=T(p.current);if(O.length===0){c(!0);return}c(!1),console.log(`[BackgroundCQ-Poll] Starting polling for ${O.length} properties without C/Q ratings`);const E=async()=>{if(y)return;const R=p.current,G=T(R);if(G.length===0||b>=iP){y||(c(!0),G.length===0?console.log(`[BackgroundCQ-Poll] All ratings resolved after ${b} polls`):console.log(`[BackgroundCQ-Poll] Stopped after ${iP} polls, ${G.length} still missing`));return}b++;const U=Array.from(new Set(G.map(C=>C.propId)));try{const C={};if(b<=2)for(const A of R){const M=Pc(A),B=A.snapshotId||A.id;if(!M||!U.includes(B))continue;const oe=A.photos||[];oe.length>0&&!C[B]&&(C[B]={mlsNumber:M,photos:oe.slice(0,4),propertyAddress:[A.address,A.city,A.state].filter(Boolean).join(", ")})}const F=await fetch("/api/ai/get-cached-ratings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({snapshotIds:U,photoMap:b<=2?C:void 0})});if(y)return;if(F.ok){const A=await F.json();if(A.success&&A.results){let M=0;for(const[B,oe]of Object.entries(A.results))if(oe.conditionRating&&oe.qualityRating&&!x.has(B)){x.add(B),M++;const ae=R.find(_=>(_.snapshotId||_.id)===B),D=ae?Pc(ae):"";D&&d.current?.(B,D,oe.conditionRating,oe.qualityRating)}M>0&&console.log(`[BackgroundCQ-Poll] Poll ${b}: ${M} new ratings received`)}}}catch(C){if(y)return;console.warn(`[BackgroundCQ-Poll] Poll ${b} failed:`,C)}y||(j=setTimeout(E,wG))};return j=setTimeout(E,PG),()=>{y=!0,j!==null&&clearTimeout(j)}},[a,s,v,m,n]),{pollingComplete:l}}function LG(t){return["/api/orders",t,"subject-photos"]}function DG(t){return Vr({queryKey:LG(t),queryFn:async()=>{if(!t)return[];const a=await fetch(`/api/orders/${t}/subject-photos`,{credentials:"include"});if(!a.ok)return[];const s=await a.json();return!s.success||!Array.isArray(s.photos)?[]:s.photos.map(r=>r.originalUrl).filter(r=>!!r&&r.trim()!=="")},enabled:!!t,staleTime:300*1e3})}const fx="ProjectInformation",kG="22.02.05",yk=["ProjectName","AssociationChargeAmount","ProjectCommonAmenityType","AssociationSpecialAssessmentStatusType"],MG=["AssociationChargeAmount","ProjectCommonAmenityType","AssociationSpecialAssessmentStatusType"],Sk="ProjectInformationManualRelevance",FG="ProjectInformation",_G={ProjectName:'Automatically included when PropertyInProjectIndicator = "true" for the subject or any comparable.',AssociationSpecialAssessmentStatusType:'Automatically included when (PropertyInProjectIndicator = "true" or PUDIndicator = "true") and (AssociationSpecialAssessmentStatusType = "Existing" or "Proposed") for the subject or any comparable.'};function dp(t){return t&&typeof t=="object"&&"value"in t?t.value:t}function Bv(t){const a=dp(t);return a===!0||a==="true"||a==="True"||a==="yes"||a==="Yes"||a==="Y"}function UG(t){const a=dp(t);return a===!1||a==="false"||a==="False"||a==="no"||a==="No"||a==="N"}function sp(t,a){const s=oP(t,a);if(s!==void 0)return s;const r=t?.[a];if(r!==void 0)return dp(r);const n=dp(t?.[FG]);if(n&&typeof n=="object"){const i=n,l=oP(i,a);if(l!==void 0)return l;const c=i[a];return c!==void 0?dp(c):void 0}}function oP(t,a){if(t){if(a==="AssociationChargeAmount")return dp(t.AssociationDuesAmount);if(a==="ProjectCommonAmenityType")return dp(t.AmenityTypes);if(a==="AssociationSpecialAssessmentStatusType"){const s=dp(t.SpecialAssessmentCharges);if(Array.isArray(s)){const r=s.map(n=>n&&typeof n=="object"?n.statusType:void 0).filter(n=>typeof n=="string");return r.length===1?r[0]:r}}}}function JI(t){return Bv(sp(t,"PropertyInProjectIndicator"))}function VG(t){return Bv(sp(t,"PUDIndicator"))}function $G(t){return JI(t)||VG(t)}function gx(t){if(!$G(t))return!1;const a=sp(t,"AssociationSpecialAssessmentStatusType");return(Array.isArray(a)?a:[a]).some(r=>/^(existing|proposed)$/i.test(String(r??"").trim()))}function lP(t,a){return[t,...a].some(JI)}function BG(t,a){return t==="ProjectName"?a.propertyInProject:t==="AssociationSpecialAssessmentStatusType"&&a.automaticSpecialAssessment||a.manuallyRelevant===!0}function zG(t,a,s=!1){return UG(sp(a,"PropertyInProjectIndicator"))}function qG(t){return MG.some(a=>t?.[a]===!0)}function YG(t){return t.automaticSection||t.automaticSpecialAssessment||qG(t.manualRelevance)}
14function mS(t){const a=dp(t?.[Sk]),s=typeof a=="string"?(()=>{try{return JSON.parse(a)}catch{return null}})():a;if(!s||typeof s!="object"||Array.isArray(s))return{};const r={};for(const n of yk)s[n]===!0&&(r[n]=!0);return r}const fg=[{key:"matchScore",label:"Match",defaultVisible:!0},{key:"locationScore",label:"Loc",defaultVisible:!0},{key:"distance",label:"Distance",defaultVisible:!0},{key:"status",label:"Status",defaultVisible:!0},{key:"address",label:"Address",defaultVisible:!0},{key:"city",label:"City",defaultVisible:!0},{key:"beds",label:"Beds",defaultVisible:!0},{key:"baths",label:"Baths",defaultVisible:!0},{key:"sqft",label:"GLA (MLS)",defaultVisible:!0},{key:"listDate",label:"List Date",defaultVisible:!0},{key:"price",label:"Price",defaultVisible:!0},{key:"closeDate",label:"Close Date",defaultVisible:!0},{key:"condition",label:"Cond",defaultVisible:!0},{key:"quality",label:"Qual",defaultVisible:!0},{key:"yearBuilt",label:"Year Built",defaultVisible:!0},{key:"avmScore",label:"AVM",defaultVisible:!0},{key:"utility",label:"Utility",defaultVisible:!0},{key:"sqftPR",label:"GLA (PR)",defaultVisible:!1},{key:"lotSqft",label:"Lot (MLS)",defaultVisible:!1},{key:"lotSqftPR",label:"Lot (PR)",defaultVisible:!1},{key:"dom",label:"DOM",defaultVisible:!1},{key:"basement",label:"Basement",defaultVisible:!1},{key:"style",label:"Style",defaultVisible:!1},{key:"nightlyRate",label:"Nightly Rate",defaultVisible:!1},{key:"occupancy",label:"Occupancy",defaultVisible:!1}],qb=["nightlyRate","occupancy"],vk=fg.filter(t=>t.defaultVisible).map(t=>t.key),GG=Object.fromEntries(fg.map(t=>[t.key,t])),cP=40,Nk={status:56,address:180,city:80,price:96,beds:40,baths:40,sqft:56,sqftPR:56,lotSqft:64,lotSqftPR:64,distance:60,listDate:56,closeDate:56,dom:48,yearBuilt:48,condition:40,quality:40,locationScore:40,matchScore:48,avmScore:48,utility:56,basement:80,style:80,nightlyRate:72,occupancy:60},HG={status:{label:"Status",textAlign:"text-center",justify:"justify-center",sortable:!1},address:{label:"Address",textAlign:"",justify:"",sortable:!1},city:{label:"City",textAlign:"",justify:"",sortable:!1},price:{label:"Price",textAlign:"text-right",justify:"justify-end",sortable:!0},beds:{label:"Bed",textAlign:"text-center",justify:"justify-center",sortable:!0},baths:{label:"Ba",textAlign:"text-center",justify:"justify-center",sortable:!0},sqft:{label:"Sqft",textAlign:"text-right",justify:"justify-end",sortable:!0},sqftPR:{label:"Sqft PR",textAlign:"text-right",justify:"justify-end",sortable:!1,extraClass:"text-blue-600"},lotSqft:{label:"Lot",textAlign:"text-right",justify:"justify-end",sortable:!1},lotSqftPR:{label:"Lot PR",textAlign:"text-right",justify:"justify-end",sortable:!1,extraClass:"text-blue-600"},distance:{label:"Dist",textAlign:"text-center",justify:"justify-center",sortable:!0},listDate:{label:"List",textAlign:"text-center",justify:"justify-center",sortable:!0},closeDate:{label:"Closed",textAlign:"text-center",justify:"justify-center",sortable:!0},dom:{label:"DOM",textAlign:"text-center",justify:"justify-center",sortable:!0},yearBuilt:{label:"Year",textAlign:"text-center",justify:"justify-center",sortable:!0},condition:{label:"Cond",textAlign:"text-center",justify:"justify-center",sortable:!0},quality:{label:"Qual",textAlign:"text-center",justify:"justify-center",sortable:!0},locationScore:{label:"Loc",textAlign:"text-center",justify:"justify-center",sortable:!0},matchScore:{label:"Match",textAlign:"text-center",justify:"justify-center",sortable:!0},avmScore:{label:"AVM",textAlign:"text-center",justify:"justify-center",sortable:!0},utility:{label:"Utility",textAlign:"text-center",justify:"justify-center",sortable:!0},basement:{label:"Basement",textAlign:"text-center",justify:"justify-center",sortable:!0},style:{label:"Style",textAlign:"text-center",justify:"justify-center",sortable:!0},nightlyRate:{label:"Nightly",textAlign:"text-right",justify:"justify-end",sortable:!0},occupancy:{label:"Occ",textAlign:"text-center",justify:"justify-center",sortable:!0}},WG={gla:"Size",beds:"Beds",baths:"Baths",yearBuilt:"Age",lotSize:"Lot",garage:"Garage",style:"Style",basement:"Basement",pool:"Pool",fireplace:"Fireplace",view:"View",proximity:"Distance",location:"Location",school:"School",els:"ELS"};function Ak({breakdown:t}){return!t||Object.keys(t).length===0?e.jsx("span",{className:"text-slate-500",children:"Match Score"}):e.jsx("dl",{className:"space-y-1",children:Object.entries(t).map(([a,s])=>e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-slate-500",children:WG[a]||a}),e.jsxs("dd",{className:Q("font-medium tabular-nums",s>=.7?"text-green-700":s>=.4?"text-amber-700":"text-slate-600"),children:[Math.round(s*100),"%"]})]},a))})}function jk(t,a){if(!t?.length||!a?.length)return[];const s=[];for(const r of t){const n=a.find(c=>c.name===r.name);if(!n)continue;const i=n.subscore-r.subscore,l=Math.abs(i);l>=20&&s.push({factorName:r.name,subjectScore:r.subscore,compScore:n.subscore,delta:i,severity:l>=30?"major":"moderate"})}return s.sort((r,n)=>Math.abs(n.delta)-Math.abs(r.delta)),s}const KG={"Flood Zone":"Flood",Highway:"Hwy","Road Traffic":"Traffic","Rail/Transit":"Rail","Power Lines":"Power","Commercial/Industrial":"Comm/Ind",Airport:"Airport",Landfill:"Landfill","Water Treatment":"WTP",Cemetery:"Cemetery","Fuel Storage":"Fuel",Water:"Water",Park:"Park","School Proximity":"School","School Rating":"SchRating","Golf Course":"Golf","Cul-de-sac":"Cul-de-sac",View:"View"};function QG({divergences:t}){if(!t.length)return null;const a=t.slice(0,3);return e.jsxs("div",{className:"flex flex-wrap gap-0.5 mt-0.5",children:[a.map(s=>{const r=KG[s.factorName]||s.factorName,n=s.delta>0?"+":"";return e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("span",{className:Q("inline-flex items-center px-1 py-0 rounded text-[9px] font-medium leading-tight cursor-help",s.severity==="major"?"bg-red-50 text-red-600 border border-red-200":"bg-amber-50 text-amber-600 border border-amber-200"),"data-testid":`els-divergence-${s.factorName.replace(/\s+/g,"-").toLowerCase()}`,children:[r," ",n,s.delta]})}),e.jsxs(Wa,{side:"bottom",className:"text-[11px] max-w-[200px]",children:[e.jsx("div",{className:"font-medium",children:s.factorName}),e.jsxs("div",{className:"text-slate-500",children:["Subject: ",s.subjectScore," → Comp: ",s.compScore]}),e.jsxs("div",{className:s.severity==="major"?"text-red-600":"text-amber-600",children:[s.severity==="major"?"Major":"Moderate"," divergence (",n,s.delta," pts)"]})]})]})},s.factorName)}),t.length>3&&e.jsxs("span",{className:"text-[9px] text-slate-400",children:["+",t.length-3," more"]})]})}function Tk({factors:t}){return!t||t.length===0?e.jsx("span",{className:"text-slate-500",children:"Location Score"}):e.jsx("dl",{className:"space-y-1.5",children:t.map(a=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("dt",{className:"text-slate-400 flex items-center gap-1.5",children:[e.jsx("span",{className:Q("w-4 text-center font-medium",a.status==="+"?"text-green-500":a.status==="−"?"text-red-500":"text-slate-400"),children:a.status==="OK"?"✓":a.status}),a.name]}),e.jsx("dd",{className:"text-slate-300 text-[10px]",children:a.detail})]},a.name))})}const gj={price:"price",beds:"beds",baths:"baths",sqft:"sqft",distance:"distance",listDate:"listDate",closeDate:"closeDate",dom:"dom",yearBuilt:"yearBuilt",condition:"condition",quality:"quality",locationScore:"locationScore",matchScore:"matchScore",avmScore:"avmScore",utility:"utility",basement:"basement",style:"style",nightlyRate:"nightlyRate",occupancy:"occupancy"};function ZG({properties:t,selectedCompIdSet:a,isCompSelected:s,isLoading:r,loadingPhase:n,hoveredPropertyId:i,onHoverProperty:l,onClickProperty:c,onSelectProperty:d,onDeselectProperty:p,selectedCount:u,s
14ortBy:m,onSortChange:h,columnSort:f,onColumnSortChange:v,viewMode:S="cards",onFocusOnMap:N,onElsOverride:x,subjectElsFactors:y,comparisonDataSource:b="mls",visibleColumns:j,onVisibleColumnsChange:T,onSaveColumnsAsDefault:O,showSelectedOnly:E,onToggleShowSelectedOnly:R,subjectRow:G,emptyStateMessage:U,emptyStateSubMessage:C,noBoundaries:F=!1,showMapPanel:A,aiAnalysisReady:M=!1,elsLoaded:B=!1,isPreloading:oe=!1,initialLoading:ae=!1,hasActiveClientFilter:D=!1,stableCount:_,strMode:$=!1}){const[z,V]=o.useState(!1),le=b==="public-record",W=o.useRef(null),me=o.useRef(null),Z=o.useRef(null),[pe,se]=o.useState(400),[fe,ue]=o.useState({...Nk}),be=o.useRef(null),H=o.useRef(null);o.useEffect(()=>()=>{H.current?.()},[]);const ye=o.useCallback((Fe,Oe)=>{Oe.preventDefault(),Oe.stopPropagation();const rt=Oe.clientX,$t=fe[Fe];be.current={key:Fe,startX:rt,startWidth:$t};const na=Ua=>{if(!be.current)return;const Ce=Ua.clientX-be.current.startX,St=Math.max(cP,be.current.startWidth+Ce);ue(vt=>({...vt,[be.current.key]:St}))},zt=()=>{be.current=null,document.removeEventListener("mousemove",na),document.removeEventListener("mouseup",zt),document.body.style.cursor="",document.body.style.userSelect="",H.current=null};H.current=zt,document.addEventListener("mousemove",na),document.addEventListener("mouseup",zt),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[fe]),de=o.useCallback((Fe,Oe)=>{Oe.preventDefault(),Oe.stopPropagation(),ue(rt=>({...rt,[Fe]:cP}))},[]),ge=o.useCallback(Fe=>({width:fe[Fe],minWidth:fe[Fe],maxWidth:fe[Fe],flexShrink:0}),[fe]),Be=o.useCallback(Fe=>s?s(Fe):a?a.has(Fe.snapshotId||Fe.id):!!Fe.isSelected,[s,a]),He=E?t.filter(Fe=>Be(Fe)):t,Ie=o.useRef(400);o.useEffect(()=>{const Fe=()=>{if(W.current){const rt=W.current.clientHeight;Math.abs(rt-Ie.current)>5&&(Ie.current=rt,se(rt))}};Fe();const Oe=new ResizeObserver(Fe);return W.current&&Oe.observe(W.current),()=>Oe.disconnect()},[]),o.useEffect(()=>{const Fe=Z.current;if(!Fe)return;const Oe=()=>{me.current&&(me.current.scrollLeft=Fe.scrollLeft)};return Fe.addEventListener("scroll",Oe),Oe(),()=>Fe.removeEventListener("scroll",Oe)},[S]);const ce=145,Pe=38,We=j||vk,Re=o.useMemo(()=>{if(!$)return We;const Fe=new Set(We),Oe=qb.filter(rt=>!Fe.has(rt));return Oe.length>0?[...We,...Oe]:We},[We,$]),[ne,Me]=o.useState(()=>{const Fe=new Set(Re),Oe=fg.map(rt=>rt.key).filter(rt=>!Fe.has(rt));return[...Re,...Oe]});o.useEffect(()=>{Me(Fe=>{const Oe=new Set(fg.map(Ua=>Ua.key)),rt=Re.filter(Ua=>Oe.has(Ua)),$t=new Set(rt),na=Fe.filter(Ua=>Oe.has(Ua)&&!$t.has(Ua)),zt=fg.map(Ua=>Ua.key).filter(Ua=>!$t.has(Ua)&&!na.includes(Ua));return[...rt,...na,...zt]})},[Re]);const lt=o.useRef(null),Tt=o.useRef(null),je=Fe=>{lt.current=Fe},Le=Fe=>{Tt.current=Fe},ut=Fe=>$?Fe.filter(Oe=>!qb.includes(Oe)):Fe,st=()=>{if(lt.current===null||Tt.current===null||lt.current===Tt.current){lt.current=null,Tt.current=null;return}const Fe=[...ne],[Oe]=Fe.splice(lt.current,1);Fe.splice(Tt.current,0,Oe),Me(Fe);const rt=Fe.filter($t=>Re.includes($t));T?.(ut(rt)),lt.current=null,Tt.current=null},Xt=Fe=>{if(T&&!($&&qb.includes(Fe)))if(Re.includes(Fe))T(ut(Re.filter(Oe=>Oe!==Fe)));else{const Oe=ne.filter(rt=>Re.includes(rt)||rt===Fe);T(ut(Oe))}},ua=Fe=>Re.includes(Fe),Oa=Fe=>{const Oe=HG[Fe];if(!Oe)return null;const rt=ge(Fe),$t=e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-[5px] cursor-col-resize hover:bg-blue-400/40 z-10",onMouseDown:na=>ye(Fe,na),onDoubleClick:na=>de(Fe,na),"data-testid":`resize-handle-${Fe}`});if(Oe.sortable&&gj[Fe]){const na=Oe.justify==="justify-center",zt=qa(Fe),Ua=na?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-2.5 h-2.5 shrink-0 invisible","aria-hidden":"true"}),Oe.label,zt]}):e.jsxs(e.Fragment,{children:[Oe.label," ",zt]});return Fe==="utility"?e.jsxs("div",{className:"relative",style:rt,children:[e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("button",{className:Q(Oe.textAlign,"flex items-center gap-0.5 hover:text-slate-700 transition-colors w-full",Oe.justify),onClick:()=>Xa(Fe),"data-testid":`sort-${Fe}`,children:Ua})}),e.jsx(Wa,{side:"bottom",className:"text-xs max-w-[220px]",children:"Shows whether this comp's size falls within the market's typical buyer utility range"})]})}),$t]},Fe):e.jsxs("div",{className:"relative",style:rt,children:[e.jsx("button",{className:Q(Oe.textAlign,"flex items-center gap-0.5 hover:text-slate-700 transition-colors w-full",Oe.justify),onClick:()=>Xa(Fe),"data-testid":`sort-${Fe}`,children:Ua}),$t]},Fe)}return e.jsxs("div",{className:Q("relative",Oe.textAlign,Oe.extraClass),style:rt,children:[Oe.label,$t]},Fe)},Xa=Fe=>{if(!v)return;const Oe=gj[Fe];if(!Oe)return;const rt=qb.includes(Fe),$t=rt?"asc":"desc",na=rt?"desc":"asc";f?.column===Oe?f.direction===$t?v({column:Oe,direction:na}):v(void 0):v({column:Oe,direction:$t})},qa=Fe=>{const Oe=gj[Fe];return!Oe||f?.column!==Oe?e.jsx(hN,{className:"w-2.5 h-2.5 opacity-40"}):f.direction==="desc"?e.jsx(gN,{className:"w-2.5 h-2.5 text-primary"}):e.jsx(xN,{className:"w-2.5 h-2.5 text-primary"})},os=160,ya=Re.reduce((Fe,Oe)=>Fe+fe[Oe],0),At=os+ya+(Re.length-1)*6+16;return e.jsxs("div",{className:"flex flex-col h-full bg-white","data-testid":"property-rail",children:[e.jsx("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-slate-100 bg-slate-50/50 shrink-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[11px] text-slate-500","data-testid":"list-count-header",children:[_===null?D&&!r?`${He.length} properties`:"Loading properties…":`${_??He.length} properties`," · ",u," selected",r&&t.length>0&&e.jsx(za,{className:"w-3 h-3 animate-spin inline ml-1.5 text-slate-400"})]}),e.jsx(RV,{}),u>0&&e.jsxs("button",{onClick:R,"data-testid":"badge-selected-count",title:E?"Show all properties":"Show selected only",className:Q("flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors",E?"bg-green-600 text-white ring-1 ring-green-300":"bg-green-100 text-green-700 hover:bg-green-200"),children:[e.jsx(QO,{className:"w-2.5 h-2.5 fill-current"}),E?"Selected":""]})]})}),e.jsx("div",{ref:W,className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:D&&t.length===0&&!r?e.jsxs("div",{className:"p-8 text-center text-slate-500 flex-1 flex flex-col items-center justify-center","data-testid":"empty-state-message",children:[e.jsx("p",{children:"No properties match your search."}),e.jsx("p",{className:"text-xs mt-1",children:"Try clearing the keyword or adju
14sting your filters."})]}):F&&t.length===0&&!ae?e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center py-16 text-center","data-testid":"no-boundary-prompt-rail",children:[e.jsx(Wl,{className:"w-10 h-10 text-slate-300 mb-3"}),e.jsx("p",{className:"text-sm font-medium text-slate-500",children:"Draw a boundary on the map to find comps"}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:"Use the map tools to draw a radius or polygon, or pick a saved boundary"})]}):!D&&!F&&!r&&_===0&&t.length===0?e.jsxs("div",{className:"p-8 text-center text-slate-500 flex-1 flex flex-col items-center justify-center","data-testid":"empty-state-no-results",children:[e.jsx(Fo,{className:"w-8 h-8 mx-auto mb-2 opacity-30"}),e.jsx("p",{children:"No properties found"}),e.jsx("p",{className:"text-xs mt-1",children:"Try adjusting your filters or expanding the search area."})]}):(r||ae)&&t.length===0?e.jsxs("div",{className:"flex-1 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3 border-b border-slate-100","data-testid":"list-search-loading-message",children:[e.jsx(za,{className:"w-4 h-4 animate-spin text-blue-500"}),e.jsx("span",{className:"text-sm text-slate-500 font-medium","data-testid":"text-loading-phase",children:n||"Loading nearby sales..."})]}),e.jsx("div",{className:"divide-y divide-slate-100",children:[...Array(6)].map((Fe,Oe)=>e.jsxs("div",{className:"flex gap-3 p-3 animate-pulse","data-testid":`skeleton-row-${Oe}`,children:[e.jsx("div",{className:"w-28 h-24 flex-shrink-0 rounded-lg bg-slate-200"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[e.jsx("div",{className:"h-3 bg-slate-200 rounded w-16"}),e.jsx("div",{className:"h-4 bg-slate-200 rounded w-3/4"}),e.jsx("div",{className:"h-6 bg-slate-200 rounded w-24"}),e.jsxs("div",{className:"flex gap-3 mt-2",children:[e.jsx("div",{className:"h-3 bg-slate-200 rounded w-12"}),e.jsx("div",{className:"h-3 bg-slate-200 rounded w-12"}),e.jsx("div",{className:"h-3 bg-slate-200 rounded w-16"})]})]})]},Oe))})]}):!r&&t.length===0&&oe?e.jsxs("div",{className:"p-8 text-center text-slate-500 flex-1 flex flex-col items-center justify-center","data-testid":"preloading-state-message",children:[e.jsx(za,{className:"w-8 h-8 mx-auto mb-2 opacity-50 animate-spin text-blue-400"}),e.jsx("p",{children:"Loading properties..."}),e.jsx("p",{className:"text-xs mt-1",children:"Properties are being fetched for this area"})]}):!r&&t.length===0?e.jsxs("div",{className:"p-8 text-center text-slate-500 flex-1 flex flex-col items-center justify-center","data-testid":"empty-state-message",children:[e.jsx(Fo,{className:"w-8 h-8 mx-auto mb-2 opacity-30"}),e.jsx("p",{children:U||"No properties found"}),e.jsx("p",{className:"text-xs mt-1",children:C||"Try adjusting your filters"})]}):S==="list"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:me,className:"overflow-x-hidden shrink-0","data-testid":"list-header-scroll-wrapper",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1.5 text-[10px] font-medium text-slate-500 uppercase tracking-wider border-b border-slate-100 bg-slate-50 shrink-0",style:{minWidth:At},"data-testid":"list-header",children:[e.jsx("div",{className:"w-[58px] shrink-0"}),e.jsx("div",{className:"w-11 shrink-0 text-center"}),e.jsxs(xn,{open:z,onOpenChange:V,children:[e.jsx(bn,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 shrink-0","data-testid":"column-picker-toggle",children:e.jsx(R5,{className:"w-3.5 h-3.5"})})}),e.jsx(yn,{side:"bottom",align:"start",className:"w-56 p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-slate-700 px-2 pb-1 border-b",children:"Show Columns"}),e.jsx("div",{className:"max-h-64 overflow-y-auto space-y-0.5",children:ne.map((Fe,Oe)=>{const rt=GG[Fe];return!rt||$&&qb.includes(Fe)?null:e.jsxs("div",{draggable:!0,onDragStart:()=>je(Oe),onDragEnter:()=>Le(Oe),onDragEnd:st,onDragOver:$t=>$t.preventDefault(),className:"flex items-center gap-1.5 px-2 py-1 rounded hover:bg-slate-50 cursor-grab active:cursor-grabbing select-none","data-testid":`column-picker-item-${rt.key}`,children:[e.jsx(pN,{className:"w-3 h-3 text-slate-300 shrink-0"}),e.jsx(Pa,{checked:ua(rt.key),onCheckedChange:()=>Xt(rt.key),"data-testid":`column-toggle-${rt.key}`}),e.jsx("span",{className:"text-xs text-slate-600",children:rt.label})]},rt.key)})}),O&&e.jsx("div",{className:"pt-2 border-t",children:e.jsxs(De,{size:"sm",variant:"outline",className:"w-full h-7 text-xs gap-1.5",onClick:()=>{O(),V(!1)},"data-testid":"save-columns-default",children:[e.jsx(ZO,{className:"w-3 h-3"}),"Save as Default"]})})]})})]}),Re.map(Fe=>Oa(Fe))]}),G&&S==="list"&&e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1.5 text-xs bg-[#FAF0E6]/60 border-b border-amber-200/60 shrink-0 relative",style:{boxShadow:"inset 3px 0 0 0 rgb(99 102 241)",minWidth:At},"data-testid":"subject-row",children:[e.jsx("div",{className:"w-[58px] shrink-0"}),e.jsx("div",{className:"w-11 h-8 shrink-0 rounded overflow-hidden bg-slate-200",children:G.photoUrl?e.jsx("img",{src:MI(G.photoUrl),alt:"Subject",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fo,{className:"w-4 h-4 text-slate-400"})})}),e.jsx("div",{className:"w-6 shrink-0"}),Re.map(Fe=>{const Oe=ge(Fe),rt={status:e.jsx(kt,{className:"h-5 text-[10px] justify-center bg-indigo-100 text-indigo-700 hover:bg-indigo-100",style:Oe,children:"Subject"}),address:e.jsx("div",{className:"truncate font-semibold text-slate-800",style:Oe,title:G.address,children:G.address}),city:e.jsx("div",{className:"truncate text-slate-600 text-[10px]",style:Oe,children:G.city||"–"}),price:e.jsx("div",{className:"font-semibold text-slate-900 text-right",style:Oe,children:G.price&&G.price>
140?`$${G.price.toLocaleString()}`:"–"}),beds:e.jsx("div",{className:"text-slate-700 font-medium text-center",style:Oe,children:G.beds??"–"}),baths:e.jsx("div",{className:"text-slate-700 font-medium text-center",style:Oe,children:yg(G.fullBathrooms,G.halfBathrooms,G.baths)}),sqft:e.jsx("div",{className:"text-slate-700 font-medium text-right",style:Oe,children:G.gla?G.gla.toLocaleString():"–"}),sqftPR:e.jsx("div",{className:"text-right",style:Oe,children:"–"}),lotSqft:e.jsx("div",{className:"text-slate-700 text-right",style:Oe,children:G.lotSqft?G.lotSqft.toLocaleString():"–"}),lotSqftPR:e.jsx("div",{className:"text-right",style:Oe,children:"–"}),distance:e.jsx("div",{className:"text-center text-slate-400",style:Oe,children:"–"}),listDate:e.jsx("div",{className:"text-center text-slate-400",style:Oe,children:"–"}),closeDate:e.jsx("div",{className:"text-center text-slate-400",style:Oe,children:"–"}),dom:e.jsx("div",{className:"text-center text-slate-400",style:Oe,children:"–"}),yearBuilt:e.jsx("div",{className:"text-slate-700 font-medium text-center",style:Oe,children:G.yearBuilt??"–"}),condition:e.jsx("div",{className:"text-center text-[10px] font-semibold text-slate-700",style:Oe,children:G.condition||"–"}),quality:e.jsx("div",{className:"text-center text-[10px] font-semibold text-slate-700",style:Oe,children:G.quality||"–"}),locationScore:e.jsx("div",{className:Q("text-center text-[10px] font-semibold rounded px-1",G.locationTier==="Positive"?"bg-green-50 text-green-700":G.locationTier==="Adverse"?"bg-red-50 text-red-700":"bg-slate-50 text-slate-600"),style:Oe,children:G.locationScore!=null?G.locationScore:"–"}),matchScore:e.jsx("div",{className:"text-center text-slate-400",style:Oe,children:"–"}),avmScore:e.jsx("div",{className:"text-center text-slate-400",style:Oe,children:"–"}),utility:e.jsx("div",{className:"text-center text-slate-400",style:Oe,children:"–"}),basement:e.jsx("div",{className:"text-center text-[10px] text-slate-700 truncate",style:Oe,title:G.basement||void 0,children:G.basement||"–"}),style:e.jsx("div",{className:"text-center text-[10px] text-slate-700 truncate",style:Oe,title:G.style||void 0,children:G.style||"–"}),nightlyRate:e.jsx("div",{className:"text-right text-slate-400",style:Oe,children:"–"}),occupancy:e.jsx("div",{className:"text-center text-slate-400",style:Oe,children:"–"})};return e.jsx(Mn.Fragment,{children:rt[Fe]},Fe)})]})]}),e.jsx("div",{className:"flex-1 min-h-0 py-2",children:e.jsx(GR,{height:Math.max(pe-(G?72:40),200),itemCount:He.length,itemSize:Pe,width:"100%",outerRef:Z,className:"scrollbar-thin scrollbar-thumb-slate-300",itemData:{displayProperties:He,comparisonDataSource:b,hoveredPropertyId:i,isColumnVisible:ua,columnOrder:Re,subjectElsFactors:y,aiAnalysisReady:M,elsLoaded:B,isPropertySelected:Be,columnWidths:fe,totalRowWidth:At},children:({index:Fe,style:Oe,data:rt})=>{const{displayProperties:$t,comparisonDataSource:na,hoveredPropertyId:zt,columnOrder:Ua,subjectElsFactors:Ce,aiAnalysisReady:St,elsLoaded:vt,isPropertySelected:Ve,columnWidths:sa,totalRowWidth:tt}=rt,it=$t[Fe],Je=Ve(it);return e.jsx("div",{style:{...Oe,minWidth:tt},children:e.jsx(XG,{property:it,isSelected:Je,isHovered:zt===it.id,columnOrder:Ua,glaDataSource:na,onHoverProperty:l,onClickProperty:c,onSelectProperty:d,onDeselectProperty:p,onFocusOnMap:N,subjectElsFactors:Ce,aiAnalysisReady:St,elsLoaded:vt,columnWidths:sa},it.id)})}})})]}):e.jsx(GR,{height:pe,itemCount:He.length,itemSize:ce,width:"100%",className:"scrollbar-thin scrollbar-thumb-slate-300",itemData:{displayProperties:He,comparisonDataSource:b,hoveredPropertyId:i,usingPublicRecord:le,subjectElsFactors:y,isPropertySelected:Be},children:({index:Fe,style:Oe,data:rt})=>{const{displayProperties:$t,comparisonDataSource:na,hoveredPropertyId:zt,usingPublicRecord:Ua,subjectElsFactors:Ce,isPropertySelected:St}=rt,vt=$t[Fe],Ve=St(vt);return e.jsx("div",{style:Oe,className:"border-b border-slate-100",children:e.jsx(JG,{property:vt,isSelected:Ve,isHovered:zt===vt.id,onHoverProperty:l,onClickProperty:c,onSelectProperty:d,onDeselectProperty:p,onFocusOnMap:N,onElsOverride:x,subjectElsFactors:Ce,usingPublicRecord:Ua,glaDataSource:na},vt.id)})}})})]})}const JG=Mn.memo(function({property:a,isSelected:s,isHovered:r,onHoverProperty:n,onClickProperty:i,onSelectProperty:l,onDeselectProperty:c,onFocusOnMap:d,onElsOverride:p,subjectElsFactors:u,usingPublicRecord:m=!1,glaDataSource:h}){const f=s??!!a.isSelected,v=a.isStrProperty||a.propertyType==="STR"||a.status==="STR",S=a.status==="CLSD";a.status;const N=jN(a.rawMlsStatus||a.status),x=N!==null,y=UI(a.rawMlsStatus||a.status),b=v?"Rental":S?"House Sold":N==="underContract"?"Under Contract":N==="contingent"?"Contingent":x?"For Sale":"Pending",j=y&&!S&&!v?`${b} (Private)`:b,T=v?"text-purple-600":S?"text-slate-600":N==="underContract"?"text-blue-600":N==="contingent"?"text-teal-600":x?"text-green-600":"text-amber-600",O=h||(m?"public-record":"mls"),E=typeof a.sqft=="number"&&a.sqft>0,R=typeof a.sqftPR=="number"&&a.sqftPR>0,G=typeof a.btNormalizedGla=="number"&&a.btNormalizedGla>0,U=O==="ai"?G?a.btNormalizedGla:E?a.sqft:R?a.sqftPR:null:O==="public-record"?R?a.sqftPR:null:E?a.sqft:null,C=m?a.yearBuiltPR??a.yearBuilt:a.yearBuilt,F=O==="ai"&&G,A=F&&a.sqft&&a.btNormalizedGla!==a.sqft,M=v?a.strAverageDailyRate||0:a.price??0,B=!v&&U&&a.price?Math.round(a.price/U):null,oe=_=>{_.stopPropagation(),f?c(a):l(a)},ae=_=>{_.stopPropagation(),d&&d(a)},D=!!a.isSameAsSubject&&!a.isSubject;return e.jsxs("div",{id:`property-card-${a.id}`,className:Q("flex gap-3 p-3 cursor-pointer transition-all",r&&"bg-blue-50",f&&"bg-green-50 border-l-4 border-l-green-500",D&&"bg-[#FAF0E6]/60 border-l-4 border-l-indigo-500"),onMouseEnter:()=>n(a.id),onMouseLeave:()=>n(null),onClick:()=>i(a),"data-testid":`property-card-${a.id}`,children:[e.jsxs("div",{className:"relative w-28 h-24 flex-shrink-0 rounded-lg overflow-hidden bg-slate-200 group",onClick:ae,title:"Click to focus on map",children:[a.photoUrl?e.jsx("img",{src:rb(a.photoUrl),alt:a.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform",loading:"lazy",decoding:"async"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fo,{className:"w-8 h-8 text-slate-400"})}),a.photoCount&&a.photoCount>0&&e.jsxs("div",{className:"absolute bottom-1 left-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded flex items-center gap-1",children:[e.jsx(xg,{className:"w-3 h-3"}),a.photoCount," photos"]}),e.jsxs("button",{className:Q("absolute top-1.5 right-1.5 flex items-center gap-0.5 px-2 py-0.5 rounded text-[9px] font-semibold transition-colors shadow-sm",f?"bg-[#C5A572] text-white hover:bg-[#A18A60]":"bg-[#072034] text-white hover:bg-[#0a2f4c]"),onClick:oe,"data-testid":`btn-add-comp-card-${a.id}`,children:[e.jsx(Bs,{size:9})," ",f?"Selected":"Add"]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[D?e.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-bold uppercase bg-indigo-100 text-indigo-700",title:"This listing is the subject property.","data-testid":`badge-same-as-subject-${a.id}`,children:"Same as Subject"}):e.jsx("div",{className:Q("text-[11px] font-medium",T),children:j}),e.jsxs("div",{className:Q("text-xs truncate mt-0.5",D?"font-semibold text-slate-800":"text-slate-600"),"data-testid":`address-${a.id}`,children:[a.address,a.city?`, ${a.city}`:""]})]}),a.dom!==void 0&&S&&e.jsxs("div",{className:"text-[10px] text-slate-400 whitespace-nowrap",children:[a.dom," days ago"]})]}),e.jsx("div",{className:"text-lg font-bold text-slate-900 mt-1",children:v?M>0?`$${M}
14/night`:"–":a.price?`$${a.price.toLocaleString()}`:S?"Price Pending":"N/A"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-slate-600",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-medium",children:a.beds??"–"}),e.jsx("span",{className:"text-slate-400",children:"bd"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"font-medium",children:yg(a.fullBathrooms,a.halfBathrooms,a.baths)}),e.jsx("span",{className:"text-slate-400",children:"ba"})]}),U!==void 0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:Q("font-medium",O==="public-record"&&U?"text-blue-600":F?"text-indigo-600":"",!U&&"text-slate-400 italic"),children:U?U.toLocaleString():"–"}),e.jsx("span",{className:"text-slate-400",children:U?"sqft":""}),O==="public-record"&&U&&e.jsx("span",{className:"text-[9px] text-blue-500 font-medium",children:"PR"}),F&&e.jsxs(xn,{children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{className:Q("text-[9px] font-medium px-1 rounded cursor-pointer hover:opacity-80 inline-flex items-center gap-0.5",a.glaSanityFlag==="critical"?"text-red-600 bg-red-50":a.glaSanityFlag==="warning"?"text-amber-600 bg-amber-50":"text-indigo-500 bg-indigo-50"),onClick:_=>_.stopPropagation(),"data-testid":`gla-ai-badge-${a.id}`,children:[a.glaSanityFlag==="critical"&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-red-500 inline-block"}),a.glaSanityFlag==="warning"&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-500 inline-block"}),"AI"]})}),e.jsx(yn,{side:"left",align:"start",className:"w-72 p-3 text-xs",onClick:_=>_.stopPropagation(),children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-semibold text-slate-700",children:"GLA Normalization v3.0"}),e.jsxs("span",{className:Q("text-[10px] font-medium px-1.5 py-0.5 rounded",(a.btGlaConfidence??0)>=80?"bg-green-100 text-green-700":(a.btGlaConfidence??0)>=60?"bg-amber-100 text-amber-700":"bg-slate-100 text-slate-600"),children:[a.btGlaConfidence??0,"% confidence"]})]}),e.jsxs("div",{className:"border-t border-slate-100 pt-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-500",children:"MLS GLA"}),e.jsx("span",{className:"font-medium tabular-nums",children:a.sqft?a.sqft.toLocaleString()+" SF":"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-500",children:"Public Record"}),e.jsx("span",{className:"font-medium tabular-nums",children:a.sqftPR?a.sqftPR.toLocaleString()+" SF":"—"})]}),a.roomMathGla&&a.roomMathGla>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-500",children:"Room-Math"}),e.jsxs("span",{className:"font-medium tabular-nums",children:[a.roomMathGla.toLocaleString()," SF",a.roomMathAgreement==="confirms"&&e.jsx("span",{className:"ml-1 text-green-600",children:"✓"}),a.roomMathAgreement==="contradicts"&&e.jsx("span",{className:"ml-1 text-red-500",children:"✗"})]})]}),e.jsxs("div",{className:"flex justify-between border-t border-slate-100 pt-1",children:[e.jsx("span",{className:"font-semibold text-indigo-700",children:"Result"}),e.jsxs("span",{className:"font-semibold tabular-nums text-indigo-700",children:[a.btNormalizedGla?.toLocaleString()," SF"]})]}),a.btGlaSource&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-slate-500",children:"Source"}),e.jsx("span",{className:"text-slate-600",children:a.btGlaSource==="consensus"?"Consensus (MLS+PR agree)":a.btGlaSource==="publicRecord"?"Public Record":a.btGlaSource==="mlsAboveGrade"?"MLS Above Grade":a.btGlaSource==="derived"?"Room-Math Derived":a.btGlaSource==="floorPlan"?"Floor Plan":a.btGlaSource})]})]}),a.glaSanityFlag&&a.glaSanityFlag!=="plausible"&&e.jsx("div",{className:Q("rounded px-2 py-1 text-[10px]",a.glaSanityFlag==="critical"?"bg-red-50 text-red-700":"bg-amber-50 text-amber-700"),children:a.glaSanityFlag==="critical"?"Bed/bath sanity check: CRITICAL — GLA far outside expected range":"Bed/bath sanity check: WARNING — GLA outside expected range"}),a.btGlaNormNote&&e.jsx("p",{className:"text-[10px] text-slate-400 leading-tight mt-1 line-clamp-3",children:a.btGlaNormNote})]})})]}),A&&e.jsx("span",{className:"text-[9px] text-amber-500",title:`MLS: ${a.sqft?.toLocaleStr
14ing()}`,children:"≠"}),a.glaBandTier&&e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("span",{className:Q("inline-block w-2 h-2 rounded-full flex-shrink-0",a.glaBandTier==="green"?"bg-emerald-500":a.glaBandTier==="yellow"?"bg-amber-500":"bg-red-500"),"data-testid":`gla-utility-dot-${a.id}`})}),e.jsx(Wa,{side:"left",className:"text-xs max-w-[240px]",children:a.glaBandTier==="green"?"This comp's size is close enough to the subject that most buyers wouldn't see a difference. A GLA adjustment probably isn't needed.":a.glaBandTier==="yellow"?"This comp's size is starting to differ from what's typical in this market. Consider whether a GLA adjustment is appropriate.":"This comp's size falls outside the typical range for this market. A GLA adjustment is likely needed."})]})})]}),B&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsxs("span",{className:"font-medium",children:["$",B]}),e.jsx("span",{className:"text-slate-400",children:"/sf"})]}),C&&e.jsxs("span",{className:Q("text-slate-400",m&&a.yearBuiltPR&&"text-blue-500"),children:[C," built",m&&a.yearBuiltPR&&e.jsx("span",{className:"text-[9px] text-blue-500 font-medium ml-0.5",children:"PR"})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[a.roomCount&&a.roomCount>0&&e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(kt,{variant:"outline",className:"h-5 text-[10px] font-medium px-1.5 bg-teal-50 text-teal-700 border-teal-200 cursor-help","data-testid":`room-badge-${a.id}`,children:[e.jsx(JO,{className:"w-3 h-3 mr-0.5"}),a.roomCount]})}),e.jsxs(Wa,{side:"left",className:"text-xs",children:[e.jsxs("p",{className:"font-medium",children:[a.roomCount," rooms with dimensions"]}),a.roomMathGla&&e.jsxs("p",{className:"text-slate-500",children:["Room-Math GLA: ",a.roomMathGla.toLocaleString()," sqft"]})]})]})}),a.qualityRating&&e.jsx(kt,{variant:"outline",className:Q("h-5 text-[10px] font-semibold px-1.5",a.qualitySource==="ai"?"bg-purple-50 text-purple-700 border-purple-200":"bg-slate-50 text-slate-600 border-slate-200"),title:`Quality ${a.qualityRating}${a.qualitySource==="ai"?" (AI)":""}`,children:a.qualityRating}),a.conditionRating&&e.jsx(kt,{variant:"outline",className:Q("h-5 text-[10px] font-semibold px-1.5",a.conditionSource==="ai"?"bg-purple-50 text-purple-700 border-purple-200":"bg-slate-50 text-slate-600 border-slate-200"),title:`Condition ${a.conditionRating}${a.conditionSource==="ai"?" (AI)":""}`,children:a.conditionRating}),e.jsxs("div",{className:"text-[11px] text-slate-400",children:[a.dom," days on site"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[a.echoLocationScore&&a.echoLocationScore.score>=0&&e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(kt,{variant:"outline",className:Q("h-5 text-[10px] font-semibold px-1.5 cursor-help",a.echoLocationScore.tier==="Positive"?"bg-green-50 text-green-700 border-green-200":a.echoLocationScore.tier==="Adverse"?"bg-red-50 text-red-700 border-red-200":"bg-amber-50 text-amber-700 border-amber-200"),children:[a.echoLocationScore.isPartial?"~":"L:",a.echoLocationScore.score]})}),e.jsxs(Wa,{side:"left",className:"text-xs min-w-[140px]",children:[e.jsxs("div",{className:"font-medium mb-2",children:["Location Score: ",a.echoLocationScore.score,"/100",a.echoLocationScore.isPartial?" (partial)":""]}),a.echoLocationScore.isPartial&&e.jsx("div",{className:"mb-2 text-amber-600 text-[10px]",children:"Partial data — OSM unavailable, score based on limited sources"}),e.jsx(Tk,{factors:a.echoLocationScore.factors}),a.echoLocationScore.isOverridden&&e.jsx("div",{className:"mt-2 text-blue-500 text-[10px]",children:"Appraiser override"})]})]})}),u&&a.echoLocationScore?.factors&&e.jsx(QG,{divergences:jk(u,a.echoLocationScore.factors)}),(a.matchScore!==void 0||a.similarityScore!==void 0)&&e.jsx(gr,{delayDuration:150,disableHoverableContent:!1,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(kt,{variant:"outline",className:Q("h-5 text-[10px] font-medium cursor-help",(a.matchScore??a.similarityScore??0)>=70?"bg-green-50 text-green-700 border-green-200":(a.matchScore??a.similarityScore??0)>=40?"bg-amber-50 text-amber-700 border-amber-200":"bg-slate-50 text-slate-600 border-slate-200"),children:[a.matchScore??a.similarityScore,"%"]})}),e.jsxs(Wa,{side:"left",className:"text-xs min-w-[120px] bg-white text-slate-800 border border-slate-200 shadow-md p-3 rounded-lg",children:[e.jsx("div",{className:"font-semibold mb-2 text-slate-800",children:"Match Score Breakdown"}),e.jsx(Ak,{breakdown:a.matchBreakdown})]})]})})]})]})]})]})}),XG=Mn.memo(function({property:a,isSelected:s,isHovered:r,onHoverProperty:n,onClickProperty:i,onSelectProperty:l,onDeselectProperty:c,onFocusOnMap:d,subjectElsFactors:p,glaDataSource:u,usingPublicRecord:m,isColumnVisible:h=()=>!0,columnOrder:f,aiAnalysisReady:v=!1,elsLoaded:S=!1,columnWidths:N}
14){const x=s??!!a.isSelected,y=u||(m?"public-record":"mls"),b=typeof a.sqft=="number"&&a.sqft>0,j=typeof a.sqftPR=="number"&&a.sqftPR>0,T=typeof a.btNormalizedGla=="number"&&a.btNormalizedGla>0,O=y==="ai"?T?a.btNormalizedGla:b?a.sqft:j?a.sqftPR:null:y==="public-record"?j?a.sqftPR:null:b?a.sqft:null,E=y==="ai"&&T,R=y==="public-record"&&j,G=a.isStrProperty||a.propertyType==="STR"||a.status==="STR",U=a.status==="CLSD",C=a.status==="PEND",F=jN(a.rawMlsStatus||a.status),A=F!==null,M=UI(a.rawMlsStatus||a.status),B=G?"Rental":U?"Sold":F==="underContract"?"Under Contract":F==="contingent"?"Contingent":A?"Active":C?"Pending":a.status||"–",oe=M&&!U&&!G?`${B} (Private)`:B,ae=G?"bg-purple-100 text-purple-700":U?"bg-red-100 text-red-700":F==="underContract"?"bg-blue-100 text-blue-700":F==="contingent"?"bg-teal-100 text-teal-700":A?"bg-green-100 text-green-700":"bg-amber-100 text-amber-700",D=G?a.strAverageDailyRate||0:U?a.price??0:a.listPrice??a.price??0,_=Z=>Z&&E2(Z)||"–",$=Z=>Z==null?"–":Z<.1?`${Z.toFixed(2)} mi`:`${Z.toFixed(1)} mi`,z=Z=>{Z.stopPropagation(),x?c(a):l(a)},V=()=>{d&&d(a),i(a)},le=N||Nk,W=Z=>({width:le[Z],minWidth:le[Z],maxWidth:le[Z],flexShrink:0}),me=!!a.isSameAsSubject&&!a.isSubject;return e.jsxs("div",{id:`property-card-${a.id}`,className:Q("flex items-center gap-1.5 px-2 py-1.5 rounded cursor-pointer text-xs transition-all",r&&"bg-blue-50",x&&"bg-green-50 ring-1 ring-green-300",me&&"bg-[#FAF0E6]/60"),style:me?{boxShadow:"inset 3px 0 0 0 rgb(99 102 241)"}:void 0,onMouseEnter:()=>n(a.id),onMouseLeave:()=>n(null),onClick:V,"data-testid":`property-list-${a.id}`,children:[e.jsxs("button",{className:Q("shrink-0 flex items-center justify-center gap-0.5 w-[58px] py-0.5 rounded text-[9px] font-semibold transition-colors",x?"bg-[#C5A572] text-white hover:bg-[#A18A60]":"bg-[#072034] text-white hover:bg-[#0a2f4c]"),onClick:z,"data-testid":`btn-add-comp-list-${a.id}`,children:[e.jsx(Bs,{size:9})," ",x?"Selected":"Add"]}),e.jsx("div",{className:"w-11 h-8 shrink-0 rounded overflow-hidden bg-slate-200",children:a.photoUrl?e.jsx("img",{src:MI(a.photoUrl),alt:a.address,className:"w-full h-full object-cover",loading:"lazy",decoding:"async"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Fo,{className:"w-4 h-4 text-slate-400"})})}),e.jsx("div",{className:"w-6 shrink-0"}),(f||fg.map(Z=>Z.key).filter(Z=>h(Z))).map(Z=>{const pe=W(Z),se={status:me?e.jsx(kt,{className:"h-5 text-[10px] justify-center bg-indigo-100 text-indigo-700 hover:bg-indigo-100",style:pe,title:"This listing is the subject property.","data-testid":`badge-same-as-subject-${a.id}`,children:"Same as Subject"}):e.jsx(kt,{className:Q("h-5 text-[10px] justify-center",ae),style:pe,children:oe}),address:e.jsx("div",{className:Q("truncate",me?"font-semibold text-slate-800":"text-slate-700"),style:pe,title:me?`${a.address} — Same as subject property`:a.address,children:a.address}),city:e.jsx("div",{className:"truncate text-slate-500 text-[10px]",style:pe,children:a.city||"–"}),price:e.jsx("div",{className:"font-semibold text-slate-900 text-right",style:pe,title:G?"Nightly Rate":U?"Sale Price":"List Price",children:G?D>0?`$${D}/nt`:"–":D>0?`$${D.toLocaleString()}`:"–"}),beds:e.jsx("div",{className:"text-slate-600 text-center",style:pe,children:a.beds??"–"}),baths:e.jsx("div",{className:"text-slate-600 text-center",style:pe,children:yg(a.fullBathrooms,a.halfBathrooms,a.baths)}),sqft:e.jsx("div",{className:Q("text-right flex items-center justify-end gap-0.5",O?E&&a.glaSanityFlag==="critical"?"text-red-600 font-medium":E&&a.glaSanityFlag==="warning"?"text-amber-600 font-medium":E?"text-indigo-600 font-medium":R?"text-blue-600":"text-slate-600":"text-slate-400 italic"),style:pe,children:e.jsx("span",{children:O?O.toLocaleString():"–"})}),sqftPR:e.jsx("div",{className:"text-blue-600 text-right",style:pe,children:a.sqftPR?a.sqftPR.toLocaleString():"–"}),lotSqft:e.jsx("div",{className:"text-slate-600 text-right",style:pe,children:a.lotSqft?a.lotSqft.toLocaleString():"–"}),lotSqftPR:e.jsx("div",{className:"text-blue-600 text-right",style:pe,children:a.lotSqftPR?a.lotSqftPR.toLocaleStr
14ing():"–"}),distance:e.jsx("div",{className:"text-slate-500 text-center",style:pe,title:`${a.distance?.toFixed(2)||"–"} miles from subject`,children:$(a.distance)}),listDate:e.jsx("div",{className:"text-slate-500 text-center",style:pe,title:a.listDate||"No list date",children:_(a.listDate)}),closeDate:e.jsx("div",{className:"text-slate-500 text-center",style:pe,title:a.saleDate||"No close date",children:U?_(a.saleDate):"–"}),dom:e.jsx("div",{className:"text-slate-500 text-center",style:pe,title:"Days on Market",children:a.dom??"–"}),yearBuilt:e.jsx("div",{className:"text-slate-500 text-center",style:pe,children:a.yearBuilt??"–"}),condition:e.jsx("div",{className:Q("text-center text-[10px] font-semibold flex items-center justify-center",a.conditionRating?a.conditionSource==="ai"?"text-purple-700":"text-slate-600":"text-slate-400"),style:pe,title:a.conditionRating?`Condition ${a.conditionRating}${a.conditionSource==="ai"?" (AI)":""}`:!v&&(a.photos?.length??0)>0?"AI analysis pending":"No condition rating available","data-testid":`condition-col-${a.id}`,children:a.conditionRating?a.conditionRating:!v&&(a.photos?.length??0)>0?e.jsx(za,{className:"w-3 h-3 animate-spin text-slate-400"}):e.jsx("span",{className:"text-[9px] text-slate-300",children:"—"})}),quality:e.jsx("div",{className:Q("text-center text-[10px] font-semibold flex items-center justify-center",a.qualityRating?a.qualitySource==="ai"?"text-purple-700":"text-slate-600":"text-slate-400"),style:pe,title:a.qualityRating?`Quality ${a.qualityRating}${a.qualitySource==="ai"?" (AI)":""}`:!v&&(a.photos?.length??0)>0?"AI analysis pending":"No quality rating available","data-testid":`quality-col-${a.id}`,children:a.qualityRating?a.qualityRating:!v&&(a.photos?.length??0)>0?e.jsx(za,{className:"w-3 h-3 animate-spin text-slate-400"}):e.jsx("span",{className:"text-[9px] text-slate-300",children:"—"})}),locationScore:a.echoLocationScore&&a.echoLocationScore.score>=0?e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("div",{className:Q("text-center text-[10px] font-semibold cursor-help rounded px-1",a.echoLocationScore.isPartial?"bg-slate-100 text-slate-500":a.echoLocationScore.tier==="Positive"?"bg-green-50 text-green-700":a.echoLocationScore.tier==="Adverse"?"bg-red-50 text-red-700":"bg-amber-50 text-amber-700"),style:pe,"data-testid":`location-col-${a.id}`,children:[a.echoLocationScore.isPartial?"~":"",a.echoLocationScore.score]})}),e.jsxs(Wa,{side:"left",className:"text-xs min-w-[140px]",children:[e.jsxs("div",{className:"font-medium mb-2",children:["Location Score: ",a.echoLocationScore.score,"/100 (",a.echoLocationScore.tier,")",a.echoLocationScore.isPartial?" — partial":""]}),a.echoLocationScore.isPartial&&e.jsx("div",{className:"mb-2 text-amber-600 text-[10px]",children:"Partial data — score based on limited sources"}),e.jsx(Tk,{factors:a.echoLocationScore.factors}),a.echoLocationScore.isOverridden&&e.jsx("div",{className:"mt-2 text-blue-500 text-[10px]",children:"Appraiser override"}),p&&a.echoLocationScore.factors&&(()=>{const fe=jk(p,a.echoLocationScore.factors);return fe.length?e.jsxs("div",{className:"mt-2 pt-2 border-t border-slate-200",children:[e.jsx("div",{className:"font-medium text-[10px] text-slate-500 mb-1",children:"vs Subject:"}),fe.slice(0,4).map(ue=>e.jsxs("div",{className:Q("text-[10px]",ue.severity==="major"?"text-red-600":"text-amber-600"),children:[ue.factorName,": ",ue.delta>0?"+":"",ue.delta," pts"]},ue.factorName))]}):null})()]})]})}):a.echoLocationScore?.score===-1?e.jsx("div",{className:"text-center text-[10px] text-slate-300",style:pe,"data-testid":`location-col-${a.id}`,title:"Location score unavailable",children:"—"}):e.jsx("div",{className:"text-center text-[10px] text-slate-400 flex items-center justify-center",style:pe,title:S?"Location score unavailable":"Location score pending",children:S?e.jsx("span",{className:"text-[9px] text-slate-300",children:"—"}):e.jsx(za,{className:"w-3 h-3 animate-spin text-slate-400"})}),matchScore:a.matchScore!==void 0||a.similarityScore!==void 0?e.jsx(gr,{delayDuration:150,disableHoverableContent:!1,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(kt,{variant:"outline",className:Q("h-5 text-[10px] cursor-help justify-center",(a.matchScore??a.similarityScore??0)>=70?"bg-green-50 text-green-700 border-green-200":(a.matchScore??a.similarityScore??0)>=40?"bg-amber-50 text-amber-700 border-amber-200":"bg-slate-50 text-slate-600 border-slate-200"),style:pe,children:[a.matchScore??a.similarityScore,"%"]})}),e.jsxs(Wa,{side:"left",className:"text-xs min-w-[120px] bg-white text-slate-800 border border-slate-200 shadow-md p-3 rounded-lg",children:[e.jsx("div",{className:"font-semibold mb-2 text-slate-800",children:"Match Score Breakdown"}),e.jsx(Ak,{breakdown:a.matchBreakdown})]})]})}):e.jsx("div",{style:pe}),avmScore:a.avmScore!==void 0?e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(kt,{variant:"outline",className:Q("h-5 text-[10px] cursor-help justify-center",a.avmScore>=70?"bg-blue-50 text-blue-700 border-blue-200":a.avmScore>=40?"bg-amber-50 text-amber-700 border-amber-200":"bg-slate-50 text-slate-600 border-slate-200"),style:pe,children:Math.round(a.avmScore)})}),e.jsxs(Wa,{side:"left",className:"text-xs",children:[e.jsx("div",{className:"font-medium",children:"AVM Reconciliation Score"}),a.avmAdjustedPrice&&e.jsxs("div",{className:"text-slate-400 mt-1",children:["Adjusted: ",R2(a.avmAdjustedPrice,!0)]})]})]})}):e.jsx("div",{className:"text-center text-slate-300 text-[10px]",style:pe,children:"-"}),utility:a.glaBandTier?e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(kt,{variant:"outline",className:Q("h-5 text-[10px] font-medium cursor-help justify-center",a.glaBandTier==="green"?"bg-emerald-50 text-emerald-700 border-emerald-200":a.glaBandTier==="yellow"?"bg-amber-50 text-amber-700 border-amber-200":"bg-red-50 text-red-700 border-red-200"),style:pe,"data-testid":`gla-utility-badge-${a.id}`,children:a.glaBandTier==="green"?"Same":a.glaBandTier==="yellow"?"Sensitive":"Adjust"})}),e.jsx(Wa,{side:"left",className:"text-xs max-w-[240px]",children:a.glaBandTier==="green"?"This comp's size is close enough to the subject that most buyers wouldn't see a difference. A GLA adjustment probably isn't needed.":a.glaBandTier==="yellow"?"This comp's size is starting to differ from what's typical in this market. Consider whether a GLA adjustment is appropriate.":"This comp's size falls outside the typical range for this market. A GLA adjustment is likely needed."})]})}):e.jsx("div",{className:"text-center text-slate-300 text-[10px]",style:pe,children:"–"}),basement:e.jsx("div",{className:"text-center text-[10px] text-slate-600 truncate",style:pe,title:a.basement||void 0,children:a.basement||"–"}),style:e.jsx("div",{className:"text-center text-[10px] text-slate-600 truncate",style:pe,title:a.style||void 0,children:a.style||"–"}),nightlyRate:(()=>{const fe=typeof a.strAverageDailyRate=="number"&&a.strAverageDailyRate>0?a.strAverageDailyRate:null;return e.jsx("div",{className:Q("text-right tabular-nums",fe!==null?"text-slate-700":"text-slate-300"),style:pe,title:fe!==null?"Nightly rate (ADR, last 12 months)":"Nightly rate unavailable","data-testid":`nightly-rate-col-${a.id}`,children:fe!==null?`$${Math.round(fe)}`:"–"})})(),occupancy:(()=>{const fe=typeof a.strOccupancyRate=="number"&&a.strOccupancyRate>0?a.strOccupancyRate:null,ue=fe!==null?Math.round(fe*(fe<=1?100:1)):null;return e.jsx("div",{className:Q("text-center tabular-nums",ue!==null?"text-slate-700":"text-slate-300"),style:pe,title:ue!==null?"Occupancy rate (last 12 months)":"Occupancy unavailable","data-testid":`occupancy-col-${a.id}`,children:ue!==null?`${ue}%`:"–"})})()};return e.jsx(Mn.Fragment,{children:se[Z]},Z)})]})}),e7=["Most","Less","NoWeight"];function Zf(t){switch(t){case"Most":case"Less":case"NoWeight":return t;case"Average":return"Less";case"Exclude":return"NoWeight";default:return"Auto"}}const VT={Auto:"Auto",Most:"Most",Less:"Less",NoWeight:"No Weight"},dP={Most:3,Auto:2,Less:1,NoWeight:0};function t7(t,a){return Zf(t)===a?"Auto":a}function a7(t,a){const s=t.filter(i=>Number.isFinite(i.value)&&i.value>0),r=s.reduce((i,l)=>i+dP[l.weight],0);if(r<=0)return null;const n=s.reduce((i,l)=>i+l.value*dP[l.weight],0)/r;return Math.round(n/1e3)*1e3}function xj(t,a){if(t==="suggested"||t==="manual")return t;const s=parseFloat(String(a).replace(/[^0-9.]/g,""));return Number.isFinite(s)&&s>0?"manual":"suggested"}function s7({category:t,value:a,countsValue:s,otherDescription:r,onValueChange:n,onCountsChange:i,onOtherDescriptionChange:l,disabled:c,testId:d}){const p=g0[t],u=C_(a),m=R_(u,s),h=p.filter(x=>!u.includes(x)),f=u.includes("Other"),v=x=>{u.includes(x)||n(cE([...u,x]))},S=x=>{const y=u.filter(j=>j!==x),b={...m};delete b[x],n(y.length?cE(y):null),i(y.length?lE(y,b):null),x==="Other"&&l("")},N=(x,y)=>{i(lE(u,{...m,[x]:y}))};return e.jsxs("div",{className:"space-y-1.5","data-testid":d,children:[u.map(x=>{const y=x==="Other"&&r.trim()?r.trim():cl(x);return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"flex-1 truncate text-xs",title:y,children:y}),e.jsx(ze,{type:"number",value:m[x]??"",onChange:b=>N(x,b.target.value),readOnly:c,disabled:c,placeholder:"#",className:"h-7 w-14 text-xs","aria-label":`Count for ${cl(x)}`,"data-testid":d?`${d}-count-${x}`:void 0}),e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-muted-foreground hover:text-red-600",onClick:()=>S(x),disabled:c,title:"Remove amenity","aria-label":`Remove ${cl(x)}`,"data-testid":d?`${d}-remove-${x}`:void 0,children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]},x)}),f&&e.jsx(ze,{type:"text",value:r,onChange:x=>l(x.target.value),readOnly:c,disabled:c,placeholder:"Describe (Other)…",className:"h-7 text-xs","data-testid":d?`${d}-other`:void 0}),h.length>0&&e.jsxs(sr,{value:void 0,onValueChange:x=>
14v(x),disabled:c,children:[e.jsx(rr,{className:"h-7 text-xs","data-testid":d?`${d}-add`:void 0,children:e.jsx(or,{placeholder:"Add amenity…"})}),e.jsx(nr,{children:h.map(x=>e.jsx(vs,{value:x,children:cl(x)},x))})]},u.length)]})}const Ik={mls:"MLS",public_records:"PR",inspection:"INS",ai_derived:"AI",user:"User",propmix:"PMX",order_context:"ORDER"},zv={mls:"MLS listing",public_records:"Public records",inspection:"Field inspection",ai_derived:"AI / Property Lab",user:"User",propmix:"PropMix property data",document:"Order document",order_context:"Order"};function r7(t,a){if(t==="manual")return"User confirmed";if(typeof a=="number"){const s=Math.round(a*100);if(t==="high")return`High confidence (${s}%)`;if(t==="medium")return`Medium confidence (${s}%)`;if(t==="low")return`Low confidence (${s}%)`}return t==="high"?"High confidence":t==="medium"?"Medium confidence":t==="low"?"Low confidence":t}function Ji({source:t,userEdited:a,testId:s}){const n={MLS:"mls",PublicRecord:"public_records",AI:"ai_derived",User:"user",Inspection:"inspection",PropMix:"propmix"}[t]??t,i={mls:"bg-sky-500",public_records:"bg-amber-500",inspection:"bg-violet-500",ai_derived:"bg-emerald-500",user:"bg-violet-500",propmix:"bg-blue-500",order_context:"bg-slate-500",document:"bg-violet-500"},l=a?"User-edited":zv[n]||t;return e.jsx("span",{"aria-label":`Source: ${l}`,className:`inline-block h-1.5 w-1.5 shrink-0 rounded-full ${i[a?"user":n]||"bg-slate-400"}`,"data-testid":s})}function qv({source:t,confidence:a,confidenceScore:s,userEdited:r,compact:n}){const i={high:"bg-green-100 text-green-700 border-green-300",medium:"bg-yellow-100 text-yellow-700 border-yellow-300",low:"bg-red-100 text-red-700 border-red-300",manual:"bg-blue-100 text-blue-700 border-blue-300"},l=n?"text-[10px] px-1 py-0 h-4":"text-xs px-1.5 py-0",c=!r&&t==="document",d=r?"bg-emerald-100 text-emerald-700 border-emerald-300":c?"bg-violet-100 text-violet-700 border-violet-300":i[a]||"",p=r?"EDITED":Ik[t]||t,u=zv[t]||t,m=t!=="user"&&!!zv[t];if(r&&!m)return null;const h=r?`Edited (was: ${u})`:t==="order_context"||t==="user"?u:`${u} • ${r7(a,s)}`,f=`chip-source-${t}${r?"-edited":""}`;return e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs(kt,{variant:"outline",className:`${l} ${d} cursor-help`,"data-testid":f,children:[r&&e.jsx(pc,{className:"h-2.5 w-2.5 mr-0.5 inline"}),c?e.jsx(gn,{className:"h-2.5 w-2.5 inline","aria-label":u}):p]})}),e.jsx(Wa,{side:"top",className:"text-xs max-w-xs",children:h})]})}const xx="border-red-400 bg-red-50/40 ring-1 ring-red-200";function bj(){const t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():`amenity_${Math.random().toString(36).slice(2,12)}`}function bx(t){return t!=null&&(typeof t!="string"||t.trim()!=="")}function n7(t){const a=t.trim().toLowerCase().replace(/[\s-]+/g,"_");return a==="public_record"||a==="publicrecord"||a==="pr"?"public_records":a==="ai"||a==="ai_derived"?"ai_derived":a==="manual"?"user":a}function uP(t,a,s){const r=new Set;return bx(t.amenityType)||r.add("amenityType"),t.amenityType==="Other"&&!bx(t.amenityTypeOtherDescription)&&r.add("amenityTypeOtherDescription"),!a&&VL(t.amenityType)&&!bx(t.materialType)&&r.add("materialType"),t.materialType==="Other"&&!bx(t.materialTypeOtherDescription)&&r.add("materialTypeOtherDescription"),!a&&$L(t.amenityType)&&!bx(t.areaMeasure)&&r.add("areaMeasure"),BL(t.amenityType)&&t.count==null&&r.add("count"),pT(t.amenityType)&&(t.swimmingPoolFeatures??[]).some(n=>n.type==="Other"&&!bx(n.otherDescription))&&r.add("swimmingPoolFeatures"),!a&&s&&zL(t.amenityType)&&t.attachedToManufacturedHome==null&&r.add("attachedToManufacturedHome"),r}function pP(t,a,s){if(!t.trim())return{value:void 0,otherDescription:void 0};const r=a.find(n=>n!=="Other"&&(n.toLowerCase()===t.toLowerCase()||cl(n).toLowerCase()===t.toLowerCase()));return r?{value:r,otherDescription:void 0}:{value:"Other",otherDescription:t.slice(0,s)}}function i7({category:t,items:a,onChange:s,disabled:r,inspectPath:n,inspectSection:i="propertyAmenities",inspectLabel:l,source:c,testId:d,comparable:p=!1,subjectHasManufacturedHome:u=!1}){const{inspecting:m}=fc(),[h,f]=o.useState(!1),[v,S]=o.useState({left:16,top:16,maxHeight:640}),N=o.useRef(null),x=a.filter(R=>R.category===t),y=Array.from(new Map(x.flatMap(R=>{if(Object.values(R.fieldUserEdited??{}).some(F=>F===!0))return[{source:"user",userEdited:!0}];const U=Object.values(R.fieldSources??{}
14).filter(Boolean);return(U.length>0?U:R.source?[R.source]:c?[c]:[]).map(F=>({source:n7(F),userEdited:!1}))}).map(R=>[R.source,R])).values()),b=[...zU[t],...t==="Miscellaneous"?["Other"]:[]],j=()=>{if(x.length>=8)return;const R=b.find(U=>!x.some(C=>C.amenityType===U))??b[0],G={id:bj(),amenityType:R,category:t,source:"user",fieldSources:{amenityType:"user"},fieldUserEdited:{amenityType:!0},...R==="Other"?{amenityTypeOtherDescription:""}:{},...p?{}:{photos:[]}};s([...a,G])},T=(R,G)=>{s(a.map(U=>{if(U.id!==R)return U;const C=Object.keys(G).filter(A=>!["id","source","sourceIdentity","fieldSources","fieldUserEdited","photos","defects"].includes(A));return{...U,...G,fieldSources:{...U.fieldSources??{},...Object.fromEntries(C.filter(A=>!U.fieldSources?.[A]).map(A=>[A,"user"]))},fieldUserEdited:{...U.fieldUserEdited??{},...Object.fromEntries(C.map(A=>[A,!0]))}}}))},O=R=>s(a.filter(G=>G.id!==R)),E=()=>{if(r)return;const R=N.current;if(R){const G=R.getBoundingClientRect(),U=Math.min(704,window.innerWidth-16),C=Math.min(650,window.innerHeight-16),F=8,A=G.right+F+U<=window.innerWidth?G.right+F:Math.max(8,G.left-U-F),M=Math.max(8,Math.min(G.top,window.innerHeight-C-8));S({left:A,top:M,maxHeight:Math.max(0,window.innerHeight-M-8)})}f(!0)};return e.jsxs(xi,{open:h,onOpenChange:R=>f(r?!1:R),children:[e.jsxs("div",{ref:N,role:"button",tabIndex:0,className:"relative flex min-h-[18px] w-full cursor-pointer flex-wrap items-center justify-center gap-x-1 rounded px-1 py-0 text-center text-[11px] leading-4 text-slate-700 transition-colors hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-inset","data-testid":d,"aria-label":`Edit ${l} ${rg[t]}`,onClick:R=>{R.target.closest('[data-testid^="datapoint-inspect-pill-"]')||E()},onKeyDown:R=>{R.key!=="Enter"&&R.key!==" "||(R.preventDefault(),E())},children:[y.length>0&&e.jsx("span",{className:"absolute left-0 top-1 flex items-center gap-1","data-testid":`${d}-summary-source-indicators`,children:y.map(({source:R,userEdited:G})=>e.jsx(Ji,{source:R,userEdited:G,testId:`${d}-summary-source-${R}`},R))}),x.length===0?e.jsxs(e.Fragment,{children:[e.jsx("span",{"data-testid":`${d}-empty`,children:"—"}),m&&e.jsx(Fs,{section:i,fieldName:n,displayLabel:`${l} · ${rg[t]}`})]}):x.map((R,G)=>{const U=`${n}.${tb(R.id)}`,C=wE(R),F=uP(R,p,u).size>0,A=x.slice(0,G).some(M=>wE(M)!=="");return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[A&&C&&e.jsx("span",{"aria-hidden":"true",className:"mx-1",children:"|"}),C,F&&e.jsx("span",{"aria-label":`Required ${cl(R.amenityType)} data is missing`,className:"inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-red-500","data-testid":`${d}-${R.id}-incomplete`,title:`Required ${cl(R.amenityType)} data is missing`}),m&&e.jsx(Fs,{section:i,fieldName:U,displayLabel:`${l} · ${cl(R.amenityType)}`})]},R.id)})]}),e.jsxs(bi,{className:"flex max-w-none translate-x-0 translate-y-0 flex-col gap-0 overflow-hidden border-slate-200 bg-white p-0 shadow-xl",onOpenAutoFocus:R=>R.preventDefault(),style:{left:v.left,top:v.top,maxHeight:v.maxHeight,width:"min(46rem, calc(100vw - 1rem))"},overlayClassName:"bg-black/50","data-testid":`${d}-editor`,children:[e.jsxs($i,{className:"shrink-0 border-b border-slate-200 px-3 py-3",children:[e.jsxs(si,{className:"text-sm font-semibold text-slate-800",children:[l," · ",rg[t]]}),e.jsx(pl,{className:"text-[11px] text-slate-500",children:"Add or edit the amenities for this category."})]}),e.jsxs("div",{className:"overflow-y-auto",children:[x.length===0?e.jsx("div",{className:"px-3 py-3 text-xs text-slate-500",children:"No amenities in this category."}):x.map((R,G)=>{const U=`${n}.${tb(R.id)}`,C=p?null:R,F=uP(R,p,u),A=F.has("amenityType"),M=F.has("amenityTypeOtherDescription"),B=F.has("materialType"),oe=F.has("materialTypeOtherDescription"),ae=F.has("areaMeasure"),D=F.has("count"),_=F.has("swimmingPoolFeatures"),$=R.amenityType==="Other"?R.amenityTypeOtherDescription??"":cl(R.amenityType),z=R.materialType==="Other"?R.materialTypeOtherDescription??"":R.materialType?cl(R.materialType):"",V=(R.swimmingPoolFeatures??[]).map(W=>W.type==="Other"?W.otherDescription??"":W.type),le=(W,me)=>{const Z=R.fieldSources?.[W]??me;return Z?e.jsx(Ji,{source:Z,userEdited:R.fieldUserEdited?.[W]===!0,testId:`${d}-${R.id}-${W}-source`}):null};return e.jsxs("div",{className:"flex flex-nowrap items-start gap-2 overflow-x-auto border-b border-slate-200 bg-slate-50/60 px-3 py-2","data-testid":`${d}-${R.id}-editor-row`,children:[e.jsx("span",{className:"w-3 shrink-0 self-center text-center text-[11px] text-slate-500","data-testid":`${d}-${R.id}-sequence`,"aria-label":`Amenity item ${G+1}`,children:G+1}),e.jsxs("div",{className:"contents",children:[m&&e.jsx(Fs,{section:i,fieldName:U,displayLabel:`${l} · ${cl(R.amenityType)}`}),e.jsxs("div",{className:"w-40 shrink-0 space-y-0.5",children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Amenity type",e.jsx(Gp,{}),le("amenityType",R.source??c)]}),t==="Miscellaneous"?e.jsx(Kd,{value:$,suggestions:b.filter(W=>W!=="Other").map(W=>cl(W)),placeholder:"Select or type…",maxLength:45,compact:!0,disabled:r,testId:`${d}-${R.id}-amenity-type`,ariaLabel:"Amenity type",ariaInvalid:A||M,inputClassName:`canonical-grid-placeholder placeholder-hint h-8 bg-white px-2 text-[11px] md:text-[11px] ${A||M?xx:"border-slate-200"}`,onChange:W=>{const me=pP(W,b,45);T(R.id,{amenityType:me.value,amenityTypeOtherDescription:me.otherDescription,category:t,swimmingPoolFeatures:void 0})}}):e.jsxs(sr,{disabled:r,value:R.amenityType,onValueChange:W=>T(R.id,{amenityType:W,amenityTypeOtherDescription:void 0,category:t,...pT(W)?{}:{swimmingPoolFeatures:void 0}}),children:[e.jsx(rr,{className:`canonical-grid-placeholder placeholder-hint h-8 w-full rounded-md bg-white px-2 text-[11px] ${A?xx:"border-slate-200"}`,"aria-invalid":A||void 0,"aria-label":`${cl(R.amenityType)} amenity type`,children:e.jsx(or,{placeholder:"Select…"})}),e.jsx(nr,{children:b.map(W=>e.jsx(vs,{value:W,children:cl(W)}
14,W))})]})]}),e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"order-last mt-[15px] h-8 w-8 shrink-0 rounded-sm text-slate-400 hover:bg-rose-50 hover:text-rose-600",disabled:r,onClick:()=>O(R.id),"aria-label":`Remove ${cl(R.amenityType)}`,children:e.jsx(Ci,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"contents",children:[p?null:e.jsxs("div",{className:"w-28 shrink-0 space-y-0.5",children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Material",VL(R.amenityType)?e.jsx(Gp,{}):null,le("materialType")]}),e.jsx(Kd,{value:z,suggestions:PE.filter(W=>W!=="Other").map(W=>cl(W)),placeholder:"Select or type…",maxLength:45,compact:!0,disabled:r,testId:`${d}-${R.id}-material`,ariaLabel:`${cl(R.amenityType)} material`,ariaInvalid:B||oe,inputClassName:`canonical-grid-placeholder placeholder-hint h-8 bg-white px-2 text-[11px] md:text-[11px] ${B||oe?xx:"border-slate-200"}`,onChange:W=>{const me=pP(W,PE,45);T(R.id,{materialType:me.value,materialTypeOtherDescription:me.otherDescription})}})]}),p?null:e.jsxs("div",{className:"w-[5.5rem] shrink-0 space-y-0.5",children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Area",$L(R.amenityType)?e.jsx(Gp,{}):null,le("areaMeasure")]}),e.jsx(ze,{type:"number",className:`canonical-grid-number-input canonical-grid-placeholder placeholder-hint h-8 w-full rounded-md bg-white px-2 text-[11px] md:text-[11px] ${ae?xx:"border-slate-200"}`,value:R.areaMeasure==null?"":String(R.areaMeasure),placeholder:"Area",disabled:r,onChange:W=>T(R.id,{areaMeasure:W.target.value===""?void 0:W.target.value}),"aria-label":`${cl(R.amenityType)} area`,"aria-invalid":ae||void 0})]}),!p||qU(R)?e.jsxs("div",{className:"w-[4.5rem] shrink-0 space-y-0.5",children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Count",BL(R.amenityType)?e.jsx(Gp,{}):null,le("count")]}),e.jsx(ze,{type:"number",className:`canonical-grid-number-input canonical-grid-placeholder placeholder-hint h-8 w-full rounded-md bg-white px-2 text-[11px] md:text-[11px] ${D?xx:"border-slate-200"}`,value:R.count==null?"":String(R.count),placeholder:"Count",disabled:r,onChange:W=>T(R.id,{count:W.target.value===""?null:Number(W.target.value)}),"aria-label":`${cl(R.amenityType)} count`,"aria-invalid":D||void 0})]}):null,pT(R.amenityType)?e.jsxs("div",{className:"w-44 shrink-0 space-y-0.5",children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Pool Features",le("swimmingPoolFeatures")]}),e.jsx(qx,{label:"Pool Features",hideLabel:!0,values:V,options:OE.filter(W=>W!=="Other").map(W=>({value:W,label:W})),maxLength:45,maxEntries:8,compact:!0,disabled:r,testId:`${d}-${R.id}-pool-features`,ariaLabel:"Select pool features",controlClassName:`min-h-8 bg-white text-[11px] ${_?xx:"border-slate-200"}`,onChange:W=>{const me=R.swimmingPoolFeatures??[],Z=W.map(pe=>{const se=OE.find(fe=>fe!=="Other"&&fe.toLowerCase()===pe.toLowerCase());return se?me.find(fe=>fe.type===se)??{id:bj(),type:se}:me.find(fe=>fe.type==="Other"&&fe.otherDescription===pe)??{id:bj(),type:"Other",otherDescription:pe}});T(R.id,{swimmingPoolFeatures:Z})}})]}):null]}),C&&e.jsx("div",{className:"flex shrink-0 items-center gap-3",children:u&&zL(C.amenityType)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-medium text-slate-600",children:"Attached to manufactured home *"}),e.jsx(cy,{required:!0,value:C.attachedToManufacturedHome,onChange:W=>T(C.id,{attachedToManufacturedHome:W}),testId:`${d}-${C.id}-mh-attachment`})]})})]},R.id)}),e.jsxs(De,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-1 text-[10px]",disabled:r||x.length>=8,onClick:j,children:[e.jsx(un,{className:"mr-1 h-3 w-3"})," Add ",rg[t]]})]})]})]})}const zd=t=>t==null?"":String(t);function $T(t){return t.split("|").map(a=>a.trim()).filter(Boolean)}const BT=E_.map(t=>({value:t,label:t==="HomeownersAssociation"?"HOA":t.replace(/([a-z])([A-Z])/g,"$1 $2")})),o7=IL.map(t=>t==="DeedTransferOnly"?"Deed Transfer Only":t.replace(/([a-z])([A-Z])/g,"$1 $2"));function l7(t){return t==="Deed Transfer Only"?"DeedTransferOnly":IL.find(s=>s.replace(/([a-z])([A-Z])/g,"$1 $2")===t)??t}function Ck(t){return t?t==="DeedTransferOnly"?"Deed Transfer Only":t.replace(/([a-z])([A-Z])/g,"$1 $2"):""}function c7(t,a,s){return["OwnershipTransferDate","OwnershipTransferTransactionType","SaleType","OwnershipTransferTransactionAmount","OwnershipTransferAmountNotAvailableReasonType","DataSourceType"].some(n=>zd(s(Ag(t,a,n))).trim()!=="")}function Rk(t,a){const s=[];for(let r=0;r<=Vm;r++)if(c7(t,r,a)){const n=zd(a(Ag(t,r,"OwnershipTransferDate")));s.push({index:r,date:n})}return s.sort((r,n)=>!r.date&&!n.date?r.index-n.index:r.date?n.date?n.date.localeCompare(r.date):-1:1),s.map(r=>r.index)}function d7(t){if(!t)return"";const a=t.match(/^(\d{4})-(\d{2})/);if(!a)return t;const s=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=parseInt(a[2],10)-1;return`${s[r]??""} ${a[1]}`}function Ek(t){if(!t)return"";const a=t.indexOf("."),s=a>
14=0?t.slice(0,a):t,r=a>=0?t.slice(a+1,a+3):void 0,n=parseInt(s.replace(/\D/g,""),10);if(!Number.isFinite(n))return t;const i=`$${n.toLocaleString()}`;return r!==void 0?`${i}.${r}`:i}function u7(t,a,s){const r=S=>zd(s(Ag(t,a,S))),n=r("OwnershipTransferTransactionType");if(!n)return"";const i={OwnershipTransferTransactionType:n,SaleType:r("SaleType"),SaleTypeOtherDescription:r("SaleTypeOtherDescription")},l=jL(i),c=l?Ck(l):n==="DeedTransferOnly"?"Deed Transfer Only":n,d=r("OwnershipTransferTransactionAmount"),p=r("OwnershipTransferAmountNotAvailableReasonType"),u=r("OwnershipTransferAmountNotAvailableReasonTypeOtherDescription")||zd(s(`Comp${t}SaleHistory${a}_OwnershipTransferAmountNotAvailableReasonOtherDescription`)),m=r("OwnershipTransferDate"),h=d?Ek(d):p==="NotDisclosed"?"Not Disclosed":p==="NotRecorded"?"Not Recorded":p==="Other"?u||"Other":"",f=d7(m),v=[c];return h&&v.push(h),f&&v.push(f),v.join(" · ")}const p7=["Not Disclosed","Not Recorded"],hS="h-8 rounded-md border-slate-200 bg-white px-2 text-[11px] md:text-[11px]";function m7(t,a){return t==="NotDisclosed"?"Not Disclosed":t==="NotRecorded"?"Not Recorded":t==="Other"?a:t}function h7(t){const a=t.trim();return a?a==="Not Disclosed"?{reason:"NotDisclosed",other:""}:a==="Not Recorded"?{reason:"NotRecorded",other:""}:{reason:"Other",other:t.slice(0,TL)}:{reason:"",other:""}}function f7(){return e.jsx("span",{className:"text-rose-500 ml-0.5 text-[9px] align-super","aria-label":"required",children:"*"})}function Jf({when:t}){return t?e.jsx("span",{className:"text-amber-500 ml-0.5 text-[9px] align-super","aria-label":"conditionally required",children:"*"}):null}function g7({compNumber:t,index:a,isMostRecent:s,getValue:r,getSource:n,setValue:i,setMirrorValue:l,readOnly:c,onRemove:d,sequenceNumber:p}){const[u,m]=o.useState(!1),{inspecting:h}=fc(),f=U=>Ag(t,a,U),v=(U,C)=>i(f(U),C),S=U=>zd(r(f(U))),N=U=>n?.(f(U)),x=S("OwnershipTransferTransactionType"),y=x==="Sale",b=S("OwnershipTransferTransactionAmount"),j=S("OwnershipTransferAmountNotAvailableReasonType"),T=S("OwnershipTransferAmountNotAvailableReasonTypeOtherDescription")||zd(r(`Comp${t}SaleHistory${a}_OwnershipTransferAmountNotAvailableReasonOtherDescription`)),O={OwnershipTransferTransactionType:x,SaleType:S("SaleType"),SaleTypeOtherDescription:S("SaleTypeOtherDescription")},E=Ck(jL(O)),R=(U,C)=>{a===0&&(l??i)(`Comp${t}${U}`,C)},G=u?b:b?Ek(b):"";return e.jsxs("div",{className:"flex min-w-0 items-start gap-2","data-testid":`sale-history-comp${t}-entry${a}`,children:[e.jsx("span",{className:"w-4 shrink-0 pt-5 text-[10px] font-semibold tabular-nums text-slate-500","data-testid":`sale-history-comp${t}-entry${a}-sequence`,children:p}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-end gap-2","data-testid":`sale-history-comp${t}-entry${a}-row`,children:[d&&!c&&e.jsx("div",{className:"order-first flex h-8 shrink-0 items-center md:order-last",children:e.jsx("button",{type:"button",onClick:d,className:"text-slate-400 hover:text-rose-500","aria-label":"Remove entry","data-testid":`sale-history-comp${t}-entry${a}-remove`,children:e.jsx(ur,{className:"h-3 w-3"})})}),e.jsxs("div",{className:"min-w-[10rem] flex-[1_1_10rem]",children:[e.jsxs("p",{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500 mb-1",children:["Date",h&&e.jsx(Fs,{section:"salesGrid",fieldName:"saleHistory[].OwnershipTransferDate"}),s?e.jsx(Jf,{when:y}):e.jsx(Jf,{when:!0})]}),e.jsx(vN,{value:S("OwnershipTransferDate"),onChange:U=>{v("OwnershipTransferDate",U),R("SaleDate",U)},testId:`sale-history-comp${t}-entry${a}-date`,inputClassName:hS,pickerButtonClassName:"h-8 w-8"})]}),e.jsxs("div",{className:"min-w-[12rem] flex-[1.25_1_12rem]",children:[e.jsxs("p",{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500 mb-1 flex items-center gap-1",children:[N("SaleType")==="AI"&&e.jsx("span",{className:"inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500",title:"AI-inferred value — verify before submitting"}),"Transfer terms",e.jsx(f7,{}),h&&e.jsx(Fs,{section:"salesGrid",fieldName:"saleHistory[].SaleType"})]}),e.jsx(Kd,{value:E,onChange:U=>{const C=l7(U),F=w_(C);v("OwnershipTransferTransactionType",F.OwnershipTransferTransactionType),v("SaleType",F.SaleType),v("SaleTypeOtherDescription",F.SaleTypeOtherDescription),R("SaleType",F.SaleType),F.OwnershipTransferTransactionType!=="Sale"&&(v("SaleType",""),v("SaleTypeOtherDescription",""),R("SaleType",""))},suggestions:o7,placeholder:"Select or type terms…",testId:`sale-history-comp${t}-entry${a}-saletype`,maxLength:33,compact:!0,inputClassName:hS})]}),e.jsxs("div",{className:"min-w-[9rem] flex-[0.8_1_9rem]",children:[e.jsxs("p",{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500 mb-1",children:["Amount",h&&e.jsx(Fs,{section:"salesGrid",fieldName:"saleHistory[].OwnershipTransferTransactionAmount"}),s&&e.jsx(Jf,{when:y})]}),e.jsx(ze,{type:"text",inputMode:"decimal",className:`${hS} placeholder-hint`,placeholder:"Amount ($)",value:G,disabled:c,onFocus:()=>m(!0),onBlur:()=>m(!1),onChange:U=>{const C=U.target.value.replace(/[^\d.]/g,""),F=C.indexOf("."),A=(F>=0?C.slice(0,F):C).slice(0,dE),M=F>=0?C.slice(F+1).replace(/\D/g,"").slice(0,2):void 0,B=M!==void 0?`${A}.${M}`:A;v("OwnershipTransferTransactionAmount",B),B!==""&&(v("OwnershipTransferAmountNotAvailableReasonType",""),v("OwnershipTransferAmountNotAvailableReasonTypeOtherDescription","")),R("SalePrice",B)},maxLength:dE+3,"data-testid":`sale-history-comp${t}-entry${a}-amount`})]}),!b&&e.jsxs("div",{className:"min-w-[12rem] flex-[1.1_1_12rem]",children:[e.jsxs("p",{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500 mb-1",children:["…or amount not available",s?e.jsx(Jf,{when:y&&!b}):e.jsx(Jf,{when:!b})]}),e.jsx(Kd,{value:m7(j,T),onChange:U=>{const{reason:C,other:F}=h7(U);v("OwnershipTransferAmountNotAvailableReasonType",C),v("OwnershipTransferAmountNotAvailableReasonTypeOtherDescription",F),v("OwnershipTransferTransactionAmount",""),R("SalePrice","")},suggestions:p7,placeholder:"Select or type reason…",maxLength:TL,testId:`sale-history-comp${t}-entry${a}-nareason`,compact:!0,inputClassName:hS})]}),e.jsxs("div",{className:"min-w-[12rem] flex-[1.1_1_12rem]",children:[e.jsxs("p",{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500 mb-1",children:["Data Source",h&&e.jsx(Fs,{section:"salesGrid",fieldName:"saleHistory[].DataSourceType"}),e.jsx(Jf,{when:!0})]}),e.jsx(qx,{label:"",values:$T(S("DataSourceType")),options:BT,maxLength:40,maxEntries:10,onChange:U=>
14v("DataSourceType",U.join("|")),testId:`sale-history-comp${t}-entry${a}-datasource`,allowCustom:!0,compact:!0,inputClassName:"text-[11px] md:text-[11px]"})]})]})]})}function x7(t,a,s){return{entries:Rk(t,a).map(n=>{const i={},l={};for(const c of mg){const d=Ag(t,n,c);i[c]=zd(a(d)),l[c]=s?.(d)}return{originIndex:n,values:i,sources:l}}),compDataSource:zd(a(`Comp${t}SaleHistoryDataSource`))}}function b7(t){return mg.some(a=>t.values[a].trim()!=="")}function y7(t){const{compNumber:a,getValue:s,getSource:r,setValue:n,setMirrorValue:i,setValueWithSource:l,readOnly:c}=t,[d,p]=o.useState(!1),[u,m]=o.useState(null),h=Rk(a,s),f=h.length>0,v=`Comp${a}SaleHistoryDataSource`,S=zd(s(v)),N=C=>{if(C===v)return u?.compDataSource??S;const F=C.match(new RegExp(`^Comp${a}SaleHistory(\\d+)_([A-Za-z0-9]+)$`));return!F||!u?s(C):u.entries.find(M=>M.originIndex===Number(F[1]))?.values[F[2]]??""},x=C=>{const F=C.match(new RegExp(`^Comp${a}SaleHistory(\\d+)_([A-Za-z0-9]+)$`));return!F||!u?r?.(C):u.entries.find(M=>M.originIndex===Number(F[1]))?.sources[F[2]]},y=(C,F)=>{if(C===v){m(oe=>oe&&{...oe,compDataSource:zd(F)});return}const A=C.match(new RegExp(`^Comp${a}SaleHistory(\\d+)_([A-Za-z0-9]+)$`));if(!A||!u)return;const M=Number(A[1]),B=A[2];mg.includes(B)&&m(oe=>oe&&{...oe,entries:oe.entries.map(ae=>ae.originIndex===M?{...ae,values:{...ae.values,[B]:zd(F)},sources:{...ae.sources,[B]:"user"}}:ae)})},b=u?.entries??[],j=(()=>{const C=new Set(b.map(F=>F.originIndex));for(let F=0;F<=Vm;F++)if(!C.has(F))return F;return-1})(),T=!c&&j!==-1,O=(C,F)=>{(i??n)(`Comp${a}${C}`,F)},E=()=>{if(!u)return;const C=u.entries.filter(b7).sort((M,B)=>{const oe=M.values.OwnershipTransferDate,ae=B.values.OwnershipTransferDate;return!oe&&!ae?0:oe?ae?ae.localeCompare(oe):-1:1});t.onCanonicalReorder?.(C.map(M=>M.originIndex));const F=(M,B,oe)=>{zd(s(M))===B&&r?.(M)===oe||t.onCanonicalReorder||(l?l(M,B,B?oe??"user":"Delete"):n(M,B))};for(let M=0;M<=Vm;M++){const B=C[M];for(const oe of mg)F(Ag(a,M,oe),B?.values[oe]??"",B?.sources[oe])}zd(s(v))!==u.compDataSource&&n(v,u.compDataSource);const A=C[0];O("SaleDate",A?.values.OwnershipTransferDate??""),O("SaleType",A?.values.SaleType??""),O("SalePrice",A?.values.OwnershipTransferTransactionAmount??""),m(null),p(!1)},R=()=>{m(null),p(!1)},G=C=>{C?(m(x7(a,s,r)),p(!0)):R()},U=e.jsxs("div",{className:"flex items-start justify-between gap-1 min-h-[1.5rem] py-0.5 w-full",children:[e.jsx("div",{className:"text-xs text-slate-700 leading-4 flex-1 min-w-0",children:f?(()=>{const C=h.map(A=>({idx:A,summary:u7(a,A,s)})).filter(({summary:A})=>!!A),F=C.length>1;return C.map(({idx:A,summary:M},B)=>e.jsxs("div",{className:`text-[11px] flex gap-1 ${B>0?"mt-1 pt-1 border-t border-slate-100":""}`,children:[F&&e.jsxs("span",{className:"shrink-0 text-slate-400 select-none tabular-nums",children:[B+1,"."]}),e.jsx("span",{children:M})]},A))})():e.jsxs("span",{className:"text-[11px]",children:[e.jsx("span",{className:"text-slate-400 italic",children:"None"}),S?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-400 italic",children:" · "}),e.jsx("span",{className:"text-slate-500",children:$T(S).map(C=>BT.find(F=>F.value===C)?.label??C).join(", ")})]}):null]})}),!c&&e.jsx("span",{className:"shrink-0 mt-0.5 text-slate-400 hover:text-slate-700 transition-colors","aria-label":"Edit sale history",title:"Edit sale history","data-testid":`sale-history-comp${a}-edit`,children:e.jsx(Ru,{className:"w-3 h-3"})})]});return c?e.jsx("div",{"data-testid":`sale-history-comp${a}`,children:U}):e.jsxs(xn,{open:d,onOpenChange:G,children:[e.jsx(bn,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer","data-testid":`sale-history-comp${a}`,children:U})}),d&&typeof document<"u"&&Wp.createPortal(e.jsx("div",{className:"fixed inset-0 z-[99] bg-slate-950/35 backdrop-blur-[1px]","data-testid":`sale-history-comp${a}-overlay`,"aria-hidden":"true"}),document.body),e.jsxs(yn,{className:"z-[100] flex max-h-[85vh] max-w-[calc(100vw-1rem)] flex-col gap-0 overflow-hidden rounded-lg border-slate-200 bg-white p-0 shadow-xl",style:{width:"min(62rem, calc(100vw - 1rem))"},side:"top",align:"start","data-testid":`sale-history-comp${a}-popover`,onPointerDownOutside:C=>{C.target.closest("[data-floating-portal]")&&C.preventDefault()},children:[e.jsxs("div",{className:"flex items-center justify-between p-3 pb-2 border-b border-slate-100",children:[e.jsxs("span",{className:"text-[10px] uppercase font-semibold text-slate-500 tracking-wide",children:["Comp ",a," Sale / Transfer History"]}),e.jsx("button",{type:"button",onClick:R,className:"text-slate-400 hover:text-slate-700 transition-colors","aria-label":"Close sale history panel","data-testid":`sale-history-comp${a}-close`,children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain bg-white p-3",children:b.length===0?e.jsxs("div",{children:[e.jsxs("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1",children:["Data Source",e.jsx(Jf,{when:!0})]}),e.jsx(qx,{label:"",values:$T(u?.compDataSource??S),options:BT,maxLength:40,maxEntries:10,onChange:C=>y(v,C.join("|")),testId:`sale-history-comp${a}-comp-datasource`,allowCustom:!0,compact:!0})]}):b.map((C,F)=>{const A=C.originIndex,M=F===0;return e.jsx("div",{className:F>0?"border-t border-slate-100 pt-3":"",children:e.jsx(g7,{...t,getValue:N,getSource:x,setValue:y,setMirrorValue:y,index:A,isMostRecent:M,sequenceNumber:F+1,onRemove:()=>m(B=>{if(!B)return B;const oe=B.entries.find(D=>D.originIndex===A),ae=B.entries.length===1;return{...B,compDataSource:ae&&!B.compDataSource&&oe?.values.DataSourceType?oe.values.DataSourceType:B.compDataSource,entries:B.entries.filter(D=>D.originIndex!==A)}})})},A)})}),T&&e.jsx("div",{className:"border-t border-slate-100 pt-2 px-3 pb-2",children:e.jsx(De,{type:"button",size:"sm",variant:"outline",className:"w-full h-7 text-xs border-dashed",onClick:()=>
14{if(j===-1)return;const C={},F={};for(const A of mg)C[A]="",F[A]=void 0;C.OwnershipTransferTransactionType="Sale",F.OwnershipTransferTransactionType="user",m(A=>A&&{...A,entries:[...A.entries,{originIndex:j,values:C,sources:F}]})},"data-testid":`sale-history-comp${a}-add`,children:"+ Add Sale"})}),e.jsxs("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-slate-200 bg-slate-50 px-3 py-2",children:[e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-7 px-3 text-xs",onClick:R,"data-testid":`sale-history-comp${a}-cancel`,children:"Cancel"}),e.jsx(De,{type:"button",size:"sm",className:"h-7 px-3 text-xs",onClick:E,"data-testid":`sale-history-comp${a}-save`,children:"Save"})]})]})]})}const kh=9,zh=60,S7="legacy-custom-adjustment",wk=["locationAdj","glaAdj","lotSizeAdj","ageAdj","conditionAdj","qualityAdj","viewAdj","heatingCoolingAdj","bedsAdj","bathsAdj","garageAdj","porchPatioDeckAdj","basementAdj","marketConditionsAdj","otherAdj"];function XI(t){return wk.reduce((a,s)=>a+(Number(t[s])||0),0)}function LN(t,a){return t.reduce((s,r)=>s+(Number(r.adjustments?.[a])||0),0)}const Pk=t=>/^[a-z0-9][a-z0-9_-]*$/i.test(t);function v7(t){const a=[];Pk(t.id)||a.push("Factor ID must contain only letters, numbers, underscores, or hyphens."),t.label.trim()||a.push("Factor label is required."),t.label.trim().length>zh&&a.push(`Factor label must be ${zh} characters or fewer.`);for(const[s,r]of Object.entries(t.adjustments||{}))s||a.push("Adjustment comp identity is required."),Number.isFinite(r)||a.push(`Adjustment for ${s||"unknown comp"} must be finite.`);return{valid:a.length===0,errors:a}}function N7(t){const a=[];t.length>kh&&a.push(`No more than ${kh} custom comparison factors are allowed.`);const s=new Set,r=new Set;for(const n of t){a.push(...v7(n).errors),s.has(n.id)&&a.push(`Duplicate factor ID: ${n.id}`),s.add(n.id);const i=n.label.trim().toLowerCase();i&&r.has(i)&&a.push(`Duplicate factor label: ${n.label.trim()}`),r.add(i)}return{valid:a.length===0,errors:a}}function A7(t,a=[]){const s=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"custom-factor",r=new Set(a.map(i=>i.id));let n=s;for(let i=2;r.has(n);i+=1)n=`${s}-${i}`;return{id:n,label:t.trim(),subjectValue:null,compValues:{}}}function mP(t,a="Legacy draft"){if(t==null||t==="")return null;if(typeof t=="object"&&"value"in t){const s=t;return{value:s.value??null,source:s.source||a,alternatives:Array.isArray(s.alternatives)?s.alternatives:[],manual:s.manual===!0,editedAt:s.editedAt||""}}return Mv(t,"")}function Ok(t){if(!Array.isArray(t))return[];const a=[],s=new Set;for(const r of t){if(a.length>=kh)break;if(!r||typeof r!="object")continue;const n=r,i=String(n.id||""),l=String(n.label||"").trim().slice(0,zh);if(!Pk(i)||!l||s.has(i))continue;const c={};if(n.compValues&&typeof n.compValues=="object")for(const[p,u]of Object.entries(n.compValues)){const m=mP(u);p&&m&&(c[p]=m)}const d={};if(n.adjustments&&typeof n.adjustments=="object")for(const[p,u]of Object.entries(n.adjustments)){const m=Number(u);p&&Number.isFinite(m)&&(d[p]=m)}a.push({id:i,label:l,subjectValue:mP(n.subjectValue),compValues:c,...Object.keys(d).length?{adjustments:d}:{}}),s.add(i)}return a}function j7(t,a){let s=!1;const r=t.map(n=>{let i=n.compValues,l=n.adjustments;for(const[c,d]of Object.entries(a))!d||c===d||(i[c]&&!i[d]&&(i===n.compValues&&(i={...i}),i[d]=i[c],s=!0),l?.[c]!==void 0&&l[d]===void 0&&(l===n.adjustments&&(l={...l}),l[d]=l[c],s=!0));return i===n.compValues&&l===n.adjustments?n:{...n,compValues:i,...l?{adjustments:l}:{}}});return s?r:t}function T7(t){const a=Ok(t.customComparisonFactors);if(a.length||!String(t.compGridCustomAdjLabel||"").trim())return{...t,customComparisonFactors:a};const s={};for(const n of t.compGridRows||[]){if(!n||typeof n!="object")continue;const i=n,l=String(i.compId||i.address||""),c=Number(i.customAdj);l&&Number.isFinite(c)&&c!==0&&(s[l]=c)}const r={id:S7,label:String(t.compGridCustomAdjLabel).trim().slice(0,zh),subjectValue:null,compValues:{},...Object.keys(s).length?{adjustments:s}:{}};return{...t,customComparisonFactors:[r]}}function hP(t){return t?.value===null||t?.value===void 0?"":String(t.value)}function fP(t){return Mv(t,new Date().toISOString())}function I7({factors:t,compIds:a,gridTemplateColumns:s,showMasterRateColumn:r,showAdjustments:n,onChange:i}
14){const[l,c]=o.useState(""),[d,p]=o.useState({}),[u,m]=o.useState(""),h=(x,y)=>{const b=x.trim();return b?b.length>zh?`Use ${zh} characters or fewer.`:t.some(T=>T.id!==y&&T.label.trim().toLowerCase()===b.toLowerCase())?"Factor names must be unique.":"":"Enter a factor name."},f=()=>{if(t.length>=kh){m(`You can add up to ${kh} custom factors.`);return}const x=h(l);if(x){m(x);return}i([...t,A7(l,t)]),c(""),m("")},v=(x,y)=>{i(t.map(b=>b.id===x?y(b):b))},S=x=>{const y=d[x.id];if(y===void 0)return;const b=h(y,x.id);if(b){m(b),p(j=>{const T={...j};return delete T[x.id],T});return}v(x.id,j=>({...j,label:y.trim()})),p(j=>{const T={...j};return delete T[x.id],T}),m("")},N=(x,y)=>{const b=x+y;if(b<0||b>=t.length)return;const j=[...t];[j[x],j[b]]=[j[b],j[x]],i(j)};return e.jsxs("div",{"data-testid":"eval-custom-comparison-factors",children:[e.jsx("div",{className:"border-y border-slate-300 bg-slate-700 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-white",children:"Custom comparison factors"}),t.map((x,y)=>e.jsxs("div",{className:"grid border-b border-slate-200 bg-white",style:{gridTemplateColumns:s},"data-testid":`eval-custom-factor-row-${x.id}`,children:[e.jsxs("div",{className:"sticky left-0 z-[2] flex min-w-[170px] items-center gap-1 bg-white px-2 py-1",children:[e.jsx("input",{"aria-label":`Custom factor ${y+1} name`,value:d[x.id]??x.label,maxLength:zh,onChange:b=>p(j=>({...j,[x.id]:b.target.value})),onBlur:()=>S(x),onKeyDown:b=>{b.key==="Enter"&&b.currentTarget.blur(),b.key==="Escape"&&(p(j=>{const T={...j};return delete T[x.id],T}),b.currentTarget.blur())},className:"h-6 min-w-0 flex-1 rounded border border-slate-200 px-1.5 text-[11px] font-medium text-slate-700 focus:border-blue-400 focus:outline-none","data-testid":`input-eval-custom-factor-label-${x.id}`}),e.jsx("button",{type:"button","aria-label":`Move ${x.label} up`,disabled:y===0,onClick:()=>N(y,-1),className:"text-slate-400 hover:text-slate-700 disabled:opacity-25",children:e.jsx(xN,{className:"h-3 w-3"})}),e.jsx("button",{type:"button","aria-label":`Move ${x.label} down`,disabled:y===t.length-1,onClick:()=>N(y,1),className:"text-slate-400 hover:text-slate-700 disabled:opacity-25",children:e.jsx(gN,{className:"h-3 w-3"})}),e.jsx("button",{type:"button","aria-label":`Remove ${x.label}`,onClick:()=>{i(t.filter(b=>b.id!==x.id)),m("")},className:"text-slate-400 hover:text-rose-600","data-testid":`button-remove-eval-custom-factor-${x.id}`,children:e.jsx(Ci,{className:"h-3 w-3"})})]}),r&&e.jsx("div",{className:"border-r border-slate-200 px-2 py-1 text-[10px] text-slate-300",children:"—"}),e.jsx("div",{className:"border-l border-amber-200 bg-amber-50/30 px-2 py-1",children:e.jsx("input",{"aria-label":`${x.label} subject value`,value:hP(x.subjectValue),title:x.subjectValue?.source||"Manual",onChange:b=>v(x.id,j=>({...j,subjectValue:fP(b.target.value)})),className:"h-6 w-full rounded border border-amber-200 bg-white px-1.5 text-[11px] focus:border-blue-400 focus:outline-none","data-testid":`input-eval-custom-factor-subject-${x.id}`})}),a.map((b,j)=>e.jsxs("div",{className:"contents",children:[e.jsx("div",{className:`px-2 py-1 ${j===0?"border-l-2 border-l-slate-300":"border-l border-slate-200"}`,children:e.jsx("input",{"aria-label":`${x.label} comparable ${j+1} value`,value:hP(x.compValues[b]),title:x.compValues[b]?.source||"Manual",onChange:T=>v(x.id,O=>({...O,compValues:{...O.compValues,[b]:fP(T.target.value)}})),className:"h-6 w-full rounded border border-slate-200 px-1.5 text-[11px] focus:border-blue-400 focus:outline-none","data-testid":`input-eval-custom-factor-comp-${x.id}-${b}`})}),n&&e.jsx("div",{className:"w-[60px] min-w-[60px] px-1 py-1",children:e.jsx("input",{type:"number",step:"1","aria-label":`${x.label} comparable ${j+1} adjustment`,value:x.adjustments?.[b]??"",onChange:T=>{const O=T.target.value;v(x.id,E=>{const R={...E.adjustments||{}};if(O==="")delete R[b];else{const G=Number(O);Number.isFinite(G)&&(R[b]=G)}return{...E,...Object.keys(R).length?{adjustments:R}:{adjustments:void 0}}})},className:"h-6 w-full rounded border border-slate-200 px-1 text-right text-[10px] tabular-nums focus:border-blue-400 focus:outline-none","data-testid":`input-eval-custom-factor-adjustment-${x.id}-${b}`})})]},b))]},x.id)),e.jsxs("div",{className:"sticky left-0 flex w-max min-w-[360px] items-center gap-2 bg-white px-3 py-2",children:[e.jsx("input",{value:l,maxLength:zh,placeholder:"e.g. Lake access","aria-label":"New custom comparison factor name",onChange:x=>{c(x.target.value),u&&m("")},onKeyDown:x=>{x.key==="Enter"&&f()},disabled:t.length>=kh,className:"h-8 w-52 rounded-md border border-slate-300 px-2 text-xs focus:border-blue-400 focus:outline-none disabled:bg-slate-100","data-testid":"input-eval-custom-factor-name"}),e.jsxs("button",{type:"button",onClick:f,disabled:t.length>=kh,className:"flex h-8 items-center gap-1.5 rounded-md bg-blue-600 px-3 text-xs font-semibold text-white hover:bg-blue-700 disabled:bg-slate-300","data-testid":"button-add-eval-custom-factor",children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Add factor"]}),e.jsxs("span",{className:"text-[10px] text-slate-400",children:[t.length,"/",kh]}),u&&e.jsx("span",{role:"alert",className:"text-[11px] font-medium text-rose-600","data-testid":"eval-custom-factor-error",children:u})]})]})}const fS="__ten_or_more__";function C7(t,a,s){return`${t}.${a}.${s}`}function gP(t){const a=t.trim().toLowerCase().replace(/[\s-]+/g,"_");return a==="public_record"||a==="publicrecord"||a==="pr"?"public_records":a==="ai"||a==="ai_derived"?"ai_derived":a==="manual"?"user":a}function Oc(t){return t!=null&&(typeof t!="string"||t.trim()!=="")}function Px(t,a){return t.length===0?!0:t.every(s=>{const r=(s.CarStorageType??"").trim();if(!r||r==="Other"&&!Oc(s.CarStorageTypeOtherDescription))return!1;const n={type:r,surface:s.ImprovedSurfaceMaterialType,tenOrMore:s.TenOrMoreParkingSpacesIndicator??null};return!(eg("ParkingSpacesCount",n)&&s.TenOrMoreParkingSpacesIndicator!==!0&&!Oc(s.ParkingSpacesCount)||eg("C
14arStorageAttachmentType",n)&&!Oc(s.CarStorageAttachmentType)||!a&&eg("CarStorageAreaMeasure",n)&&!Oc(s.CarStorageAreaMeasure)||eg("ImprovedSurfaceMaterialType",n)&&!Oc(s.ImprovedSurfaceMaterialType)||s.ImprovedSurfaceMaterialType==="Other"&&!Oc(s.ImprovedSurfaceMaterialTypeOtherDescription)||eg("ProjectParkingSpaceAssignmentType",n)&&!Oc(s.ProjectParkingSpaceAssignmentType))})}function xP({items:t,onChange:a,source:s,userEdited:r,isLoading:n=!1,disabled:i,emptyLabel:l="None",inspectSection:c,inspectPrefix:d,inspectEntityLabel:p,testIdPrefix:u}){const{inspecting:m}=fc(),[h,f]=o.useState(!1),[v,S]=o.useState({left:16,top:16,maxHeight:640}),N=o.useRef(null),x=o.useRef(null),y=o.useRef(!1);o.useEffect(()=>{if(!y.current)return;y.current=!1;const D=x.current;D&&D.scrollTo({top:D.scrollHeight,behavior:"smooth"})},[t.length]);const b=p??(d.startsWith("ordered")?"Comp":"Subject"),j=d.startsWith("orderedComparables."),T=Px(t,j),O=t.flatMap(D=>Object.entries(D.fieldSources??{}).flatMap(([_,$])=>$?[{source:gP($),userEdited:D.fieldUserEdited?.[_]===!0}]:[])),E=r===!0||t.some(D=>Object.values(D.fieldUserEdited??{}).some(_=>_===!0)),R=O.length>0?O:t.length>0&&s?[{source:gP(s),userEdited:!1}]:[],G=Array.from(new Map((E?[{source:"user",userEdited:!0}]:R.map(D=>({source:D.source,userEdited:!1}))).map(D=>[D.source,D])).values()),U=(D,_)=>a(t.map($=>{if($.id!==D)return $;const z=Object.keys(_).filter(V=>!["id","photos","fieldSources","fieldUserEdited"].includes(V));return{...$,..._,fieldUserEdited:{...$.fieldUserEdited??{},...Object.fromEntries(z.map(V=>[V,!0]))}}})),C=D=>a(t.filter(_=>_.id!==D)),F=()=>{t.length<uE&&(y.current=!0,a([...t,L_()]))},A=()=>{if(i)return;const D=N.current;if(D){const _=D.getBoundingClientRect(),$=Math.min(704,window.innerWidth-16),z=Math.min(650,window.innerHeight-16),V=8,le=_.right+V+$<=window.innerWidth?_.right+V:Math.max(8,_.left-$-V),W=Math.max(8,Math.min(_.top,window.innerHeight-z-8));S({left:le,top:W,maxHeight:Math.max(0,window.innerHeight-W-8)})}f(!0)},M=(D,_,$)=>m?e.jsx(Fs,{section:c,fieldName:C7(d,D,_),displayLabel:$}):null,B=(D,_,$,z,V=!1)=>e.jsxs("div",{className:"min-w-[8rem] shrink-0 space-y-0.5",children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:[z,V&&e.jsx(Gp,{}),D.fieldSources?.[String(_)]&&e.jsx(Ji,{source:D.fieldSources[String(_)],userEdited:D.fieldUserEdited?.[String(_)]===!0,testId:`source-dot-${u}-${D.id}-${String(_)}`}),M(D.id,String(_),`${b} · ${z}`)]}),e.jsxs(sr,{value:String(D[_]??"")||void 0,disabled:i,onValueChange:le=>U(D.id,{[_]:le,..._==="CarStorageType"&&le!=="Other"?{CarStorageTypeOtherDescription:""}:{},..._==="ImprovedSurfaceMaterialType"&&le!=="Other"?{ImprovedSurfaceMaterialTypeOtherDescription:""}:{}}),children:[e.jsx(rr,{className:`h-8 rounded-md bg-white px-2 text-[11px] ${V&&!Oc(D[_])?"border-red-400 bg-red-50/40 ring-1 ring-red-200":"border-slate-200"}`,"aria-invalid":V&&!Oc(D[_]),"aria-label":`${b} ${z}`,"data-testid":`${u}-${D.id}-${String(_)}`,children:e.jsx(or,{placeholder:"Select…"})}),e.jsx(nr,{children:$.map(le=>e.jsx(vs,{value:le,children:Hs(String(_),le)},le))})]})]}),oe=(D,_,$,z,V,le,W=!1)=>{const me=String(D[_]??""),Z=String(D[$]??""),pe=z.filter(fe=>fe!=="Other").map(fe=>Hs(_,fe)),se=me==="Other"?Z:me?Hs(_,me):"";return e.jsxs("div",{className:`min-w-[12rem] shrink-0 space-y-0.5 [&>div>div>input]:h-8 [&>div>div>input]:rounded-md [&>div>div>input]:px-2 [&>div>div>input]:text-[11px] ${W&&!se.trim()?"[&>div>div>input]:border-red-500 [&>div>div>input]:ring-1 [&>div>div>input]:ring-red-200":""}`,children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:[V,W&&e.jsx(Gp,{}),D.fieldSources?.[_]&&e.jsx(Ji,{source:D.fieldSources[_],userEdited:D.fieldUserEdited?.[_]===!0,testId:`source-dot-${u}-${D.id}-${_}`}),M(D.id,_,`${b} · ${V}`)]}),e.jsx(Kd,{value:se,suggestions:pe,compact:!0,required:W,maxLength:le,testId:`${u}-${D.id}-${_}`,ariaLabel:`${b} ${V}`,onChange:fe=>{const ue=fe.slice(0,le),be=ue.trim(),H=z.find(ye=>ye!=="Other"&&(ye.toLowerCase()===be.toLowerCase()||Hs(_,ye).toLowerCase()===be.toLowerCase()));U(D.id,{[_]:be?H??"Other":"",[$]:!be||H?"":ue})}})]})},ae=e.jsxs("div",{ref:x,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain bg-white","data-testid":`${u}-vehicle-storage-editor-items`,children:[t.map((D,_)=>{const $=(D.CarStorageType||"").trim(),z=$==="Driveway"||$==="SharedDriveway",V=le=>eg(le,{type:$,surface:D.ImprovedSurfaceMaterialType,tenOrMore:D.TenOrMoreParkingSpacesIndicator??null});return e.jsx("div",{className:"border-b border-slate-200 px-3 py-2",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-4 shrink-0 pt-5 text-[10px] font-semibold tabular-nums text-slate-500","aria-label":`Vehicle storage ${_+1}`,"data-testid":`${u}-${D.id}-sequence`,children:_+1}),e.jsxs("div",{className:"grid min-w-0 flex-1 grid-cols-1 gap-1.5 md:flex md:flex-nowrap md:items-end md:gap-2","data-testid":`${u}-${D.id}-editor-fields`,children:[oe(D,"CarStorageType","CarStorageTypeOtherDescription",k_,"Vehicle storage type",D_,!0),(z||V("ParkingSpacesCount"))&&(z?e.jsxs("div",{className:"w-28 shrink-0 space-y-0.5",children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Number of space
14s",e.jsx(Gp,{}),D.fieldSources?.ParkingSpacesCount&&e.jsx(Ji,{source:D.fieldSources.ParkingSpacesCount,userEdited:D.fieldUserEdited?.ParkingSpacesCount===!0,testId:`source-dot-${u}-${D.id}-ParkingSpacesCount`}),D.fieldSources?.TenOrMoreParkingSpacesIndicator&&e.jsx(Ji,{source:D.fieldSources.TenOrMoreParkingSpacesIndicator,userEdited:D.fieldUserEdited?.TenOrMoreParkingSpacesIndicator===!0,testId:`source-dot-${u}-${D.id}-TenOrMoreParkingSpacesIndicator`}),M(D.id,"ParkingSpacesCount",`${b} · Number of spaces`),M(D.id,"TenOrMoreParkingSpacesIndicator",`${b} · 10+ spaces`)]}),e.jsxs(sr,{value:D.TenOrMoreParkingSpacesIndicator===!0?fS:typeof D.ParkingSpacesCount=="number"?String(D.ParkingSpacesCount):void 0,disabled:i,onValueChange:le=>U(D.id,{ParkingSpacesCount:le===fS?null:Number(le),TenOrMoreParkingSpacesIndicator:le===fS}),children:[e.jsx(rr,{className:`h-8 rounded-md bg-white px-2 text-[11px] ${!Oc(D.ParkingSpacesCount)&&D.TenOrMoreParkingSpacesIndicator!==!0?"border-red-400 bg-red-50/40 ring-1 ring-red-200":"border-slate-200"}`,"aria-invalid":!Oc(D.ParkingSpacesCount)&&D.TenOrMoreParkingSpacesIndicator!==!0,"aria-label":`${b} Number of spaces`,"data-testid":`${u}-${D.id}-ParkingSpacesCount`,children:e.jsx(or,{placeholder:"Select…"})}),e.jsxs(nr,{children:[Array.from({length:9},(le,W)=>e.jsx(vs,{value:String(W+1),children:W+1},W+1)),e.jsx(vs,{value:fS,children:"10 or more"})]})]})]}):e.jsxs("div",{className:"w-28 shrink-0 space-y-0.5",children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Number of spaces",e.jsx(Gp,{}),D.fieldSources?.ParkingSpacesCount&&e.jsx(Ji,{source:D.fieldSources.ParkingSpacesCount,userEdited:D.fieldUserEdited?.ParkingSpacesCount===!0,testId:`source-dot-${u}-${D.id}-ParkingSpacesCount`}),M(D.id,"ParkingSpacesCount",`${b} · Number of spaces`)]}),e.jsx(ze,{type:"number",min:1,max:99,value:D.ParkingSpacesCount??"",disabled:i,onChange:le=>U(D.id,{ParkingSpacesCount:le.target.value===""?null:Number(le.target.value),TenOrMoreParkingSpacesIndicator:null}),className:`h-8 rounded-md bg-white px-2 text-[11px] md:text-[11px] ${Oc(D.ParkingSpacesCount)?"border-slate-200":"border-red-400 bg-red-50/40 ring-1 ring-red-200"}`,"aria-invalid":!Oc(D.ParkingSpacesCount),"aria-label":`${b} Number of spaces`,"data-testid":`${u}-${D.id}-ParkingSpacesCount`})]})),V("CarStorageAttachmentType")&&B(D,"CarStorageAttachmentType",M_,"Attachment",!0),V("CarStorageAreaMeasure")&&e.jsxs("div",{className:"w-24 shrink-0 space-y-0.5",children:[e.jsxs(Ja,{className:"text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Area (sf)",!j&&e.jsx(Gp,{}),D.fieldSources?.CarStorageAreaMeasure&&e.jsx(Ji,{source:D.fieldSources.CarStorageAreaMeasure,userEdited:D.fieldUserEdited?.CarStorageAreaMeasure===!0,testId:`source-dot-${u}-${D.id}-CarStorageAreaMeasure`}),M(D.id,"CarStorageAreaMeasure",`${b} · Area`)]}),e.jsx(ze,{type:"number",min:0,value:D.CarStorageAreaMeasure??"",disabled:i,onChange:le=>U(D.id,{CarStorageAreaMeasure:le.target.value===""?null:Number(le.target.value)}),className:`h-8 rounded-md bg-white px-2 text-[11px] md:text-[11px] ${!j&&!Oc(D.CarStorageAreaMeasure)?"border-red-400 bg-red-50/40 ring-1 ring-red-200":"border-slate-200"}`,"aria-invalid":!j&&!Oc(D.CarStorageAreaMeasure),"aria-label":`${b} Area (sf)`,"data-testid":`${u}-${D.id}-CarStorageAreaMeasure`})]}),V("ImprovedSurfaceMaterialType")&&oe(D,"ImprovedSurfaceMaterialType","ImprovedSurfaceMaterialTypeOtherDescription",__,"Surface",F_,!0),V("ProjectParkingSpaceAssignmentType")&&B(D,"ProjectParkingSpaceAssignmentType",U_,"Assignment",!0)]}),e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"mt-4 h-6 w-6 shrink-0 rounded-sm p-0 text-slate-400 hover:bg-rose-50 hover:text-rose-600",onClick:()=>C(D.id),disabled:i,"aria-label":"Delete vehicle storage","data-testid":`${u}-${D.id}-remove`,children:e.jsx(Ci,{className:"h-3 w-3"})})]})},D.id)}),e.jsx("div",{className:"px-3 py-2",children:e.jsxs(De,{type:"button",variant:"outline",size:"sm",onClick:F,disabled:i||t.length>=uE,className:"h-8 w-full justify-center rounded-md border-dashed border-slate-400 bg-white text-[11px] font-medium text-slate-700 hover:bg-slate-50",children:[e.jsx(un,{className:"mr-2 h-3.5 w-3.5"})," Add vehicle storage"]})})]});return e.jsxs(xi,{open:h,onOpenChange:D=>f(i?!1:D),children:[e.jsx("div",{ref:N,role:i?void 0:"button",tabIndex:i?void 0:0,"aria-label":i?void 0:`Edit ${b} Vehicle Storage`,className:`group relative min-h-[18px] rounded px-1 py-0 text-left text-[11px] leading-4 text-slate-700 ${i?"cursor-default":"cursor-pointer transition-colors hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-inset"}`,onClick:D=>{D.target.closest('[data-testid^="datapoint-inspect-pill-"]')||A()},onKeyDown:D=>{D.key!=="Enter"&&D.key!==" "||(D.preventDefault(),A())},"data-testid":`${u}-vehicle-storage`,children:e.jsxs("div",{className:"relative flex items-center justify-start",children:[G.length>0&&e.jsx("div",{className:"absolute left-0 top-1 flex shrink-0 items-center gap-1","data-testid":`${u}-vehicle-storage-source-indicators`,children:G.map(({source:D,userEdited:_})=>e.jsx(Ji,{source:D,userEdited:_,testId:`source-dot-${u}-summary-${D}${_?"-edited":""}`},`${D}:${_?"edited":"source"}`))}),e.jsx("div",{className:`w-full min-w-0 space-y-1 ${G.length>0?"pl-8":""}`,"data-testid":`${u}-vehicle-storage-summary`,children:n&&t.length===0?e.jsx("span",{className:"text-slate-500",children:"Loading…"}):t.length===0?e.jsxs("span",{className:"inline-flex items-center text-slate-700",children:[l,!T&&e.jsx("span",{"aria-label":"Required Vehicle Storage data is missing",className:"ml-1 inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-red-500","data-testid":`${u}-vehicle-storage-incomplete`,title:"Required Vehicle Storage data is missing"}),m&&e.jsx(Fs,{section:c,fieldName:d,displayLabel:`${b} · Vehicle Storage`})]}):t.map((D,_)=>{const $=(D.CarStorageType||"").trim(),z=$==="Driveway"||$==="SharedDriveway",V=ue=>eg(ue,{type:$,surface:D.ImprovedSurfaceMaterialType,tenOrMore:D.TenOrMoreParkingSpacesIndicator??null}),{count:le,tenOrMore:W}=P_(D),me=[];V("ProjectParkingSpaceAssignmentType")&&me.push({field:"ProjectParkingSpaceAssignmentType",label:"Assignment",value:D.ProjectParkingSpaceAssignmentType?Hs("ProjectParkingSpaceAssignmentType",D.ProjectParkingSpaceAssignmentType):""}),V("CarStorageAttachmentType")&&me.push({field:"CarStorageAttachmentType",label:"Attachment",value:D.CarStorageAttachmentType?Hs("CarStorageAttachmentType",D.CarStorageAttachmentType):""}),V("ImprovedSurfaceMaterialType")&&me.push({field:"ImprovedSurfaceMaterialType",label:"Surface",value:D.ImprovedSurfaceMaterialType==="Other"?D.ImprovedSurfaceMaterialTypeOtherDescription||"Other":D.ImprovedSurfaceMaterialType?Hs("ImprovedSurfaceMaterialType",D.ImprovedSurfaceMaterialType):""}),V("CarStorageAreaMeasure")&&me.push({field:"CarStorageAreaMeasure",label:"Area",value:D.CarStorageAreaMeasure==null?"":`${D.CarStorageAreaMeasure.toLocaleStr
14ing()} sf`});const Z=z&&W===!0?"TenOrMoreParkingSpacesIndicator":"ParkingSpacesCount",pe=z&&W===!0?"10 or more":le==null?"":String(le),se=[{field:"CarStorageType",label:"Storage Type",value:O_(D)},{field:Z,label:"Spaces",value:pe}].filter(ue=>ue.value.trim()!==""),fe=me.filter(ue=>ue.value.trim()!=="");return e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-start gap-y-0.5 text-left leading-tight","data-testid":`${u}-${D.id}-summary-line`,children:[se.map((ue,be)=>e.jsxs("span",{className:"inline-flex items-center",children:[be>0&&e.jsx("span",{"aria-hidden":"true",className:"mx-1",children:"|"}),ue.value,M(D.id,ue.field,`${b} · ${ue.label}`)]},ue.field)),fe.length>0&&e.jsxs(e.Fragment,{children:[se.length>0&&e.jsx("span",{"aria-hidden":"true",className:"mx-1",children:"|"}),e.jsx("span",{className:"inline-flex flex-wrap items-center justify-start gap-x-1","data-testid":`${u}-${D.id}-detail-group`,children:fe.map(ue=>e.jsxs("span",{className:"inline-flex items-center",children:[ue.value,M(D.id,ue.field,`${b} · ${ue.label}`)]},ue.field))})]}),_===t.length-1&&!T&&e.jsx("span",{"aria-label":"Required Vehicle Storage data is missing",className:"ml-1 inline-block h-1.5 w-1.5 shrink-0 rounded-full bg-red-500","data-testid":`${u}-vehicle-storage-incomplete`,title:"Required Vehicle Storage data is missing"})]},D.id)})})]})}),e.jsxs(bi,{className:"flex max-w-none translate-x-0 translate-y-0 flex-col gap-0 overflow-hidden border-slate-200 bg-white p-0 shadow-xl",onOpenAutoFocus:D=>{D.preventDefault()},style:{left:v.left,top:v.top,maxHeight:v.maxHeight,width:"min(44rem, calc(100vw - 1rem))"},overlayClassName:"bg-black/50","data-testid":`${u}-vehicle-storage-editor`,children:[e.jsxs($i,{className:"shrink-0 border-b border-slate-200 px-3 py-3",children:[e.jsxs(si,{className:"text-sm font-semibold text-slate-800",children:[b," Vehicle Storage"]}),e.jsx(pl,{className:"text-[11px] text-slate-500",children:"Add or edit storage instances for this grid cell."})]}),ae]})]})}const R7=[{id:"siteInfluence",label:"Site Influence (Location)",fid:"1800.0233"},{id:"viewRange",label:"View | Range",fid:"1800.0243"}];function eC(t){return t&&typeof t=="object"?t:null}function ip(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function E7(t){return typeof t=="boolean"?t:t==="true"||t==="Yes"?!0:t==="false"||t==="No"?!1:null}function w7(t){return(Array.isArray(t)?t:[]).slice(0,6).flatMap((s,r)=>{const n=eC(s);if(!n)return[];const i=ip(n.BodyOfWaterType),l=ip(n.BodyOfWaterTypeOtherDescription),c=E7(n.PrivateAccessIndicator);return!i&&!l&&c===null?[]:[{id:ip(n.id)??`body-of-water-${r+1}`,...i?{BodyOfWaterType:i}:{},...i==="Other"&&l?{BodyOfWaterTypeOtherDescription:l}:{},...c!==null?{PrivateAccessIndicator:c}:{}}]})}function P7(t){return(Array.isArray(t)?t:[]).slice(0,V_).flatMap((s,r)=>{const n=eC(s);if(!n)return[];const i=ip(n.SiteInfluenceType),l=ip(n.SiteInfluenceTypeOtherDescription),c=w7(n.bodiesOfWater??n.BodiesOfWater??n.BODIES_OF_WATER);return!i&&!l&&c.length===0?[]:[{id:ip(n.id)??`site-influence-${r+1}`,...i?{SiteInfluenceType:i}:{},...i==="Other"&&l?{SiteInfluenceTypeOtherDescription:l}:{},...i==="BodyOfWater"&&c.length>0?{bodiesOfWater:c}:{}}]})}function O7(t){return(Array.isArray(t)?t:[]).slice(0,33).flatMap((s,r)=>{const n=eC(s);if(!n)return[];const i=ip(n.ViewRangeType),l=ip(n.ViewRangeTypeOtherDescription),c=ip(n.ViewType),d=ip(n.ViewTypeOtherDescription);return!i&&!l&&!c&&!d?[]:[{id:ip(n.id)??`site-view-${r+1}`,...i?{ViewRangeType:i}:{},...i==="Other"&&l?{ViewRangeTypeOtherDescription:l}:{},...c?{ViewType:c}:{},...c==="Other"&&d?{ViewTypeOtherDescription:d}:{}}]})}function bP(t){return typeof t=="string"?t.trim():""}function L7(t){const a=P7([t])[0];if(a?.SiteInfluenceType==="BodyOfWater"){const s=(a.bodiesOfWater??[]).map(r=>r.BodyOfWaterType==="Other"?r.BodyOfWaterTypeOtherDescription??"Other":r.BodyOfWaterType?Hs("BodyOfWaterType",r.BodyOfWaterType):"").filter(Boolean);return s.length>0?s.join(" | "):"Body of Water"}return a?.SiteInfluenceType==="Other"?a.SiteInfluenceTypeOtherDescription??"Other":a?.SiteInfluenceType?Hs("SiteInfluenceType",a.SiteInfluenceType):""}function D7(t){return(Array.isArray(t)?t:[]).map(a=>
14L7(a)).filter(Boolean).join(" | ")}function k7(t){const a=O7([t])[0];if(!a)return"";const s=a.ViewType==="Other"?a.ViewTypeOtherDescription??"Other":a.ViewType?Hs("ViewType",a.ViewType):"",r=a.ViewRangeType==="Other"?a.ViewRangeTypeOtherDescription??"Other":a.ViewRangeType?Hs("ViewRangeType",a.ViewRangeType):"";return[bP(s),bP(r)].filter(Boolean).join(" | ")}function M7(t){return(Array.isArray(t)?t:[]).map(a=>k7(a)).filter(Boolean).join(`
15`)}const F7={mls:"MLS",public_records:"Public record",ai_derived:"AI",user:"User"};function yx({options:t,value:a,otherValue:s,otherMaxLength:r,placeholder:n,ariaLabel:i,onChange:l}){const c=t.filter(u=>u.value!=="Other"),d=a==="Other"?s:c.find(u=>u.value===a)?.label??"",p=u=>{const m=u.trim();if(!m){l("","");return}const h=c.find(f=>f.value.toLowerCase()===m.toLowerCase()||f.label.toLowerCase()===m.toLowerCase());h?l(h.value,""):l("Other",u)};return e.jsx(Kd,{value:d,onChange:p,suggestions:c.map(u=>u.label),placeholder:n,ariaLabel:i,maxLength:a==="Other"?r:void 0,compact:!0,inputClassName:"h-8 rounded-md border-slate-200 bg-white px-2 text-[11px] md:text-[11px]"})}function zT(t){const a=globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`;return`user-site-${t}-${a}`}function gS(t,a,s){return a!=="influence"?t:t.map(r=>r.SiteInfluenceType==="BodyOfWater"&&(!Array.isArray(r.bodiesOfWater)||r.bodiesOfWater.length===0)?{...r,bodiesOfWater:[{id:zT("influence")}]}:r)}function _7(t,a,s){return!s||a!=="influence"?!1:t.some(r=>r.SiteInfluenceType==="BodyOfWater"&&Array.isArray(r.bodiesOfWater)&&r.bodiesOfWater.some(n=>n.PrivateAccessIndicator===!0&&(typeof n.BodyOfWaterName!="string"||n.BodyOfWaterName.trim()==="")))}function U7(t,a,s){return a!=="influence"?!1:t.some(r=>r.SiteInfluenceType==="BodyOfWater"&&(!Array.isArray(r.bodiesOfWater)||r.bodiesOfWater.length===0||r.bodiesOfWater.some(n=>typeof n.BodyOfWaterType!="string"||n.BodyOfWaterType.trim()==="")))}function V7(t,a){return a!=="influence"?!1:t.some(s=>s.SiteInfluenceType==="BodyOfWater"&&(!Array.isArray(s.bodiesOfWater)||s.bodiesOfWater.length===0||s.bodiesOfWater.some(r=>typeof r.PrivateAccessIndicator!="boolean")))}function $7(t,a){return a!=="influence"?!1:t.some(s=>s.SiteInfluenceType==="BodyOfWater"&&Array.isArray(s.bodiesOfWater)&&s.bodiesOfWater.some(r=>r.BodyOfWaterType==="Other"&&(typeof r.BodyOfWaterTypeOtherDescription!="string"||r.BodyOfWaterTypeOtherDescription.trim()==="")))}function yP({kind:t,label:a,items:s,subjectMode:r=!1,activeSource:n="user",sourceCandidates:i,onChange:l,onClearUser:c,onCopyToAll:d,testId:p}){const[u,m]=o.useState(!1),[h,f]=o.useState(()=>gS(s,t)),[v,S]=o.useState(n),[N,x]=o.useState(!1),y=o.useRef(null),b=o.useId(),j=o.useId(),T=_7(h,t,r),O=U7(h,t),E=V7(h,t),R=$7(h,t),G=T||O||E||R;o.useEffect(()=>{u||(f(gS(s,t)),S(n),x(!1))},[n,s,t,u,r]);const U=o.useMemo(()=>t==="influence"?D7(h):M7(h),[h,t]),C=t==="influence"?25:33,F=(_,$,z)=>{S("user"),f(V=>V.map(le=>{if(le.id!==_)return le;const W={...le,[$]:z||void 0};return $==="SiteInfluenceType"&&z==="BodyOfWater"&&(!Array.isArray(le.bodiesOfWater)||le.bodiesOfWater.length===0)&&(W.bodiesOfWater=[{id:zT("influence")}]),$==="SiteInfluenceType"&&z!=="Other"&&(W.SiteInfluenceTypeOtherDescription=void 0),$==="ViewType"&&z!=="Other"&&(W.ViewTypeOtherDescription=void 0),$==="ViewRangeType"&&z!=="Other"&&(W.ViewRangeTypeOtherDescription=void 0),W}))},A=(_,$,z,V)=>{S("user"),f(le=>le.map(W=>{if(W.id!==_)return W;const me=Array.isArray(W.bodiesOfWater)?W.bodiesOfWater:[];return{...W,bodiesOfWater:me.map(Z=>{if(Z.id!==$)return Z;const pe={...Z,[z]:typeof V=="string"?V||void 0:V};return z==="BodyOfWaterType"&&V!=="Other"&&(pe.BodyOfWaterTypeOtherDescription=void 0),z==="WaterAccessRightType"&&V!=="Other"&&(pe.WaterAccessRightTypeOtherDescription=void 0),z==="WaterAccessDepthType"&&V!=="Other"&&(pe.WaterAccessDepthTypeOtherDescription=void 0),pe})}}))},M=_=>{S("user"),f($=>$.filter(z=>z.id!==_))},B=()=>{S("user"),f(_=>_.length>=C?_:[..._,{id:zT(t)}])},oe=()=>{G||(N&&d?d(h):l(h,v),m(!1))},ae=Object.keys(i??{}).filter(_=>Array.isArray(i?.[_])),D=ae.filter(_=>_!=="user");return e.jsxs(xn,{open:u,onOpenChange:m,modal:!0,children:[e.jsx(bn,{asChild:!0,children:e.jsx("button",{ref:y,type:"button",className:"flex min-h-8 w-full min-w-0 items-center justify-start px-2 py-1 text-left text-[11px] text-slate-700 hover:bg-blue-50 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-blue-500",onClick:()=>{f(gS(s,t)),S(n),x(!1)},"data-testid":p,"aria-label":`Edit ${a}`,children:e.jsx("span",{className:U?"whitespace-pre-line":"text-slate-400",children:U})})}),u&&typeof document<"u"&&Wp.createPortal(e.jsx("div",{className:"fixed inset-0 z-[99] bg-slate-950/45 backdrop-blur-[1px]","data-testid":"site-info-editor-overlay","aria-hidden":"true"}),document.body),e.jsxs(yn,{role:"dialog","aria-modal":"true","aria-labelledby":b,"aria-describedby":j,align:"start",side:"right",sideOffset:8,collisionPadding:8,onOpenAutoFocus:_=>{_.preventDefault()},onCloseAutoFocus:_=>{_.preventDefault(),y.current?.focus({preventScroll:!0})},className:"z-[100] flex max-h-[85vh] max-w-[calc(100vw-1rem)] flex-col gap-0 overflow-hidden rounded-lg border-slate-200 bg-white p-0 shadow-xl",style:{width:"min(44rem, calc(100vw - 1rem))"},children:[e.jsxs("div",{className:"shrink-0 border-b border-slate-200 px-3 py-3",children:[e.jsx("h2",{id:b,className:"text-sm font-semibold text-slate-800",children:a}),e.jsx("p",{id:j,className:"mt-1 text-[11px] text-slate-500",children:r?"Add or edit site instances for this grid cell.":"Add or edit site instances and source for this comparable."})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain bg-white",children:[!r&&e.jsx("div",{className:"border-b border-slate-200 px-3 py-2",children:e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsxs("div",{className:"w-56 shrink-0 space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"Source"}),ae.length>0?e.jsxs(sr,{value:v,onValueChange:_=>{const $=i?.[_]??[];f(gS($,t)),S(_)},children:[e.jsx(rr,{className:"h-8 rounded-md border-slate-200 bg-white px-2 text-[11px]",children:e.jsx(or,{})}),e.jsx(nr,{children:ae.map(_=>e.jsx(vs,{value:_,children:F7[_]},_))})]}):e.jsx("div",{className:"rounded-md border border-slate-200 bg-slate-50 px-2 py-1.5 text-[11px] text-slate-600",children:"No source candidate"})]}),D.length===0&&e.jsx("p",{className:"pb-2 text-[10px] leading-snug text-blue-600","data-testid":"site-info-provider-status",children:"No supported MLS, Public Record, or AI value is available for this row."})]})}),h.map((_,$)=>e.jsx("div",{className:"border-b border-slate-200 px-3 py-2",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-4 shrink-0 pt-5 text-[10px] font-semibold tabular-nums text-slate-500",children:$+1}),e.jsx("div",{className:"grid min-w-0 flex-1 grid-cols-1 gap-1.5 md:flex md:flex-wrap md:items-end md:gap-2",children:t==="influence"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"min-w-[12rem] flex-1 space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"Site influence type"}),e.jsx(yx,{options:$_,value:String(_.SiteInfluenceType??""),otherValue:String(_.SiteInfluenceTypeOtherDescription??""),otherMaxLength:rx.SiteInfluenceTypeOtherDescription,placeholder:"Select or type influence…",ariaLabel:`Site influence type ${$+1}`,onChange:(z,V)=>{F(String(_.id),"SiteInfluenceType",z),F(String(_.id),"SiteInfluenceTypeOtherDescription",V)}})]}),_.SiteInfluenceType==="BodyOfWater"&&e.jsx("div",{className:"basis-full space-y-2 md:basis-full",children:(Array.isArray(_.bodiesOfWater)?_.bodiesOfWater:[]).map((z,V)=>e.jsxs("div",{className:"grid grid-cols-1 gap-1.5 border-l-2 border-slate-100 pl-2 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Body of water type ",e.jsx("span",{className:"text-rose-500",children:"*"})]}),e.jsx(yx,{options:B_,value:String(z.BodyOfWaterType??""),otherValue:String(z.BodyOfWaterTypeOtherDescription??""),otherMaxLength:rx.BodyOfWaterTypeOtherDescription,placeholder:"Select or type…",ariaLabel:`Body of water type ${V+1}`,onChange:(le,W)=>{A(String(_.id),String(z.id),"BodyOfWaterType",le),A(String(_.id),String(z.id),"BodyOfWaterTypeOtherDescription",W)}}),(typeof z.BodyOfWaterType!="string"||z.BodyOfWaterType.trim()==="")&&e.jsx("span",{className:"block text-[10px] text-rose-600",children:"Required for a Body of Water influence."})]}),e.jsx("div",{className:"space-y-0.5",children:e.jsx(cy,{label:"Private access",value:typeof z.PrivateAccessIndicator=="boolean"?z.PrivateAccessIndicator:null,onChange:le=>A(String(_.id),String(z.id),"PrivateAccessIndicator",le),testId:`private-access-${V+1}`,labelClass:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",className:"gap-0.5"})}),r&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"Proximity"}),e.jsxs(sr,{value:String(z.BodyOfWaterProximityType??"")||void 0,onValueChange:le=>A(String(_.id),String(z.id),"BodyOfWaterProximityType",le),children:[e.jsx(rr,{className:"h-8 rounded-md border-slate-200 bg-white px-2 text-[11px]",children:e.jsx(or,{placeholder:"Select proximity…"})}),e.jsx(nr,{children:z_.map(le=>e.jsx(vs,{value:le.value,children:le.label},le.value))})]})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"Impact"}),e.jsxs(sr,{value:String(z.ValueMarketabilityImpactType??"")||void 0,onValueChange:le=>A(String(_.id),String(z.id),"ValueMarketabilityImpactType",le),children:[e.jsx(rr,{className:"h-8 rounded-md border-slate-200 bg-white px-2 text-[11px]",children:e.jsx(or,{placeholder:"Select impact…"})}),e.jsx(nr,{children:q_.map(le=>e.jsx(vs,{value:le.value,children:le.label},le.value))})]})]})]}),r&&z.PrivateAccessIndicator===!0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:["Body of water name ",e.jsx("span",{className:"text-rose-500",children:"*"})]}),e.jsx(ze,{className:`h-8 rounded-md bg-white px-2 text-[11px] md:text-[11px] ${typeof z.BodyOfWaterName!="string"||z.BodyOfWaterName.trim()===""?"border-red-400 bg-red-50/40 ring-1 ring-red-200":""}`,value:String(z.BodyOfWaterName??""),onChange:le=>A(String(_.id),String(z.id),"BodyOfWaterName",le.target.value),placeholder:"Enter name…","aria-invalid":typeof z.BodyOfWaterName!="string"||z.BodyOfWaterName.trim()===""}),(typeof z.BodyOfWaterName!="string"||z.BodyOfWaterName.trim()==="")&&e.jsx("span",{className:"block text-[10px] text-rose-600",children:"Required when private access is Yes."})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"Waterfront access rights"}),e.jsx(yx,{options:Y_,value:String(z.WaterAccessRightType??""),otherValue:String(z.WaterAccessRightTypeOtherDescription??""),otherMaxLength:rx.WaterAccessRightTypeOtherDescription,placeholder:"Select or type rights…",ariaLabel:`Waterfront access rights ${V+1}`,onChange:(le,W)=>{A(String(_.id),String(z.id),"WaterAccessRightType",le),A(String(_.id),String(z.id),"WaterAccessRightTypeOtherDescription",W)}})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"Water access depth"}),e.jsx(yx,{options:G_,value:String(z.WaterAccessDepthType??""),otherValue:String(z.WaterAccessDepthTypeOtherDescription??""),otherMaxLength:rx.WaterAccessDepthTypeOtherDescription,placeholder:"Select or type depth…",ariaLabel:`Water access depth ${V+1}`,onChange:(le,W)=>{A(String(_.id),String(z.id),"WaterAccessDepthType",le),A(String(_.id),String(z.id),"WaterAccessDepthTypeOtherDescription",W)}})]})]})]},String(z.id)))})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"min-w-[12rem] flex-1 space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"View type"}),e.jsx(yx,{options:H_,value:String(_.ViewType??""),otherValue:String(_.ViewTypeOtherDescription??""),otherMaxLength:rx.ViewTypeOtherDescription,placeholder:"Select or type view…",ariaLabel:`View type ${$+1}`,onChange:(z,V)=>{F(String(_.id),"ViewType",z),F(String(_.id),"ViewTypeOtherDescription",V)}})]}),e.jsxs("div",{className:"min-w-[12rem] flex-1 space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"View range"}),e.jsx(yx,{options:W_,value:String(_.ViewRangeType??""),otherValue:String(_.ViewRangeTypeOtherDescription??""),otherMaxLength:rx.ViewRangeTypeOtherDescription,placeholder:"Select or type range…",ariaLabel:`View range ${$+1}`,onChange:(z,V)=>{F(String(_.id),"ViewRangeType",z),F(String(_.id),"ViewRangeTypeOtherDescription",V)}})]})]})}),e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"mt-4 h-6 w-6 shrink-0 rounded-sm p-0 text-slate-400 hover:bg-rose-50 hover:text-rose-600",onClick:()=>M(String(_.id)),"aria-label":`Remove ${a} ${$+1}`,children:e.jsx(Ci,{className:"h-3 w-3"})})]})},String(_.id))),e.jsx("div",{className:"px-3 py-2",children:e.jsxs(De,{type:"button",variant:"outline",size:"sm",className:"h-8 w-full justify-center rounded-md border-dashed border-slate-400 bg-white text-[11px] font-medium text-slate-700 hover:bg-slate-50",onClick:B,disabled:h.length>=C,children:[e.jsx(un,{className:"mr-2 h-3.5 w-3.5"}),"Add ",t==="influence"?"site influence":"view"]})})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2 border-t border-slate-200 bg-slate-50 px-3 py-2",children:[!r&&d&&e.jsxs(De,{type:"button",variant:"outline",size:"sm",className:"h-8 text-[11px]",onClick:()=>x(!0),children:[e.jsx(jr,{className:"mr-1 h-3.5 w-3.5"}),N?"Copy queued":"Copy to all comps"]}),!r&&c&&e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"h-8 text-[11px]",onClick:()=>{c(),m(!1)},children:"Clear User"}),e.jsxs("div",{className:"ml-auto flex gap-2",children:[e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"h-8 text-[11px]",onClick:()=>m(!1),children:"Cancel"}),e.jsx(De,{type:"button",size:"sm",className:"h-8 text-[11px]",onClick:oe,disabled:G,children:"Save"})]})]})]})]})}const B7=/^Comp(\d+)(.*)$/;function z7(t){const a=B7.exec(t);if(!a)return null;const s=a[2];if(/^\d/.test(s))return null;const r=parseInt(a[1],10);return!Number.isFinite(r)||r<1?null:{slot:r,suffix:s}}function Lk(t,a,s,r="salesComparison"){if(!Number.isFinite(a)||a<1)return[];const n=new Map;let i=0;for(const[p,u]of Object.entries(t??{})){const m=z7(p);if(!m)continue;let h=n.get(m.slot);h||(h=new Map,n.set(m.slot,h)),h.set(m.suffix,u?.value),m.slot>i&&(i=m.slot)}const l=Math.max(a,s,i),c=[],d=p=>p==null||p==="";for(let p=a;p<=l;p++){const u=n.get(p)??new Map,m=p<l?n.get(p+1)??new Map:new Map,h=new Set([...u.keys(),...m.keys()]);for(const f of h){const v=m.has(f)?m.get(f)??null:null,S=u.has(f)?u.get(f):void 0;
15Object.is(S,v)||d(S)&&d(v)||c.push({field:`Comp${p}${f}`,value:v})}}return c}const xS=80,SP=36,q7=10,vP=.06,kp=t=>"$"+Math.round(t/1e3)+"K";function Y7(t){return t==="Most"?"h-4 w-4":t==="Less"?"h-2.5 w-2.5":t==="NoWeight"?"h-2 w-2 opacity-50":"h-3 w-3"}function G7(t,a,s){return t==="NoWeight"?"bg-slate-400":a?"bg-amber-500":s?"bg-emerald-400":"bg-emerald-500"}function H7({unadjMin:t,unadjMax:a,unadjPrices:s,adjMin:r,adjMax:n,adjPrices:i,hasAdj:l,adjSpread:c,adjPct:d,indicatedValue:p,setIndicatedValue:u,fmtCur:m,inspectSection:h="salesGrid",inspectFieldName:f="indicatedValue",weightedDots:v,weightedSuggested:S,automaticValue:N,onUseAutomatic:x,valueMode:y="manual",onUseSuggested:b,readOnly:j=!1,opinionOfMarketValue:T,setOpinionOfMarketValue:O,marketValueCondition:E,toggleMarketValueCondition:R,effectiveDate:G,setEffectiveDate:U}){const C=o.useRef(null),[F,A]=o.useState(!1),[M,B]=o.useState(!1),{inspecting:oe}=fc(),ae=ne=>{const Me=parseFloat(String(ne).replace(/[^0-9.]/g,""));return isNaN(Me)?0:Me},D=p&&ae(p)>0?ae(p):Math.round((r+n)/2),_=ne=>u(String(Math.round(ne))),$=N!=null&&N>0?N:S,z=$!=null&&$>0,V=N!=null&&N>0,le=p.trim()===""||D<=0,W=y==="manual",me=z?Math.abs(D-$):null,Z=W&&me!=null&&z?me/$>.02:!1,pe=d>25,se=d>15&&!pe,fe=Math.min(t,r,D>0?D:t)*(1-vP),ue=Math.max(a,n,D>0?D:a)*(1+vP),be=Math.max(ue-fe,1),H=ne=>(ne-fe)/be*100,ye=H(D),de=z?H($):null,ge=D>=r&&D<=n,He=!(D>=t&&D<=a),Ie=pe?"bg-amber-500":se?"bg-emerald-400":"bg-emerald-500",ce=He?"#dc2626":"#2563eb",Pe=ne=>{const Me=C.current?.getBoundingClientRect();if(!Me||Me.width===0)return D;const lt=Me.width-xS,Tt=Me.left+xS,je=Math.max(0,Math.min(1,(ne-Tt)/lt));return Math.round((fe+je*be)/1e3)*1e3},We=[];He?We.push({kind:"error",testid:"flag-outside-unadjusted",text:`Indicated value (${m(D)}) falls outside the unadjusted sale-price range (${kp(t)}–${kp(a)}). This is uncommon and will require strong narrative support explaining why the concluded value is supportable despite being outside all comp sale prices.`}):l&&!ge&&We.push({kind:"warning",testid:"flag-outside-adjusted",text:`Indicated value (${m(D)}) is outside the adjusted range (${kp(r)}–${kp(n)}). Your reconciliation narrative must explain why the concluded value is appropriate despite falling outside your comp adjustments.`}),l&&pe?We.push({kind:"advisory",testid:"flag-wide-spread",text:`Adjusted spread of ${d.toFixed(0)}% is wider than typical. A wide spread often signals that the comps are not closely comparable after adjustment — reviewers may question whether the right sales were selected. Your narrative should explain why each comp was chosen and why the adjustments are well-supported.`}):l&&se&&We.push({kind:"advisory",testid:"flag-moderate-spread",text:`Adjusted spread of ${d.toFixed(0)}% is moderate. Make sure your reconciliation narrative addresses the range and explains where the indicated value falls within it.`});const Re={error:{bg:"bg-red-50 border-red-200",icon:"text-red-500",text:"text-red-900"},warning:{bg:"bg-orange-50 border-orange-200",icon:"text-orange-500",text:"text-orange-900"},advisory:{bg:"bg-amber-50 border-amber-200",icon:"text-amber-500",text:"text-amber-900"}};return e.jsx("div",{className:"mx-4 mt-3 mb-4","data-testid":"indicated-value-footer",children:e.jsxs("div",{className:"max-w-3xl bg-white rounded-2xl shadow-sm ring-1 ring-slate-200 overflow-visible",children:[e.jsxs("div",{className:"flex items-center gap-5 px-6 py-5",children:[e.jsxs("div",{className:"shrink-0",style:{width:144},children:[e.jsxs("p",{className:"text-[9px] font-bold uppercase tracking-widest text-slate-400 mb-1.5",children:["Indicated Value",oe&&e.jsx(Fs,{section:h,fieldName:f})]}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-sm font-bold text-slate-400",children:"$"}),e.jsx("input",{id:"input-indicated-value-sca","data-testid":"input-indicated-value-sca",type:"text",inputMode:"numeric",readOnly:j,value:p?Number(ae(p)).toLocaleString():"",onChange:ne=>!j&&u(ne.target.value.replace(/[^0-9]/g,"")),placeholder:l?m(Math.round((r+n)/2)).replace("$",""):"Enter value",className:Q("w-full rounded-xl border-2 border-slate-200 bg-white py-2.5 pl-7 pr-2 text-[18px] font-black text-slate-900 leading-none",j?"cursor-default":"focus:border-blue-500 focus:outline-none")})]})]}),e.jsxs("div",{ref:C,"data-testid":"range-bar",className:Q("relative flex-1 min-w-0 select-none overflow-visible",j?"cursor-default":"cursor-pointer"),style:{paddingLeft:xS,paddingTop:8,paddingBottom:4},onPointerDown:j?void 0:ne=>{ne.target.setPointerCapture?.(ne.pointerId),A(!0),_(Pe(ne.clientX))},onPointerMove:j?void 0:ne=>{F&&_(Pe(ne.clientX))},onPointerUp:j?void 0:()=>A(!1),children:[e.jsx("div",{className:"pointer-events-none absolute z-20",style:{left:`calc(${ye}% + ${xS}px)`,top:0,bottom:0,width:2,transform:"translateX(-50%)",backgroundColor:ce}
15,children:e.jsx("div",{className:"absolute -top-7 left-1/2 -translate-x-1/2 whitespace-nowrap z-30",children:!j&&M?e.jsx("input",{type:"number",autoFocus:!0,step:5e3,defaultValue:D,onPointerDown:ne=>ne.stopPropagation(),onClick:ne=>ne.stopPropagation(),onBlur:ne=>{_(Number(ne.target.value)||0),B(!1)},onKeyDown:ne=>{ne.key==="Enter"&&(_(Number(ne.target.value)||0),B(!1)),ne.key==="Escape"&&B(!1)},"data-testid":"input-reconciled",className:"w-28 rounded-md border border-blue-600 bg-white px-2 py-1 text-center text-xs font-semibold text-blue-700 shadow focus:outline-none"}):j?e.jsx("div",{"data-testid":"display-reconciled",className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[12px] font-black text-white shadow-md",style:{backgroundColor:ce},children:kp(D)}):e.jsx("button",{type:"button",onPointerDown:ne=>ne.stopPropagation(),onClick:ne=>{ne.stopPropagation(),B(!0)},"data-testid":"button-reconciled",title:"Click to type your indicated value",className:"flex items-center gap-1 rounded-lg px-2.5 py-1 text-[12px] font-black text-white shadow-md hover:opacity-90",style:{backgroundColor:ce},children:kp(D)})})}),e.jsxs("div",{className:"relative flex items-center",style:{height:SP},children:[e.jsx("span",{className:"pointer-events-none absolute text-[10px] font-bold uppercase tracking-wider text-slate-400 whitespace-nowrap",style:{right:"calc(100% + 8px)",top:"50%",transform:"translateY(-50%)"},children:"Unadjusted"}),e.jsx("div",{className:"absolute top-1/2 -translate-y-1/2 h-0.5 rounded-full bg-slate-300",style:{left:`${H(t)}%`,width:`${H(a)-H(t)}%`},"data-testid":"range-bar-unadjusted"}),e.jsx("span",{className:"pointer-events-none absolute -translate-x-1/2 text-[10px] font-semibold text-slate-400 whitespace-nowrap",style:{left:`${H(t)}%`,top:0},children:kp(t)}),e.jsx("span",{className:"pointer-events-none absolute -translate-x-1/2 text-[10px] font-semibold text-slate-400 whitespace-nowrap",style:{left:`${H(a)}%`,top:0},children:kp(a)}),(s??[]).map((ne,Me)=>e.jsx("div",{className:"absolute top-1/2 -translate-x-1/2 -translate-y-1/2 h-3 w-3 rounded-full border-2 border-white shadow-sm z-10 bg-slate-400",style:{left:`${H(ne)}%`},title:`Comp ${Me+1} sale price: ${m(ne)}`},`udot-${Me}`))]}),e.jsx("div",{style:{height:q7}}),l&&e.jsxs("div",{className:"relative flex items-center",style:{height:SP},children:[e.jsx("span",{className:Q("pointer-events-none absolute text-[10px] font-bold uppercase tracking-wider whitespace-nowrap",pe?"text-amber-600":"text-emerald-600"),style:{right:"calc(100% + 8px)",top:"50%",transform:"translateY(-50%)"},children:"Adjusted"}),e.jsx("div",{className:Q("absolute top-1/2 -translate-y-1/2 h-0.5 rounded-full",Ie),style:{left:`${H(r)}%`,width:`${H(n)-H(r)}%`},"data-testid":"range-bar-adjusted"}),e.jsx("span",{className:Q("pointer-events-none absolute -translate-x-1/2 text-[10px] font-semibold whitespace-nowrap",pe?"text-amber-600":"text-slate-400"),style:{left:`${H(r)}%`,bottom:0},children:kp(r)}),e.jsx("span",{className:Q("pointer-events-none absolute -translate-x-1/2 text-[10px] font-semibold whitespace-nowrap",pe?"text-amber-600 font-bold":"text-slate-400"),style:{left:`${H(n)}%`,bottom:0},children:kp(n)}),v&&v.length>0?v.map((ne,Me)=>e.jsx("div",{className:Q("absolute top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-sm z-10",Y7(ne.weight),G7(ne.weight,pe,se)),style:{left:`${H(ne.value)}%`},title:`Comp ${Me+1} adjusted: ${m(ne.value)} — ${VT[ne.weight]}`,"data-testid":`range-bar-dot-${Me}`},`wdot-${Me}`)):i.map((ne,Me)=>e.jsx("div",{className:Q("absolute top-1/2 -translate-x-1/2 -translate-y-1/2 h-3 w-3 rounded-full border-2 border-white shadow-sm z-10",pe?"bg-amber-500":"bg-emerald-500"),style:{left:`${H(ne)}%`},title:`Adjusted comp: ${m(ne)}`},`dot-${Me}`)),W&&de!=null&&e.jsx("div",{className:"absolute top-1/2 -translate-x-1/2 z-10 text-violet-500",style:{left:`${de}%`,lineHeight:1,transform:"translateX(-50%) translateY(-30%)"},"data-testid":"range-bar-weighted-suggested",title:`Suggested: ${m($)}`,children:e.jsx("svg",{width:"11",height:"9",viewBox:"0 0 11 9",children:e.jsx("path",{d:"M5.5 0 L11 9 L0 9 Z",fill:"currentColor",opacity:"0.9"})})})]})]}),e.jsxs("div",{className:"shrink-0 flex flex-col items-end gap-2",children:[l&&(He?e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-red-600 px-3 py-1.5 text-[12px] font-bold text-white shadow-sm whitespace-nowrap","data-testid":"badge-outside-unadjusted",children:[e.jsx(nf,{className:"h-3.5 w-3.5"})," Outside unadjusted"]}):ge?e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-emerald-600 px-3 py-1.5 text-[12px] font-bold text-white shadow-sm whitespace-nowrap","data-testid":"badge-in-range",children:[e.jsx(Bs,{className:"h-3.5 w-3.5"})," In range"]}):e.jsxs("span",{className:"flex items-center gap-1.5 rounded-lg bg-orange-500 px-3 py-1.5 text-[12px] font-bold text-white shadow-sm whitespace-nowrap","data-testid":"badge-outside-adjusted",children:[e.jsx(Ns,{className:"h-3.5 w-3.5"})," Outside adjusted"]})),l&&e.jsxs("span",{className:Q("rounded-lg px-3 py-1.5 text-[12px] font-bold shadow-sm whitespace-nowrap",pe?"bg-amber-500 text-white":se?"bg-amber-100 text-amber-800":"bg-slate-100 text-slate-600"),"data-testid":"range-spread-badge",children:[pe?"Wide":se?"Moderate":"Tight"," spread · ",d.toFixed(0),"%"]})]})]}),We.length>0&&e.jsx("div",{className:"px-4 pb-4 flex flex-col gap-2",children:We.map((ne,Me)=>{const lt=Re[ne.kind],Tt=ne.kind==="error"?nf:Ns;return e.jsxs("div",{className:Q("flex items-start gap-3 rounded-xl border px-5 py-3.5 text-[12px] leading-relaxed",lt.bg,lt.text),"data-testid":ne.testid,children:[e.jsx(Tt,{className:Q("h-4 w-4 mt-0.5 shrink-0",lt.icon)}),e.jsx("span",{children:ne.text})]},Me)})}),!j&&W&&z&&($!==D||le)&&(V?x:b)&&e.jsxs("div",{className:"px-6 pb-4 flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:V?x:b,"data-testid":"button-use-suggested",title:V?"Apply the suggested range midpoint and resume live tracking":"Apply the weight-suggested value and resume tracking your Comparable Weight selections",className:"rounded-md bg-vi
15olet-100 px-2.5 py-1 text-[11px] font-semibold text-violet-800 ring-1 ring-violet-300 hover:bg-violet-200",children:["Use suggested"," ",m($)]}),Z&&e.jsx("span",{className:"text-[11px] text-amber-700","data-testid":"weight-misalignment-note",children:V?`Differs from the suggested midpoint by ${m(me??0)}.`:`Differs from your weight selection by ${m(me??0)}.`})]}),e.jsx("span",{"data-testid":"range-bar-legend",className:"sr-only"}),W&&z&&e.jsx("span",{"data-testid":"legend-weighted-suggested",className:"sr-only"})]})})}function W7(){return{chains:new Map,versions:new Map}}function Yb(t,a,s,r,n){const i=(t.versions.get(a)??0)+1;t.versions.set(a,i);const c=(t.chains.get(a)??Promise.resolve()).catch(()=>{}).then(async()=>{await s()});return t.chains.set(a,c),c.then(()=>{t.versions.get(a)===i&&r()},d=>{t.versions.get(a)===i&&n(d)}).finally(()=>{t.chains.get(a)===c&&t.chains.delete(a)}),c}const K7="SettledSale";function Mh(t){if(t==null||t==="")return null;const a=typeof t=="number"?t:Number(t);return Number.isFinite(a)?a:null}function Wx(t){const a=Mh(t);return a!==null&&a>0?a:null}function Q7(t){return Wx(t.salePrice)??Wx(t.contractPrice)??Wx(t.listPrice)}function Z7(t){const a=t.listingStatusType;return a!=null&&String(a).trim()!==""?String(a).trim()===K7:Wx(t.salePrice)!==null}function J7(t){const a=Mh(t.netAdjustment)??0,s=Z7(t)?Wx(t.salePrice):Wx(t.listPrice);return s===null?null:s+a}function X7(t){const a=Mh(t);return a!==null&&a>1}function bS(t,a){return t===null||a===null||a<=0?null:t/a}function eH(t){const a=J7(t),s=Q7(t),r=(Mh(t.aboveGradeStandardArea)??0)+(Mh(t.aboveGradeNonStandardArea)??0);return{adjustedPrice:a,adjustedPricePerUnit:bS(a,Mh(t.livingUnitCount)),adjustedPricePerBedroom:bS(a,Mh(t.bedroomCount)),pricePerGrossBuildingFinishedArea:bS(s,Mh(t.totalFinishedArea)),pricePerAboveGradeFinishedArea:bS(s,r>0?r:null)}}const U0="ProximityToSubjectDistanceLinearMeasure",Yv="LinearUnitOfMeasureType",Gv="ComparableToSubjectDirectionType",tH={Miles:"Miles",Kilometers:"Km."},NP={North:"N",NorthEast:"NE",East:"E",SouthEast:"SE",South:"S",SouthWest:"SW",West:"W",NorthWest:"NW"};function aH(t){const a=String(fy(t)??"").trim();if(/^km\.?$/i.test(a))return"Km.";const s=Dk(t);return s?tH[s]:""}function sH(t){const a=String(fy(t)??"").trim().toUpperCase();if(Object.values(NP).includes(a))return a;const s=kk(t);return s?NP[s]:""}const rH=new Set(["North","NorthEast","East","SouthEast","South","SouthWest","West","NorthWest"]);function fy(t){return t&&typeof t=="object"&&"value"in t?t.value:t}function nH(t){if(t==null)return!0;if(typeof t=="string"){const a=t.trim();return a===""||a==="undefined"||a==="null"||a==="NaN"}return!1}function iH(t){const a=fy(t);if(nH(a))return null;const s=typeof a=="number"?a:Number(a);return Number.isFinite(s)&&s>=0?s:null}function Dk(t){const a=String(fy(t)??"").trim();return a==="Miles"||a==="Kilometers"?a:null}function kk(t){const a=String(fy(t)??"").trim();return rH.has(a)?a:null}function oH(t){const a=iH(t[U0]);return{distance:a,unit:Dk(t[Yv]),direction:a!==null&&a>0?kk(t[Gv]):null}}function qT(t,a={}){const s=oH(t);if(s.distance===null)return"";const r=Number(s.distance.toFixed(2)).toString(),n=s.unit??a.defaultUnit,i=[r,aH(n)].filter(Boolean);return a.includeDirection!==!1&&s.direction&&i.push(sH(s.direction)),i.join(" ")}function lH(t){if(t==null||t==="")return null;const a=typeof t=="number"?t:Number(t);return Number.isFinite(a)?a:null}function AP(t){const a=lH(t);return a===null?"":`${a<0?"-":""}$${Math.abs(Math.round(a)).toLocaleString("en-US")}`}function vg(t){return t==null?"":String(t).trim()}function yS(t){return t===!0||vg(t).toLowerCase()==="true"}function SS(t){return t===!1||vg(t).toLowerCase()==="false"}function vS(t){return t.applicabilityAlreadyResolved===!0||vg(t.get("OwnershipTransferTransactionType"))==="Sale"}function jP(t,a){return vg(t.get(`${a}OtherDescription`))}function TP(t,a,s){const r=vg(a);return r?r==="Other"?s||"Other":Dc(t,r):""}function DN(t,a){if(t==="SalePrice"){if(a.role==="subject")return{field:t,state:"gray",text:""};if(!vS(a))return{field:t,state:"em-dash",text:"—"};const n=AP(a.get("OwnershipTransferTransactionAmount"));return{field:t,state:n?"value":"blank",text:n}}if(t==="SaleType"){if(a.role==="subject"||!vS(a))return{field:t,state:a.role==="subject"?"gray":"em-d
15ash",text:a.role==="subject"?"":"—"};const n=vg(a.get("SaleType"));return{field:t,state:n?"value":"blank",text:TP("SaleType",n,jP(a,"SaleType"))}}if(t==="FinancingType"){if(a.role==="subject"||!vS(a))return{field:t,state:a.role==="subject"?"gray":"em-dash",text:a.role==="subject"?"":"—"};if(yS(a.get("NoFinancingTransactionIndicator")))return{field:t,state:"value",text:"Cash"};const n=vg(a.get("MortgageType"));return{field:t,state:n?"value":"blank",text:TP("MortgageType",n,jP(a,"MortgageType"))}}if(a.role==="subject"&&(SS(a.get("SalesContractExistsIndicator"))||SS(a.get("SalesContractReviewedIndicator"))))return{field:t,state:"em-dash",text:"—"};if(a.role==="comparable"&&!vS(a))return{field:t,state:"em-dash",text:"—"};const s=a.get("SalesConcessionIndicator"),r=a.get("SalesConcessionAmountKnownIndicator");if(SS(s))return{field:t,state:"value",text:"No"};if(yS(s)&&SS(r))return{field:t,state:"value",text:"Unknown"};if(yS(s)&&yS(r)){const n=AP(a.get("TotalSalesConcessionAmount"));return{field:t,state:n?"value":"blank",text:n}}return{field:t,state:"blank",text:""}}function cH(t){switch(t){case"SalePrice":case"OwnershipTransferTransactionAmount":return"SalePrice";case"SaleType":return"SaleType";case"FinancingType":case"NoFinancingTransactionIndicator":case"MortgageType":return"FinancingType";case"TotalSalesConcessionAmount":return"SalesConcessions";default:return null}}function dH({getValue:t,setValue:a,disabled:s,testId:r,resolvedDisplay:n=!1}){const i="Cash",l=(Pr("MortgageType")??[]).filter(u=>u!=="Other"),c=u=>Dc("MortgageType",u),d=K_("MortgageType")??21,p=DN("FinancingType",{role:"comparable",get:t,applicabilityAlreadyResolved:!0}).text;return e.jsx(Kd,{value:p,suggestions:[i,...l.map(c)],compact:!0,disabled:s,resolvedDisplay:n,testId:r,ariaLabel:"Financing Type",maxLength:d,inputClassName:"h-8 text-[12px] md:text-[12px] font-medium text-slate-800 placeholder-hint",onCh
15ange:u=>{const m=u.trim(),h=[i.toLowerCase(),"cash"].includes(m.toLowerCase()),f=l.find(v=>[v.toLowerCase(),c(v).toLowerCase()].includes(m.toLowerCase()));a("NoFinancingTransactionIndicator",m?h:null),a("MortgageType",!m||h?null:f??"Other"),a("MortgageTypeOtherDescription",!m||h||f?null:u.slice(0,d))}})}function uH({type:t,otherDescription:a,onTypeChange:s,onOtherDescriptionChange:r,disabled:n,testId:i}){const l=Q_(t,a),c=Z_(),d=l?"ADU/Garage":t==="Other"?a||"":t?c.find(E=>E.value===t)?.label??t:"",[p,u]=o.useState(""),[m,h]=o.useState(!1),[f,v]=o.useState({}),S=o.useRef(null),N=o.useRef(null),x=p.trim().toLowerCase(),y=x?c.filter(E=>E.label.toLowerCase().includes(x)):c,b=()=>{if(!N.current)return;const E=N.current.getBoundingClientRect();v({position:"fixed",top:E.bottom+2,left:E.left,width:Math.max(E.width,180),maxHeight:200,zIndex:9999,overflow:"auto"})},j=E=>{E===pE?(s("Other"),r(X_)):(s(E||null),r(null)),u(""),h(!1)},T=()=>{const E=p.trim();if(!E){u("");return}const R=c.find(G=>G.label.toLowerCase()===E.toLowerCase()||G.value.toLowerCase()===E.toLowerCase());R?j(R.value):(s("Other"),r(E)),u(""),h(!1)},O=E=>{E.preventDefault(),E.stopPropagation(),s(null),r(null),u(""),h(!1),N.current?.focus()};return o.useEffect(()=>{if(!m)return;const E=R=>{S.current?.contains(R.target)||(T(),h(!1))};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[m,p]),o.useEffect(()=>{if(!m)return;const E=()=>b();return window.addEventListener("scroll",E,!0),window.addEventListener("resize",E),()=>{window.removeEventListener("scroll",E,!0),window.removeEventListener("resize",E)}},[m]),e.jsxs("div",{className:"relative",ref:S,"data-testid":i,children:[e.jsxs("div",{className:"relative flex items-center",children:[e.jsx("input",{ref:N,type:"text",className:"h-7 w-full text-xs rounded-md border border-input bg-transparent px-2 py-1 pr-8 outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",value:m?p:d,placeholder:"Select or type…",disabled:n,autoComplete:"off","data-testid":i?`${i}-type`:void 0,onFocus:()=>{b(),u(""),h(!0)},onChange:E=>{u(E.target.value),m||(b(),h(!0))},onBlur:()=>{setTimeout(()=>{S.current?.contains(document.activeElement)||(T(),h(!1))},150)},onKeyDown:E=>{E.key==="Enter"?(E.preventDefault(),y.length>0&&x?j(y[0].value):T()):E.key==="Escape"?(u(""),h(!1)):E.key==="ArrowDown"&&!m&&(b(),h(!0))}}),e.jsxs("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 flex items-center gap-0.5",children:[d&&!n&&e.jsx("button",{type:"button",onMouseDown:O,tabIndex:-1,className:"text-slate-400 hover:text-slate-700","aria-label":"Clear outbuilding type","data-testid":i?`${i}-clear`:void 0,children:e.jsx(ur,{className:"w-3 h-3"})}),!n&&e.jsx("button",{type:"button",tabIndex:-1,onMouseDown:E=>{E.preventDefault(),m?(T(),h(!1)):(b(),u(d),h(!0),N.current?.focus())},className:"text-muted-foreground","aria-label":"Toggle suggestions",children:e.jsx(Rr,{className:Q("w-3.5 h-3.5 transition-transform",m&&"rotate-180")})})]})]}),m&&y.length>0&&e.jsx("div",{role:"listbox",style:f,className:"rounded-md border border-slate-200 bg-white shadow-lg","data-testid":i?`${i}-listbox`:void 0,children:y.map(E=>{const R=E.value===pE?l:E.value===t&&!l;return e.jsxs("button",{type:"button",role:"option",tabIndex:-1,"aria-selected":R,onMouseDown:G=>{G.preventDefault(),j(E.value)},className:"flex w-full items-center gap-1.5 px-3 py-1.5 text-left text-xs hover:bg-slate-100","data-testid":i?`${i}-option-${E.value}`:void 0,children:[e.jsx("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:R?e.jsx(Bs,{className:"w-3 h-3"}):null}),E.label]},E.value)})})]})}function pH(t){return(t??"").split("|").map(a=>a.trim()).filter(Boolean)}function mH({value:t,onChange:a,disabled:s,testId:r}){const[n,i]=o.useState(""),l=pH(t),c=u=>{const m=u.trim();if(!m||l.includes(m))return;const h=m==="None"?[]:l.filter(f=>f!=="None");a([...h,m].join("|"))},d=u=>{a(l.filter(m=>m!==u).join("|"))},p=J_.filter(u=>u!=="Other");return e.jsxs("div",{className:"space-y-1","data-testid":r,children:[l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:l.map(u=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-slate-100 px-1.5 py-0.5 text-[11px] text-slate-700","data-testid":r?`${r}-chip-${u}`:void 0,children:[u,!s&&e.jsx("button",{type:"button",onClick:()=>d(u),className:"text-slate-400 hover:text-rose-500","aria-label":`Remove ${u}`,children:e.jsx(ur,{className:"w-2.5 h-2.5"})})]},u))}),!s&&e.jsx("div",{className:"flex flex-wrap gap-1",children:p.map(u=>e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:Q("h-5 px-1.5 text-[10px] rounded border",l.includes(u)?"bg-slate-200 border-slate-300 text-slate-700 line-through":"border-slate-200 text-slate-500 hover:bg-slate-100"),onClick:()=>l.includes(u)?d(u):c(u),"data-testid":r?`${r}-toggle-${u}`:void 0,children:u},u))}),!s&&e.jsx("input",{type:"text",value:n,onChange:u=>i(u.target.value),onKeyDown:u=>{(u.key==="Enter"||u.key===",")&&n.trim()&&(u.preventDefault(),c(n),i(""))},placeholder:"Other — type and press Enter",className:"h-6 w-full rounded border border-slate-200 bg-transparent px-2 text-[11px] outline-none focus:ring-1 focus:ring-ring","data-testid":r?`${r}-custom-input`:void 0})]})}function kn({state:t,children:a,className:s,title:r,testId:n,ariaDisabled:i}){const c=[t==="gray"?`flex min-h-5 w-full items-center justify-start gap-0 bg-slate-100 ${Ou}`:t==="em-dash"?`flex min-h-5 w-full items-center justify-start gap-0 ${eU}`:`flex min-h-5 w-full items-center justify-start gap-0 ${Ou}
15`,s??""].filter(Boolean).join(" ");return e.jsx("span",{className:c||void 0,title:r,"data-testid":n,"data-cell-state":t,"aria-disabled":i||void 0,children:t==="em-dash"?"—":t==="value"?a:null})}const hH=["water","energy","amenities","project","outbuilding"];new Set(hH);const wh=t=>typeof t=="string"&&t!==""?t:null,fH=t=>typeof t=="boolean"?t:null,gH=t=>typeof t=="number"&&Number.isFinite(t)?t:null;function xH(t,a){const s=t??{};return{id:wh(s.id)??`csu-${a}`,isAdu:s.isAdu===!0,kitchenCount:gH(s.kitchenCount)}}function bH(t,a){const s=t??{},r=s.improvementType==="Outbuilding"?"Outbuilding":s.improvementType==="Dwelling"?"Dwelling":null;return r?{id:wh(s.id)??`cs-${a}`,improvementType:r,label:wh(s.label),attachmentType:wh(s.attachmentType),structuralDesignType:wh(s.structuralDesignType),constructionMethods:Array.isArray(s.constructionMethods)?s.constructionMethods.filter(n=>typeof n=="string"&&n!==""):[],manufacturedHomeWidthType:wh(s.manufacturedHomeWidthType),outbuildingType:wh(s.outbuildingType),outbuildingTypeOtherDescription:wh(s.outbuildingTypeOtherDescription),outbuildingRealPropertyIndicator:fH(s.outbuildingRealPropertyIndicator),units:Array.isArray(s.units)?s.units.map(xH):[]}:null}function yj(t){if(t==null||t==="")return[];let a=t;if(typeof t=="string")try{a=JSON.parse(t)}catch{return[]}return Array.isArray(a)?a.map((s,r)=>bH(s,r)).filter(s=>s!==null):[]}function yH(t){return JSON.stringify(t)}function SH(t){return{id:t.id,improvementType:t.improvementType,outbuildingRealPropertyIndicator:t.outbuildingRealPropertyIndicator,units:t.units.map(a=>({id:a.id,isAdu:a.isAdu}))}}function Mk(t){return tU(SH(t))}function Sx(t){return t.filter(a=>a.improvementType==="Dwelling")}function vx(t){const a=[];for(const s of t)if(Mk(s))for(const r of s.units)r.isAdu||a.push({structureId:s.id,unit:r});return a}function Nx(t){const a=[];for(const s of t)if(Mk(s))for(const r of s.units)r.isAdu&&a.push({structureId:s.id,unit:r});return a}const vH=["mls","public_records","inspection","ai_derived","user","propmix"];function Fk(){const[t,a]=o.useState(!1);return e.jsxs("div",{className:"px-6 pt-3 text-[10px]","data-testid":"uad36-source-badge-legend",children:[e.jsxs("button",{type:"button",onClick:()=>a(s=>!s),className:"flex items-center gap-1 text-slate-500 hover:text-slate-700 font-semibold","data-testid":"btn-toggle-uad36-source-legend","aria-expanded":t,children:[e.jsx("span",{"aria-hidden":!0,children:t?"▾":"▸"}),"What do the badges mean?"]}),t&&e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 px-2 py-1.5 bg-slate-50 border border-slate-200 rounded","data-testid":"uad36-source-legend-body",children:[vH.map(s=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qv,{source:s,confidence:"high",compact:!0}),e.jsxs("span",{className:"text-slate-600",children:[Ik[s]," — ",zv[s]]})]},s)),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qv,{source:"mls",confidence:"high",userEdited:!0,compact:!0}),e.jsx("span",{className:"text-slate-600",children:"EDITED — confirmed/changed by appraiser"})]})]})]})}function vo({section:t,field:a,getFieldMeta:s,suppressWhenFieldEdited:r}){const n=s?.(t,a);if(!n||r&&s?.(t,r)?.userEdited)return null;const i=n.rawValue===null||n.rawValue===void 0?"":String(n.rawValue),l=n.standardized&&!n.userEdited,c=n.needsStandardization&&!n.userEdited;return e.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-1",children:[e.jsx(qv,{source:n.source,confidence:n.confidence,confidenceScore:n.confidenceScore,userEdited:n.userEdited,compact:!0}),l&&e.jsx("span",{className:"inline-flex items-center gap-0.5 rounded-sm bg-emerald-50 px-1 py-px text-[9px] font-semibold uppercase tracking-wide text-emerald-700 ring-1 ring-inset ring-emerald-200",title:i?`Standardized to UAD 3.6 from "${i}"`:"Standardized to UAD 3.6","data-testid":`chip-standardized-${t}-${a}`,children:"✓ standardized"}),c&&e.jsx("span",{className:"inline-flex items-center gap-0.5 rounded-sm bg-amber-50 px-1 py-px text-[9px] font-semibold uppercase tracking-wide text-amber-700 ring-1 ring-inset ring-amber-300",title:i?`Couldn't standardize "${i}" to a UAD 3.6 value — pick one`:"Couldn't standardize — pick a value","data-testid":`chip-needs-standardization-${t}-${a}`,children:"⚠ pick a value"})]})}function _k({comp:t,compCount:a,onDuplicate:s,readOnly:r,testId:n}){return a<=1?null:e.jsxs(sr,{onValueChange:i=>{const l=parseInt(i,10);Number.isFinite(l)&&s(t,l)},disabled:r,children:[e.jsx(rr,{className:"h-6 w-6 p-0 border-0 bg-transparent shadow-none focus:ring-0 [&>svg]:hidden","data-testid":n,title:"Duplicate this comp into another column","aria-label":`Duplicate comp ${t}`,children:e.jsx(jr,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx(nr,{children:Array.from({length:a},(i,l)=>l+1).filter(i=>i!==t).map(i=>e.jsxs(vs,{value:String(i),children:["Copy to Comp ",i]},i))})]})}
15function Uk(t,a,s,r,n){if(s===r)return;const i=t?.[a]??{},l=`Comp${s}`;for(const[c,d]of Object.entries(i)){if(!c.startsWith(l))continue;const p=c.slice(l.length);/^\d/.test(p)||n(a,`Comp${r}${p}`,d?.value??null)}}function YT(t){return t==null||!Number.isFinite(t)?null:`$${Math.round(t).toLocaleString()}`}function Hv({label:t,isSubject:a=!1,address:s,figure:r,photoUrl:n,controls:i,testId:l}){const[c,d]=o.useState(!1),p=!!n&&!c,u=(s??"").trim(),m=u?u.split(",")[0]:t;return e.jsxs("div",{className:"group relative rounded-lg border border-slate-200 bg-white text-left font-normal","data-testid":l,children:[e.jsxs("div",{className:"relative aspect-[4/3] overflow-hidden rounded-t-lg",children:[p?e.jsx("img",{src:n,alt:m,className:"absolute inset-0 h-full w-full object-cover",onError:()=>d(!0),loading:"lazy"}):e.jsx("div",{className:"absolute inset-0 flex h-full w-full items-center justify-center bg-slate-200",children:e.jsx(Wh,{className:"h-7 w-7 text-slate-400"})}),p&&e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 via-trans
15parent to-black/5"}),e.jsxs("div",{className:"absolute left-1.5 right-1.5 top-1.5 flex items-start justify-between",children:[e.jsx("span",{className:Q("rounded px-1.5 py-0.5 text-[9px] font-bold uppercase text-white shadow-sm",a?"bg-amber-500":"bg-[#0f2942]"),children:t}),i]}),r?e.jsx("div",{className:"absolute bottom-0 left-0 right-0 flex items-end px-2 pb-1.5",children:e.jsx("span",{className:"inline-block rounded bg-black/55 px-1.5 py-0.5 backdrop-blur-sm",children:e.jsx("span",{className:"text-[13px] font-bold leading-tight text-white",children:r})})}):null]}),e.jsx("div",{className:"flex w-full items-center justify-center gap-1.5 rounded-b-lg border-t border-slate-200 bg-slate-50 px-2 py-1 text-slate-700",children:e.jsx("span",{className:"truncate text-[13px] font-bold",children:m})})]})}function NH({getValue:t,setValue:a,setValues:s,disabled:r,testId:n,hint:i,allowUnknown:l=!0,resolvedDisplay:c=!1}){const[d,p]=o.useState(!c),u=N=>{if(s){s(N);return}Object.entries(N).forEach(([x,y])=>a(x,y))},m=t("ContractDateUnknownIndicator"),h=l&&(m===!0||m==="true"),f=t("SalesContractDate"),v=f==null?"":String(f),S=(()=>{const N=/^(\d{4})-(\d{2})-(\d{2})$/.exec(v);return N?`${N[2]}/${N[3]}/${N[1]}`:v})();return c&&!d?e.jsx("div",{className:"flex min-h-[18px] min-w-0 cursor-pointer items-center text-left",role:"button",tabIndex:r?-1:0,"aria-label":`Edit ${n??"Contract Date"}`,"data-testid":n,onClick:()=>{r||p(!0)},onKeyDown:N=>{N.key!=="Enter"&&N.key!==" "||(N.preventDefault(),r||p(!0))},children:e.jsx("span",{className:Ou,children:h?"Unknown":S})}):e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2","data-testid":n?`${n}-layout`:void 0,children:[h?null:e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(vN,{value:v,disabled:r,onChange:N=>{u({SalesContractDate:N===""?null:N,...l?{ContractDateUnknownIndicator:N===""?null:!1}:{}})},testId:n,className:"min-w-0",inputClassName:"h-8 min-w-0 text-xs",pickerButtonClassName:"h-8 w-8"})}),l?e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx(Pa,{id:n?`${n}-unknown`:void 0,checked:h,disabled:r,onCheckedChange:N=>{const x=N===!0;u({ContractDateUnknownIndicator:x,...x?{SalesContractDate:null}:{}})},"data-testid":n?`${n}-unknown`:void 0}),e.jsx(Ja,{htmlFor:n?`${n}-unknown`:void 0,className:"cursor-pointer whitespace-nowrap text-[10px] text-muted-foreground",children:"Unknown"})]}):null]}),!h&&!v&&i?e.jsx("div",{className:"placeholder-hint text-[10px]","data-testid":n?`${n}-hint`:void 0,children:i}):null]})}function AH({getValue:t,setValue:a,setValues:s,onTransactionChange:r,disabled:n,testId:i}){const[l,c]=o.useState(!1),[d,p]=o.useState(""),[u,m]=o.useState("");u===""||`${u.replace(/^-?\d+/,E=>E.replace(/\B(?=(\d{3})+(?!\d))/g,","))}`;const h=t("SalesConcessionIndicator"),f=h===!0||h==="true",v=h===!1||h==="false",S=t("SalesConcessionAmountKnownIndicator"),N=S===!0||S==="true",x=t("TotalSalesConcessionAmount"),y=(()=>{if(x==null)return"";const E=String(x).trim();if(!E||/^(undefined|null|nan)$/i.test(E))return"";const R=Number(E);return Number.isFinite(R)&&R>=0?E:""})(),b=v?"None":f?N?"Amount":"Unknown":"",j=DN("SalesConcessions",{role:"comparable",get:t,applicabilityAlreadyResolved:!0}).text,T=()=>{p(b),m(y),c(!0)},O=()=>{if(d==="Amount"&&u.trim()){const R=Number(u.trim());if(!Number.isFinite(R)||R<0)return}const E=d==="Amount"?u.trim():null;r?r(d===""?"Clear":d,E):s?s(d==="None"?{SalesConcessionIndicator:!1,SalesConcessionAmountKnownIndicator:null,TotalSalesConcessionAmount:null}:d==="Unknown"?{SalesConcessionIndicator:!0,SalesConcessionAmountKnownIndicator:!1,TotalSalesConcessionAmount:null}:d==="Amount"?{SalesConcessionIndicator:!0,SalesConcessionAmountKnownIndicator:!0,TotalSalesConcessionAmount:E}:{SalesConcessionIndicator:null,SalesConcessionAmountKnownIndicator:null,TotalSalesConcessionAmount:null}):(a("SalesConcessionIndicator",d==="None"?!1:d===""?null:!0),a("SalesConcessionAmountKnownIndicator",d==="Amount"?!0:d==="Unknown"?!1:null),a("TotalSalesConcessionAmount",d==="Amount"?E:null)),c(!1)};return e.jsxs(xn,{open:l,onOpenChange:c,modal:!0,children:[e.jsx(bn,{asChild:!0,children:e.jsx("button",{type:"button",disabled:n,onClick:T,className:Q("min-h-8 w-full rounded px-2 py-1 text-left transition-colors",n?"text-slate-400":"text-slate-700 hover:bg-blue-50 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-blue-500",Ou),"aria-label":"Edit Sales Concessions","data-testid":i,children:j})}),l&&typeof document<"u"&&Wp.createPortal(e.jsx("button",{type:"button","aria-label":"Close Sales Concessions editor",className:"fixed inset-0 z-[99] cursor-default bg-slate-950/45 backdrop-blur-[1px]","data-testid":i?`${i}-overlay`:void 0,onClick:()=>c(!1)}),document.body),e.jsxs(yn,{role:"dialog","aria-modal":"true",align:"start",side:"right",sideOffset:8,collisionPadding:8,className:"z-[100] w-[min(28rem,calc(100vw-1rem))] border-slate-200 bg-white p-0 shadow-xl","data-testid":i?`${i}-editor`:void 0,children:[e.jsxs("div",{className:"border-b border-slate-200 px-3 py-3",children:[e.jsx("h2",{className:"text-sm font-semibold text-slate-800",children:"Sales Concessions"}),e.jsx("p",{className:"mt-1 text-[11px] text-slate-500",children:"Choose one value, then save or cancel your changes."})]}),e.jsxs("div",{className:"space-y-3 p-3",children:[e.jsx("div",{className:"grid grid-cols-3 overflow-hidden rounded-md border border-slate-200 bg-white",role:"radiogroup","aria-label":"Sales Concessions mode",children:["None","Unknown","Amount"].map(E=>e.jsx("button",{type:"button",role:"radio","aria-label":E,"aria-checked":d===E,onClick:()=>p(E),className:Q("h-9 border-r border-slate-200 text-[11px] font-medium last:border-r-0",d===E?"bg-vi
15olet-600 text-white":"text-slate-600 hover:bg-slate-50"),"data-testid":i?`${i}-mode-${E}`:void 0,children:E},E))}),d==="Amount"&&e.jsx(ze,{type:"number",inputMode:"decimal",value:u,onChange:E=>{const R=E.target.value.replace(/[$,]/g,"").trim();/^-?\d*(?:\.\d*)?$/.test(R)&&m(R)},placeholder:"Enter concession amount","aria-label":"Sales Concessions amount",className:"h-8 text-xs placeholder-hint","data-testid":i?`${i}-amount`:void 0})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t border-slate-200 bg-slate-50 px-3 py-2",children:[e.jsx(De,{type:"button",variant:"outline",size:"sm",onClick:()=>c(!1),"data-testid":i?`${i}-cancel`:void 0,children:"Cancel"}),e.jsx(De,{type:"button",size:"sm",onClick:O,"data-testid":i?`${i}-save`:void 0,children:"Save"})]})]})]})}const Gb=[{rowId:"RenewableEnergyComponentType",label:"Renewable Energy Component",key:"renewableComponents"},{rowId:"GreenCertificationName",label:"Building Certification",key:"greenCertifications"},{rowId:"EfficiencyRatingName",label:"Efficiency Rating",key:"efficiencyRatings"}];function IP({entries:t,disabled:a,onApply:s,onClose:r,placement:n="below",dimBackground:i=!1}){const l=o.useRef(null),c=new Set(t.filter(f=>Gb.some(v=>v.rowId===f.rowId)&&f.relevant!==!1).map(f=>f.rowId)),[d,p]=o.useState(c),u=o.useRef(c),m=Gb.map(f=>c.has(f.rowId)).join(",");o.useEffect(()=>{const f=new Set(c);u.current=f,p(f)},[m]);const h=f=>{const v=t.filter(N=>!Gb.some(x=>x.rowId===N.rowId)),S=new Map(t.map(N=>[N.rowId,N]));s([...v,...Gb.map(N=>({...S.get(N.rowId)??{rowId:N.rowId,kind:"optional"},rowId:N.rowId,kind:"optional",relevant:f.has(N.rowId)}))])};return o.useEffect(()=>{if(!r)return;const f=v=>{l.current?.contains(v.target)||r()};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},[r]),e.jsxs(e.Fragment,{children:[i&&e.jsx("button",{type:"button",className:"fixed inset-0 z-50 cursor-default bg-white/50","aria-label":"Close Energy row selector","data-testid":"energy-picker-grid-scrim",onMouseDown:r}),e.jsxs("div",{ref:l,className:Q("absolute left-0 z-[60] w-80 rounded-md bg-white text-left text-xs font-normal normal-case tracking-normal shadow-lg ring-1 ring-slate-200",n==="above"?"bottom-full mb-1":"top-full mt-1"),"data-testid":"energy-row-picker",children:[e.jsx("div",{className:"px-3 pt-2 pb-1",children:e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-wide text-slate-400",children:"Energy"})}),e.jsx("div",{className:"max-h-72 overflow-y-auto py-1",children:Gb.map(f=>{const v=d.has(f.rowId);return e.jsxs("label",{className:"flex w-full cursor-pointer select-none items-center gap-2 px-3 py-1.5 text-xs text-slate-700 hover:bg-blue-50",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 shrink-0 cursor-pointer rounded border-slate-300 accent-blue-600",checked:v,disabled:a,onChange:S=>{const N=new Set(u.current);S.target.checked?N.add(f.rowId):N.delete(f.rowId),u.current=N,p(N),h(N)}}),e.jsx("span",{className:"truncate font-medium",children:f.label})]},f.rowId)})})]})]})}function jH({label:t,collectionKey:a,items:s,onChange:r,disabled:n,inspectSection:i,inspectPrefix:l,onMarkIrrelevant:c,scope:d="subject",compact:p=!1,collectionSource:u}){const{inspecting:m}=fc(),[h,f]=o.useState(!1),[v,S]=o.useState(s),N=o.useRef(s),x=o.useRef(null),[y,b]=o.useState({left:8,top:8,maxHeight:650});o.useEffect(()=>{h||(N.current=s,S(s))},[h,s]);const j=p&&h?v:s,T=ae=>{const D=p&&h?N.current:s,_=ae(D).slice(0,_A);N.current=_,S(_),r(_)},O=()=>{const ae=globalThis.crypto?.randomUUID?.()??`${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;T(D=>[...D,{id:`${a}-${ae}`,userEdited:!0}])},E=ae=>GU(a,ae,d),R=ae=>({RenewableEnergyComponentType:"Component type",RenewableEnergyComponentTypeOtherDescription:"Other description",RenewableEnergyComponentOwnershipType:"Ownership",RenewableEnergyComponentFinancedIndicator:"Financed",GreenCertificationName:"Certification",GreenCertificationAssociationName:"Association",GreenCertificationLevelName:"Level",GreenCertificationLevelAwardedYear:"Awarded year",EfficiencyRatingName:"Rating",EfficiencyRatingOrganizationName:"Organization",EfficiencyRatingScoreValue:"Score"})[ae]??ae.replace(/([A-Z])/g," $1").trim(),G=(ae,D)=>{if(ae.endsWith("Indicator")){if(D===!0||D==="true")return!0;
15if(D===!1||D==="false")return!1;if(D==null||D==="")return}return D===""?void 0:D},U=(ae,D,_)=>T($=>$.map(z=>z.id===ae?{...z,[D]:G(D,_),userEdited:!0,fieldSources:{...z.fieldSources,[D]:"user"}}:z)),C=()=>{if(n)return;N.current=s,S(s);const ae=x.current;if(ae){const D=ae.getBoundingClientRect(),_=Math.min(704,window.innerWidth-16),$=Math.min(650,window.innerHeight-16),z=8,V=D.right+z+_<=window.innerWidth?D.right+z:Math.max(8,D.left-_-z),le=Math.max(8,Math.min(D.top,window.innerHeight-$-8));b({left:V,top:le,maxHeight:Math.max(0,window.innerHeight-le-8)})}f(!0)},F=e.jsxs("div",{className:"space-y-1 rounded border border-slate-200 p-2","data-testid":`energy-editor-${l}-${a}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Ja,{className:"text-xs font-semibold",children:t}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-1 text-xs",disabled:n||j.length>=_A,onClick:O,children:"+ Add"}),c&&e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-1 text-xs text-muted-foreground",disabled:n,onClick:c,"aria-label":`Mark ${t} row irrelevant`,title:"Mark row irrelevant",children:"X"})]})]}),j.length===0&&e.jsx("div",{className:"py-1 text-xs text-slate-500",children:"None"}),j.map((ae,D)=>e.jsxs("div",{className:"space-y-1 border-t pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[e.jsxs("span",{children:["Item ",D+1,ae.source&&e.jsx(qv,{source:ae.source,confidence:"high",userEdited:ae.userEdited,compact:!0})]}),e.jsxs("span",{className:"flex gap-1",children:[e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"h-5 px-1",disabled:n||D===0,onClick:()=>T(_=>{const $=[..._];return[$[D-1],$[D]]=[$[D],$[D-1]],$}),children:"↑"}),e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"h-5 px-1",disabled:n||D===j.length-1,onClick:()=>T(_=>{const $=[..._];return[$[D+1],$[D]]=[$[D],$[D+1]],$}),children:"↓"}),e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"h-5 px-1",disabled:n,onClick:()=>T(_=>_.filter($=>$.id!==ae.id)),children:"Remove"})]})]}),E(ae).map(_=>{const $=ae[_],z=`${l?`${l}.`:""}${a}.${tb(ae.id)}.${_}`,V=Pr(_)??[],le=V.length>0;return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ja,{className:"w-24 shrink-0 text-[10px]",children:_.replace(/([A-Z])/g," $1").trim()}),le?e.jsxs(sr,{disabled:n,value:String($??""),onValueChange:W=>U(ae.id,_,W),children:[e.jsx(rr,{className:"h-7 text-xs","data-field-name":z,children:e.jsx(or,{placeholder:"Select…"})}),e.jsx(nr,{children:V.map(W=>e.jsx(vs,{value:W,children:Dc(_,W)},W))})]}):e.jsx(ze,{className:"h-7 text-xs",disabled:n,type:_.endsWith("Indicator")?"checkbox":"text",checked:_.endsWith("Indicator")?$===!0:void 0,value:_.endsWith("Indicator")?void 0:String($??""),onChange:W=>U(ae.id,_,_.endsWith("Indicator")?W.target.checked:W.target.value),"data-field-name":z}),m&&e.jsx(Fs,{section:i,fieldName:z})]},_)})]},ae.id))]});if(!p)return F;const A=s.map(ae=>{if(a==="renewableComponents"){const _=String(ae.RenewableEnergyComponentType??"").trim();return _?Dc("RenewableEnergyComponentType",_):""}return(a==="greenCertifications"?["GreenCertificationName","GreenCertificationLevelName"]:["EfficiencyRatingName","EfficiencyRatingScoreValue"]).map(_=>String(ae[_]??"").trim()).filter(Boolean).join(" | ")}).filter(Boolean),M=s.flatMap(ae=>{const D=E(ae).map(_=>ae.fieldSources?.[_]).filter(_=>!!_);return D.length>0?D.map(_=>({source:_,userEdited:ae.userEdited===!0||_==="user"})):ae.source?[{source:ae.source,userEdited:ae.userEdited===!0}]:[]}),B=Array.from(new Map((M.length>0?M:u?[{source:u,userEdited:!1}]:[]).map(ae=>[`${ae.source}:${ae.userEdited}`,ae])).values()),oe=s.some(ae=>!YU(a,ae)&&E(ae).some(D=>LE(D,ae[D])));return e.jsxs(xi,{open:h,onOpenChange:ae=>f(n?!1:ae),children:[e.jsxs("div",{ref:x,role:n?void 0:"button",tabIndex:n?void 0:0,className:Q("relative min-h-[18px] w-full rounded px-0 py-0 text-left text-[11px] leading-4 text-slate-700 transition-colors hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-inset",B.length>0&&"pl-4"),onClick:ae=>{n||ae.target.closest('[data-testid^="datapoint-inspect-pill-"]')||C()},onKeyDown:ae=>{n||ae.key!=="Enter"&&ae.key!==" "||(ae.preventDefault(),C())},"aria-label":`Edit ${t}`,"data-testid":`energy-summary-${l}-${a}`,children:[B.length>0&&e.jsx("span",{className:"absolute left-1 top-1.5 flex items-center gap-1",children:B.map(({source:ae,userEdited:D})=>e.jsx(Ji,{source:ae,userEdited:D,testId:`source-dot-energy-${l||"subject"}-${a}-${ae}${D?"-edited":""}`},`${ae}:${D}`))}),oe&&e.jsx("span",{className:"absolute right-1 top-1.5 h-1.5 w-1.5 rounded-full bg-rose-500",title:"Missing required Energy data","data-testid":`missing-dot-energy-${l||"subject"}-${a}`}),A.length>0?a==="renewableComponents"?e.jsx("span",{children:A.join(" | ")}):e.jsx("span",{className:"block space-y-1",children:A.map((ae,D)=>e.jsx("span",{className:"block",children:ae},`${D}-${ae}`))}):e.jsx("span",{children:"None"}),m&&e.jsx(Fs,{section:i,fieldName:`${l?`${l}.`:""}${a}`})]}),e.jsxs(bi,{className:"flex max-w-none translate-x-0 translate-y-0 flex-col gap-0 overflow-hidden border-slate-200 bg-white p-0 shadow-xl",onOpenAutoFocus:ae=>ae.preventDefault(),style:{left:y.left,top:y.top,maxHeight:y.maxHeight,width:"min(44rem, calc(100vw - 1rem))"},overlayClassName:"bg-black/50","data-testid":`energy-dialog-${l||"subject"}-${a}`,children:[e.jsxs($i,{className:"shrink-0 border-b border-slate-200 px-3 py-3",children:[e.jsxs(si,{className:"text-sm font-semibold text-slate-800",children:[d==="subject"?"Subject":"Comparable"," ",t]}),e.jsxs(pl,{className:"text-[11px] text-slate-500",children:["Add or edit ",t.toLowerCase()," entries for this grid cell."]})]}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain bg-white",children:[j.map((ae,D)=>{const _=E(ae);return e.jsx("div",{className:"border-b border-slate-200 px-3 py-2","data-testid":`energy-dialog-item-${ae.id}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-4 shrink-0 pt-5 text-[10px] font-semibold tabular-nums text-slate-500",children:D+1}),e.jsx("div",{className:"grid min-w-0 flex-1 grid-cols-1 gap-1.5 md:flex md:flex-nowrap md:items-end md:gap-2",children:_.map($=>{const z=ae[$],V=`${l?`${l}.`:""}${a}.${tb(ae.id)}.${$}`,le=Pr($)??[],W=le.length>0,me=LE($,z);return e.jsxs("div",{className:"min-w-[8rem] flex-1 space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(Ja,{className:"truncate text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:[R($)," ",e.jsx(Gp,{})]}),m&&e.jsx(Fs,{section:i,fieldName:V})]}),$.endsWith("Indicator")?e.jsx("div",{"aria-invalid":me||void 0,"data-field-name":V,children:e.jsx(cy,{value:z===!0||z==="true"?!0:z===!1||z==="false"?!1:void 0,onChange:Z=>U(ae.id,$,Z),testId:`energy-toggle-${ae.id}-${$}`,required:!0,fieldName:V,section:i,activeClassName:"bg-slate-700 text-white"})}):W?e.jsxs(sr,{disabled:n,value:String(z??""),onValueChange:Z=>U(ae.id,$,Z),children:[e.jsx(rr,{"aria-invalid":me||void 0,className:Q("h-8 rounded-md border-slate-200 bg-white px-2 text-[11px]",me&&"border-red-400 bg-red-50/40 focu
15s:ring-red-400"),"data-field-name":V,children:e.jsx(or,{placeholder:"Select…"})}),e.jsx(nr,{children:le.map(Z=>e.jsx(vs,{value:Z,children:Dc($,Z)},Z))})]}):e.jsx(ze,{"aria-invalid":me||void 0,className:Q("h-8 rounded-md border-slate-200 bg-white px-2 text-[11px]",me&&"border-red-400 bg-red-50/40 focus-visible:ring-red-400"),disabled:n,value:String(z??""),onChange:Z=>U(ae.id,$,Z.target.value),"data-field-name":V})]},$)})}),e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"mt-4 h-6 w-6 shrink-0 rounded-sm p-0 text-slate-400 hover:bg-rose-50 hover:text-rose-600",disabled:n,onClick:()=>T($=>$.filter(z=>z.id!==ae.id)),"aria-label":`Remove ${t} item ${D+1}`,children:e.jsx(Ci,{className:"h-3 w-3"})})]})},ae.id)}),e.jsx("div",{className:"px-3 py-2",children:e.jsxs(De,{type:"button",variant:"outline",size:"sm",className:"h-8 w-full justify-center rounded-md border-dashed border-slate-400 bg-white text-[11px] font-medium text-slate-700 hover:bg-slate-50",disabled:n||j.length>=_A,onClick:O,children:[e.jsx(un,{className:"mr-2 h-3.5 w-3.5"}),"Add ",t.toLowerCase()]})})]}),e.jsx(eb,{className:"shrink-0 border-t border-slate-200 px-3 py-2.5",children:e.jsx(De,{type:"button",className:"h-8 rounded-md bg-slate-700 px-4 text-xs hover:bg-slate-800",onClick:()=>f(!1),children:"Done"})})]})]})}function CP(t){const a=/^(\d+)(?:\.(\d+))?$/.exec(t.trim());return a?{full:parseInt(a[1],10),half:a[2]?parseInt(a[2],10):0}:null}function RP(t,a){const s=String(t??"").trim();if(!s||!s.includes("|"))return null;const r=s.split("|").map(m=>m.trim());if(r.length<3)return null;const n=/^\d+$/.test(r[1])?parseInt(r[1],10):null,i=CP(r[2]);if(n===null&&!i)return null;let l=0,c=0,d=0,p=!1;const u=String(a??"").trim();if(u){const m=/(\d+)\s*br/i.exec(u),h=/(\d+(?:\.\d+)?)\s*ba/i.exec(u);if(m&&(l=parseInt(m[1],10),p=!0),h){const f=CP(h[1]);f&&(c=f.full,d=f.half,p=!0)}}return{bedrooms:n===null?null:n+l,fullBaths:i?i.full+c:null,halfBaths:i?i.half+d:null,includesBelowGrade:p}}function nd(t,a){if(!Number.isFinite(t))return 0;const s=Number.isFinite(a)?a:0;return s<=0||Math.abs(t)>s?t:0}function TH(t,a){return!Number.isFinite(t)||t===0||!Number.isFinite(a)||a===0?0:Math.round(t>0?a:-a)}function NS(t,a){if(t==null)return null;const s=String(t).match(new RegExp(`${a}\\s*([1-6])`,"i"));return s?Number(s[1]):null}function AS(t){const a=t.qualityCondition?.value;return{quality:NS(t.quality?.value,"Q")??NS(a,"Q"),condition:NS(t.condition?.value,"C")??NS(a,"C")}}function IH(t){const{subject:a,comp:s,salePrice:r,qualityRate:n,conditionRate:i}=t;if(!Number.isFinite(n)||n<0||!Number.isFinite(i)||i<0)return null;const l=(p,u,m,h)=>{if(p==null||u==null)return null;if(m===0)return 0;if(h==="percent"&&(!Number.isFinite(r)||r<=0))return null;const f=u-p,v=Number.isFinite(t.threshold)&&t.threshold>0?t.threshold:0,S=Math.abs(f)>v?f:0,N=h==="percent"?r/100:1;return S*m*N},c=l(a.quality,s.quality,n,t.qualityBasis),d=l(a.condition,s.condition,i,t.conditionBasis);return c==null&&d==null?null:Math.round((c??0)+(d??0))}function CH(t,a){const s=t==null?"":String(t).trim().toLowerCase(),r=a==null?"":String(a).trim().toLowerCase();return s===""||r===""?!1:s!==r}const RH=16;function EP(t){if(typeof t!="string")return null;const a=t.trim();return a===""||a.length>RH||!/^-?[\d,]*\.?\d*$/.test(a)?null:a}function wP(t,a,s){const r={rates:{},thresholds:{},basis:{}};if(!t||typeof t!="object"||Array.isArray(t))return r;const n=t,i=n.rates;if(i&&typeof i=="object"&&!Array.isArray(i))for(const[p,u]of Object.entries(i)){if(a&&!a.has(p))continue;const m=EP(u);m!==null&&(r.rates[p]=m)}const l=n.thresholds;if(l&&typeof l=="object"&&!Array.isArray(l))for(const[p,u]of Object.entries(l)){if(s&&!s.has(p))continue;const m=EP(u);m!==null&&(r.thresholds[p]=m)}const c=n.basis;if(c&&typeof c=="object"&&!Array.isArray(c))for(const[p,u]of Object.entries(c))s&&!s.has(p)||(u==="perUnit"||u==="flat")&&(r.basis[p]=u);const d=n.qualityConditionBasis;if(d&&typeof d=="object"&&!Array.isArray(d)){const p=d;r.qualityConditionBasis={quality:p.quality==="dollars"?"dollars":"percent",condition:p.condition==="dollars"?"dollars":"percent"}}return r}function PP(t){return Object.keys(t.rates).length===0&&Object.keys(t.thresholds).length===0&&Object.keys(t.basis).length===0&&!t.qualityConditionBasis}const EH=CI;function mp(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}function gb(t,a){const s=EH[t]??Pr(t)??[],r=mp(a);if(!r)return"";for(const n of s)if(mp(n)===r)return n;return""}const wH={conv:"Traditional",conventional:"Traditional",traditional:"Traditional",col:"Colonial",colonial:"Colonial",ranch:"Ranch",rmblr:"Rambler",rambler:"Rambler",raisedranch:"RaisedRanch",contemp:"Contemporary",contemporary:"Contemporary",modern:"Modern",cape:"CapeCod",capecod:"CapeCod",vic:"Victorian",victorian:"Victorian",tudor:"Tudor",craftsman:"Craftsman",bung:"Bungalow",bungalow:"Bungalow",cottage:"Cottage",farm:"Farmhouse",farmhouse:"Farmhouse",georgian:"Georgian",med:"Mediterranean",mediterranean:"Mediterranean",spanish:"Spanish",southwest:"Southwest",log:"Log",chalet:"Chalet",aframe:"AFrame",barn:"Barn",bilevel:"BiLevel",split:"SplitLevel",splitlevel:"SplitLevel",splitfoyer:"SplitFoyerOrEntry",splitentry:"SplitFoyerOrEntry",earthberm:"EarthBerm",dome:"GeodesicDome",geodesicdome:"GeodesicDome",neoeclectic:"NeoEclectic",stilt:"Stilt",other:"Other"};function gg(t){let a=String(t??"").trim();if(!a)return"";if(a.includes(";")){const r=a.split(";");a=r[r.length-1].trim()}if(/^(DT|SD|AT|RT|MH|RW)\d/i.test(a)&&!/[a-z]/i.test(a.replace(/^(DT|SD|AT|RT|MH|RW)[\d.]*/i,""))||!a)return"";const s=wH[mp(a)];return s||gb("ArchitecturalDesignCategoryType",a)}const OP={res:"Residential",residential:"Residential",wtr:"",water:"",mtn:"Mountain",mountain:"Mountain",mountains:"Mountain",woods:"Woods",wooded:"Woods",trees:"Woods",golf:"GolfCourse",golfcourse:"GolfCourse",cmrcl:"Commercial",commercial:"Commercial",ind:"Industrial",industrial:"Industrial",city:"CityStreet",citystreet:"CityStreet",street:"CityStreet",park:"Park",lake:"Lake",river:"River",ocean:"Ocean",pond:"Pond",creek:"Creek",bay:"Bay",canal:"Canal",valley:"Valley",pastoral:"Pastoral",skyline:"Skyline",parkinglot:"ParkingLot",other:"Other"};function Vk(t){return/^[NBA];/i.test(t)?t.slice(2).trim():t}const GT="|";function Wv(t,a){const s=[];for(const r of t.split(GT)){const n=a(r.trim());n&&!s.includes(n)&&s.push(n)}return s.join(GT)}function PH(t){let a=t.trim();if(!a)return"";if(a=Vk(a),a.includes(";")){const s=a.split(";");a=s[s.length-1].trim()}return a?Object.prototype.hasOwnProperty.call(OP,mp(a))?OP[mp(a)]:gb("ViewType",a):""}function tC(t){const a=String(t??"").trim();return a?Wv(a,PH):""}function OH(t){let a=t.trim();if(!a)return"";if(a=Vk(a),a.includes(";")){const r=a.split(";");a=r[r.length-1].trim()}if(!a)return"";const s=mp(a);return s==="urban"||s==="suburban"||s==="suburb"||s==="rural"?"":gb("SiteInfluenceType",a)}function aC(t){const a=String(t??"").trim();return a?Wv(a,OH):""}const LH={fwa:"ForcedWarmAir",forcedwarmair:"ForcedWarmAir",forcedair:"ForcedWarmAir",forced:"ForcedWarmAir",fa:"ForcedWarmAir",centralheat:"ForcedWarmAir",central:"ForcedWarmAir",heatpump:"ForcedWarmAir",hp:"ForcedWarmAir",bb:"Baseboard",baseboard:"Baseboard",hwbb:"Baseboard",electricbaseboard:"Baseboard",rad:"Radiant",radiant:"Radiant",radiator:"Radiators",radiators:"Radiators",minisplit:"MiniSplit",ductless:"MiniSplit",gravity:"GravityAir",gravityair:"GravityAir",fireplace:"Fireplace",stove:"Stove",woodstove:"Stove",passivesolar:"PassiveSolar",solar:"PassiveSolar",none:"None",other:"Other"},DH={cac:"Centralized",centralac:"Centralized",centralair:"Centralized",central:"Centralized",centralized:"Centralized",ca:"Centralized",ac:"Centralized",window:"Individual",windowunit:"Individual",wall:"Individual",wallunit:"Individual",individual:"Individual",ductless:"Individual",minisplit:"Individual",none:"None",other:"Other"};function kH(t){const a=String(t??"").trim();if(!a)return"";const s=LH[mp(a)];return s!==void 0?s:gb("HeatingSystemType",a)}function MH(t){const a=String(t??"").trim();if(!a)return"";const s=DH[mp(a)];return s!==void 0?s:gb("CoolingSystemType",a)}const FH=";";function sC(t,a){const s=Wv(String(t??""),kH),r=Wv(String(a??""),MH);return!s&&!r?"":`${s}${FH}${r}`}function _H(t){const a=String(t??"").trim();if(!a)return"";const s=a.split(";");return sC(s[0],s[1])}const UH={ga:"Garage",gd:"Garage",gbi:"Garage",garage:"Garage",attached:"Garage",detached:"Garage",builtin:"Garage",parkinggarage:"ParkingGarage",cp:"Carport",carport:"Carport",commoncarport:"CommonCarport",dw:"Driveway",driveway:"Driveway",shareddriveway:"SharedDriveway",openlot:"OpenLot",open:"OpenLot",other:"Other"};function LP(t){if(!t)return"";const a=UH[mp(t)];return a||gb("CarStorageType",t)}function VH(t){if(!t)return"";if(mp(t)==="none"||mp(t)==="0")return"None";const a=t.match(/^(\d+)\s*(.*)$/);if(a){const r=parseInt(a[1],10);if(r===0)return"None";const n=LP(a[2]);return n?`${r} ${n}`:`${r}`}const s=LP(t);return s?`1 ${s}`:""}function rC(t){const a=String(t??"").trim();if(!a)return"";const s=a.split(";").map(n=>VH(n.trim())).filter(n=>n!==""),r=s.filter(n=>n!=="None");return r.length>0?r.join("; "):s.length>0?"None":""}function $H(t){if(t==null)return NaN;if(typeof t=="number")return t;const a=t.trim();if(a==="")return NaN;
15if(/^none$/i.test(a)||/no\s+(garage|parking)/i.test(a))return 0;let s=0,r=!1;for(const n of a.split(";")){const i=n.trim().match(/^(\d+)/);i&&(s+=parseInt(i[1],10),r=!0)}return r?s:NaN}function nC(t){const a=String(t??"").trim();if(!a)return"";const s=a.match(/^(.*?)(?:,\s*(wo|wu|in|ex))\s*$/i);return s?s[1].trim():a}const BH=" / ";function jS(t,a){return t.split(GT).filter(s=>s.length>0).map(s=>Hs(a,s)).join(", ")}function zH(t,a){const s=a==null?"":String(a);switch(t){case"design":{const r=gg(s);return r?Hs("ArchitecturalDesignCategoryType",r):""}case"view":{const r=tC(s);return r?jS(r,"ViewType"):""}case"location":{const r=aC(s);return r?jS(r,"SiteInfluenceType"):""}case"heatingCooling":{const r=_H(s);if(!r)return"";const[n,i]=r.split(";"),l=[];return n&&n.length>0&&l.push(jS(n,"HeatingSystemType")),i&&i.length>0&&l.push(jS(i,"CoolingSystemType")),l.join(BH)}case"garageCarport":{const r=rC(s);return r?r==="None"?"None":r.split("; ").map(n=>{const i=n.match(/^(\d+)\s+(.*)$/);return i?`${i[1]} ${Hs("CarStorageType",i[2])}`:n}).join("; "):""}case"basement":return nC(s);default:return null}}const jg=[{name:"mlsNumber",label:"MLS Number",key:"mlsNumber",category:"sale_financing",uadFormat:"text",photoCardOnly:!0},{name:"salePrice",label:"Sale Price",key:"price",category:"sale_financing",uadFormat:"currency",photoCardOnly:!0},{name:"salePricePerGLA",label:"Sale Price/Gross Liv. Area",key:"salePricePerGLA",category:"sale_financing",uadFormat:"currency",photoCardOnly:!0},{name:"dataSource",label:"Data Source",key:"dataSource",category:"sale_financing",uadFormat:"DataSourceType | Identifier",photoCardOnly:!0},{name:"daysOnMarket",label:"Days on Market",key:"dom",mlsKey:"daysOnMarket",category:"sale_financing",uadFormat:"number",photoCardOnly:!0},{name:"saleType",label:"Transfer Terms",key:"saleType",category:"sale_financing",uadFormat:"SaleType enum",photoCardOnly:!0},{name:"financing",label:"Financing Type",key:"financing",category:"sale_financing",uadFormat:"MortgageType enum or Cash",photoCardOnly:!0},{name:"concessions",label:"Sales Concessions",key:"concessions",category:"sale_financing",uadFormat:"currency or None",photoCardOnly:!0},{name:"quality",label:"Quality",key:"quality",category:"design",uadFormat:"Q1-Q6",photoCardOnly:!0},{name:"condition",label:"Condition",key:"condition",category:"design",uadFormat:"C1-C6",photoCardOnly:!0},{name:"listPrice",label:"List Price",key:"listPrice",mlsKey:"listPrice",category:"sale_financing",uadFormat:"currency",referenceOnly:!0},{name:"listingStatus",label:"Listing Status",key:"listingStatus",category:"sale_financing",uadFormat:"ListingStatusType",referenceOnly:!0},{name:"neighborhoodName",label:"Neighborhood Name",key:"neighborhoodName",category:"location",uadFormat:"text",referenceOnly:!0},{name:"proximity",label:"Proximity to Subject",key:"proximity",category:"location",uadFormat:"[#.##] miles [dir]",referenceOnly:!0},{name:"priorSaleDate",label:"Prior Sale Date",key:"priorSaleDate",category:"sale_financing",uadFormat:"date",referenceOnly:!0},{name:"priorSalePrice",label:"Prior Sale Price",key:"priorSalePrice",category:"sale_financing",uadFormat:"currency",referenceOnly:!0},{name:"dateOfSale",label:"Date of Sale / Contract",key:"saleDate",mlsKey:"saleDate",category:"sale_financing",uadFormat:"s[mm/yy];c[mm/yy]"},{name:"financingConcessions",label:"Financing/Concessions",key:"financingConcessions",category:"sale_financing",uadFormat:"text"},{name:"leaseholdFeeSimple",label:"Leasehold/Fee Simple",key:"leaseholdFeeSimple",category:"location",uadFormat:"Fee Simple|Leasehold"},{name:"location",label:"Site Influence (Location)",key:"location",category:"location",uadFormat:"SiteInfluenceType"},{name:"site",label:"Site",key:"lotSize",mlsKey:"lotSize",prKey:"lotSize",category:"site",uadFormat:"[#] sf or ac"},{name:"view",label:"View",key:"view",category:"site",uadFormat:"[N|B|A];[Type]"},{name:"design",label:"Design (Style)",key:"style",mlsKey:"style",prKey:"style",category:"design",uadFormat:"[DT|SD|Row][#];[Style]"},{name:"constructionMethod",label:"Construction Method",key:"constructionMethod",category:"design",uadFormat:"ConstructionMethodType"},{name:"qualityCondition",label:"Overall Quality / Condition",key:"qualityCondition",category:"design",uadFormat:"Q1-Q6 / C1-C6"},{name:"interiorQuality",label:"Interior Quality / Condition",key:"interiorQuality",category:"design",uadFormat:"Q1-Q6 / C1-C6",referenceOnly:!0},{name:"exteriorQuality",label:"Exterior Quality / Condition",key:"exteriorQuality",category:"design",uadFormat:"Q1-Q6 / C1-C6",referenceOnly:!0},{name:"attachedDetached",label:"Attached / Detached",key:"attachedDetached",category:"design",uadFormat:"Attached|Detached"},{name:"yearBuilt",label:"Year Built",key:"yearBuilt",mlsKey:"yearBuilt",prKey:"yearBuilt",category:"design",uadFormat:"number (year)"},{name:"aboveGrade",label:"Above Grade Rooms",key:"rooms",category:"rooms",uadFormat:"[Total]|[Bdrms]|[Baths]"},{name:"gla",label:"Finished Area Above Grade",key:"gla",mlsKey:"squareFeet",prKey:"squareFeet",category:"rooms",uadFormat:"[#] sf"},{name:"basement",label:"Below Grade Area",key:"basement",mlsKey:"basement",prKey:"basement",category:"basement",uadFormat:"[#]sf;[#]sfin"},{name:"belowGrade",label:"Rooms Below Grade",key:"belowGrade",category:"basement",uadFormat:"[#]rr [#]br [#.#]ba"},{name:"functionalUtility",label:"Functional Utility",key:"functionalUtility",category:"features",uadFormat:"FunctionalIssueType"},{name:"heatingCooling",label:"Heating/Cooling",key:"heating",category:"features",uadFormat:"[Heat];[Cool]"},{name:"energyEfficient",label:"Energy Efficient Items",key:"energyEfficient",category:"features",uadFormat:"text"},{name:"garageCarport",label:"Vehicle Storage",key:"garageSpaces",mlsKey:"garageSpaces",prKey:"garageSpaces",category:"features",uadFormat:"[#] [Type]; ..."},{name:"porchPatioDeck",label:"Porch/Patio/Deck",key:"porch",category:"features",uadFormat:"[Type];[sf]"},{name:"netAdjustment",label:"Net Adjustment",key:"netAdjustment",category:"adjustments",uadFormat:"$"},{name:"grossAdjustment",label:"Gross Adjustment",key:"grossAdjustment",category:"adjustments",uadFormat:"$"},{name:"adjustedSalePrice",label:"Adjusted Sale Price",key:"adju
15stedSalePrice",category:"adjustments",uadFormat:"$"}];function qH(t){const a=t.split("-").pop()||t;return jg.find(s=>s.name===a)?.uadFormat==="date"}new Set(jg.filter(t=>t.photoCardOnly).map(t=>t.name));const $k={financingConcessions:["saleType","concessions"],qualityCondition:["quality","condition"],aboveGrade:["bedrooms","bathrooms"],belowGrade:["belowGradeBedrooms","belowGradeBathrooms"]};function Mp(){return jg.filter(t=>!t.photoCardOnly&&!t.referenceOnly&&t.category!=="adjustments").map(t=>t.name)}function YH(){return jg.filter(t=>t.category==="adjustments").map(t=>t.name)}const GH=new Set(["quality","condition"]);function TS(){return jg.filter(t=>(t.photoCardOnly||t.referenceOnly)&&t.category!=="adjustments"&&!GH.has(t.name)).map(t=>t.name)}const Bk=[{name:"strNightlyRate",label:"Nightly Rate",key:"nightlyRate",category:"str_income"},{name:"strOccupancy",label:"Occupancy Rate",key:"occupancyRate",category:"str_income"},{name:"strAnnualNights",label:"Annual Nights",key:"annualNights",category:"str_income"},{name:"strGrossIncome",label:"Gross Monthly Income",key:"grossMonthlyIncome",category:"str_income"},{name:"strDataSource",label:"Data Source",key:"dataSource",category:"str_income"},{name:"strBedrooms",label:"Bedrooms",key:"bedrooms",category:"str_property"},{name:"strBathrooms",label:"Bathrooms",key:"bathrooms",category:"str_property"},{name:"strGLA",label:"GLA",key:"gla",category:"str_property"},{name:"strParking",label:"Parking",key:"parking",category:"str_property"},{name:"strLocation",label:"Location",key:"location",category:"str_property"}];function DP(){return Bk.map(t=>t.name)}const kP={leaseholdFeeSimple:"Ownership Rights (Estate Type)",dateOfSale:"Sale Date",saleType:"Transfer Terms",basement:"Finished / Unfinished Area Below Grade",basementUnit2:"Finished / Unfinished Area Below Grade — Unit 2",basementUnit3:"Finished / Unfinished Area Below Grade — Unit 3",basementUnit4:"Finished / Unfinished Area Below Grade — Unit 4"};function Ah(t,a="1004",s=!1){return s&&a!=="str"&&kP[t]?kP[t]:(a==="str"?Bk:jg).find(i=>i.name===t)?.label||t}function Sj(t){return!(t==null||t==="")}function HH(t){const a=[];let s=0,r=0;const n=t,i=t.mlsData,l=t.publicRecordData;for(const m of jg){let h=null;m.mlsKey&&i&&(h=i[m.mlsKey]),Sj(h)||(h=n[m.key]),Sj(h)||(h=null);let f=null;if(m.prKey&&l&&(f=l[m.prKey]),Sj(f)||(f=null),m.name==="dateOfSale"){const j=i?.saleDate??n.saleDate,T=i?.contractDate??i?.ContractDate??i?.PurchaseContractDate??i?.purchaseContractDate??n.contractDate;(j||T)&&(h=Mm(j,T))}if(m.name==="yearBuilt"){const j=i?.yearBuilt??n.yearBuilt??l?.yearBuilt;j&&(h=String(j))}if(m.name==="listingStatus"&&(h=TN(String(i?.status??n.status??""))),m.name==="neighborhoodName"){const j=i?.subdivision??i?.SubdivisionName??i?.neighborhood??n.subdivision;h=j!=null&&String(j).trim()!==""?String(j).trim():null}if(m.name==="proximity"){const j=typeof n.distance=="number"&&n.distance>0?n.distance:null;h=j!=null?`${j.toFixed(2)} Miles`:null}if(m.name==="financingConcessions"){const j=cp(n.saleType||i?.saleType||"ArmLth"),T=ib(n.concessions||i?.concessions);h=Pv(j,"",!1,T)}if(m.name==="qualityCondition"){const j=n.quality||i?.quality||"Q4",T=n.condition||i?.condition||"C3";h=`${j} / ${T}`}if(m.name==="basement"){const j=Tv({compData:n,mlsData:i,prData:l});j.kind==="value"||j.kind==="confirmed-none"?h=nC(j.formatted)||null:h=null}if(m.name==="porchPatioDeck"){const j=PI({compData:n,mlsData:i,prData:l});j.kind==="value"||j.kind==="confirmed-none"?h=j.formatted:h=null}if(m.name==="garageCarport"){const j=dy({compData:n,mlsData:i,prData:l});j.kind==="value"||j.kind==="confirmed-none"?h=rC(j.formatted)||null:h=null}if(m.name==="site"){const j=i?.lotSize??n.lotSize??l?.lotSize,T=i?.lotSizeUnits??n.lotSizeUnits??"sqft";j&&(h=sb(j,T))}if(m.name==="gla"){const j=i?.squareFeet??n.gla??l?.squareFeet;j&&(h=Iv(j))}if(m.name==="belowGrade"){const j=OI({compData:n,mlsData:i,prData:l});j.kind==="value"||j.kind==="confirmed-none"?h=j.formatted:h=null}if(m.name==="aboveGrade"){const j=i?.totalRooms??n.totalRooms,T=i?.bedrooms??n.beds??l?.bedrooms,O=i?.bathrooms??n.baths??l?.bathrooms,E=i?.fullBaths??i?.BathroomsFull??n.fullBathrooms??null,R=i?.halfBaths??i?.BathroomsHalf??n.halfBathrooms??null;h=jv(j,T,O,E,R)}if(m.name==="location"&&(h=aC(n.locationType)||null),m.name==="view"&&(h=tC(n.viewT
15ype)||null),m.name==="design"){const j=i?.style??n.style??null;h=gg(j)||null}if(m.name==="heatingCooling"){const j=i?.heating??n.heating??null,T=i?.cooling??n.cooling??null;h=sC(j,T)||null}m.name==="quality"&&!h&&(h="Q4"),m.name==="condition"&&!h&&(h="C3"),m.name==="functionalUtility"&&!h&&(h="None"),m.name==="saleType"&&!h&&(h="ArmLth"),m.name==="concessions"&&!h&&(h="None");const v=[];h!==null&&v.push({source:"MLS",value:h,confidence:75}),f!==null&&v.push({source:"PublicRecord",value:f,confidence:70});const S=v.length>1&&!v.every(j=>MP(j.value)===MP(v[0].value));S&&s++;const N=v.length>0?v[0].value:null,x=v.length>0?v[0].source:"MLS",y=!S&&N!==null;y&&r++;const b=S?40:y?80:60;a.push({name:m.name,label:m.label,category:m.category,currentValue:N,currentSource:x,sources:v,hasConflict:S,isVerified:y,confidence:b})}const c=a.length>0?Math.round(a.reduce((m,h)=>m+h.confidence,0)/a.length):50,d=a.find(m=>m.name==="dateOfSale"),p=a.find(m=>m.name==="salePrice"),u=a.find(m=>m.name==="propertyType");return{id:t.id,address:t.address,city:t.city,state:t.state,photoUrl:t.photoUrl||null,photos:t.photos||[],fields:a,overallConfidence:c,conflictCount:s,verifiedCount:r,saleDate:d?.currentValue?String(d.currentValue):void 0,salePrice:p?.currentValue?Number(p.currentValue):void 0,propertyType:u?.currentValue?String(u.currentValue):void 0,mlsNumber:t.mlsNumber||t.listingId}}function MP(t){return t==null?"":String(t).trim().toLowerCase()}function WH(t,a,s,r,n){const i=t.fields.map(p=>{if(p.name!==a)return p;const u={source:r,value:s,confidence:r==="User"?95:85,timestamp:new Date().toISOString(),note:n};return{...p,currentValue:s,currentSource:r,isVerified:!0,hasConflict:!1,confidence:r==="User"?95:85,sources:[u,...p.sources.filter(m=>m.source!==r)]}}),l=i.filter(p=>p.hasConflict).length,c=i.filter(p=>p.isVerified).length,d=Math.round(i.reduce((p,u)=>p+u.confidence,0)/i.length);return{...t,fields:i,conflictCount:l,verifiedCount:c,overallConfidence:d}}function Tu(t){if(t.source!=="catalog"||!t.rowId)return;const a=mb.find(s=>s.rowId===t.rowId);return a?.uad36Element?a.uad36Element:t.rowId}const KH={LandOwnedInCommonIndicator:{fieldKey:"LandOwnedInCommonIndicator",normalize:t=>t===!0||t==="true"?"true":t===!1||t==="false"?"false":void 0},HazardZoneType:{fieldKey:"HazardZoneType",normalize:t=>{if(Array.isArray(t))return t;if(typeof t=="string"&&t.trim()!=="")return t.trim()}},SalesContractExistsIndicator:{fieldKey:"SalesContractExistsIndicator",normalize:t=>t===!0||t==="true"?"true":t===!1||t==="false"?"false":void 0},SalesContractReviewedIndicator:{fieldKey:"SalesContractReviewedIndicator",normalize:t=>t===!0||t==="true"?"true":t===!1||t==="false"?"false":void 0},ProximityToSubjectDistanceLinearMeasure:{fieldKey:"proximity",normalize:t=>typeof t=="string"&&t.trim()!==""?t.trim():void 0},ListingStatusType:{fieldKey:"listingStatus",normalize:t=>typeof t=="string"&&t.trim()!==""?t.trim():void 0},PropertyInProjectIndicator:{fieldKey:"PropertyInProjectIndicator",normalize:t=>t===!0||t===!1?String(t):typeof t=="string"&&t.trim()!==""?t.trim():void 0},ProjectLegalStructureType:{fieldKey:"ProjectLegalStructureType",normalize:t=>typeof t=="string"&&t.trim()!==""?t.trim():void 0},OwnershipTransferTransactionType:{fieldKey:"saleHistory0_OwnershipTransferTransactionType",normalize:t=>typeof t=="string"&&t.trim()!==""?t.trim():void 0}};function FP(t,a,s){const r=new Map;for(const i of s){const l=Tu(i);l&&!r.has(l)&&r.set(l,i.id)}const n=i=>({get:l=>{if(l==="OwnershipTransferTransactionType"){const m=i.transferHistory?.[0],h=m?.OwnershipTransferTransactionType??m?.transactionType??m?.type,v=(S=>S&&typeof S=="object"&&"value"in S?S.value:S)(h);return v!=null&&String(v).trim()!==""?v:void 0}if(l==="ListingStatusType"){const u=i.fields?.listingStatus;if(u?.source==="User")return u.value===""||u.value===void 0||u.value===null?void 0:String(u.value).trim()||void 0}const c=KH[l],d=i.fields?.[l]?.value;if(d!==""&&d!==void 0&&d!==null)return c?.normalize(d)??d;const p=r.get(l);if(p){const u=i.fields?.[p]?.value;if(u!==""&&u!==void 0&&u!==null)return u}if(c){const u=i.fields?.[c.fieldKey]?.value,m=c.normalize(u);return m===""||m===void 0?void 0:m}}});return{subject:n(t),comps:a.map(n)}}const qd={gla:"GLA",bedrooms:"Bedrooms",bathrooms:"Bathrooms",garage:"Garage",basement:"Basement",site:"Site / Lot",condition:"Condition",quality:"Quality",location:"Location"},HT={gla:"$/sqft",bedrooms:"$/bed",bathrooms:"$/bath",garage:"$/space",basement:"$/sqft",site:"$/sqft",condition:"$/tier",quality:"$/tier",location:"$/ELS-pt"},uf={paired:"Paired Sales",peeled:"Paired Sales (peeled, retired)",grouped:"Grouped Paired Sales",regression:"Regression","manual-c
15hip":"Manual (chip)"},af={submarket:"Submarket",broad:"Broad Market",manual:"Manual"},_P={similarityToleranceFailed:"Comps too dissimilar overall (similarity-distance tolerance exceeded)",glaMismatch:"GLA was the largest similarity-distance contributor",bedroomMismatch:"Bedroom count was the largest similarity-distance contributor",bathroomMismatch:"Bathroom count was the largest similarity-distance contributor",garageMismatch:"Garage spaces were the largest similarity-distance contributor",lotSizeMismatch:"Lot size was the largest similarity-distance contributor",conditionMismatch:"Condition tier differed (categorical pairs require Δ=1)",qualityMismatch:"Quality tier differed (categorical pairs require Δ=1)",yearMismatch:"Year built was the largest similarity-distance contributor",nullValueRejected:"One of the comps was missing this attribute",equalValueRejected:"Both comps had the same value for this attribute",priceRatioOutlier:"Implied $/unit exceeded the trim band",locationDeltaTooSmall:"Location score difference was below the floor",targetDeltaBelowFloor:"Target attribute delta was below the per-attribute floor"},qh=15;function WT(t,a){if(t==null||t<=0||t>=qh)return null;const s=a?qd[a]:"this attribute";return`Sample size of ${t} is below the confidence threshold of ${qh}. Consider another method or the broader market for ${s}.`}function V0(t){if(t==null)return null;if(typeof t=="string")try{return JSON.parse(t)}catch{return null}return typeof t=="object"?t:null}function vj(t){return t==="market"?"Broad market":t==="submarket"?"Submarket":"FHFA"}function IS(t,a,s){if(!s||s.isAvailable===!1||a==="curve"&&!(Array.isArray(s.curveData)&&s.curveData.length>0))return null;const r=s.linearRate,n=s.recommendedMethod===a,i=s.counts?.included??s.includedSales?.length??0,l=a==="linear"?s.trendConsistency:null,c=a==="linear"?`One steady ${r!=null&&r>=0?"appreciation":"depreciation"} rate across all months in the ${vj(t).toLowerCase()} dataset.`:`Indexed month-by-month adjustment derived from the ${vj(t).toLowerCase()} dataset — best when prices changed direction.`;return{id:`${a}-${t}`,label:`${a==="linear"?"Linear":"Monthly"} (${vj(t)})`,dataset:t,method:a,monthlyRatePct:r,sampleSize:i,r2:l,explanation:c,isRecommended:n}}function QH(t){return!t||typeof t.rateEquivMonth!="number"||!isFinite(t.rateEquivMonth)?null:{
15id:"hpi-fhfa",label:"HPI",dataset:"fhfa",method:"hpi_only",monthlyRatePct:t.rateEquivMonth,sampleSize:null,r2:null,explanation:"Federal Housing Finance Agency repeat-sales index — broad regional benchmark, not a local paired-sales rate.",isRecommended:!1}}function zk(t){if(!t)return[];const a=V0(t.marketResultsJson),s=V0(t.submarketResultsJson),r=V0(t.fhfaResultsJson);return[IS("submarket","linear",s),IS("market","linear",a),IS("submarket","curve",s),IS("market","curve",a),QH(r)].filter(i=>i!=null)}function qk(t){if(!t||!t.decisionSavedAt)return null;const a=t.selectedDataset,s=t.selectedMethod;if(!a||!s||s==="zero")return null;let r=null;if(s==="linear"||s==="curve"||s==="hpi_only")r=s;else if(s==="recommended"){if(a==="market"){const i=V0(t.marketResultsJson)?.recommendedMethod;(i==="linear"||i==="curve")&&(r=i)}else if(a==="submarket"){const i=V0(t.submarketResultsJson)?.recommendedMethod;(i==="linear"||i==="curve")&&(r=i)}}return r?r==="hpi_only"?"hpi-fhfa":`${r}-${a}`:null}function ZH(t){return t==null||!isFinite(t)?"—":`${t>=0?"+":""}${t.toFixed(2)}%/mo`}function JH(t){return t==null||!isFinite(t)?null:`R² ${t.toFixed(2)}`}const Yk=({options:t,activeMethodId:a,needsWizard:s,isWorking:r,isHydrating:n,errorMessage:i,onSelect:l,onRemove:c,onOpenFullWizard:d})=>{const[p,u]=o.useState(null),m=f=>{r||f.id!==a&&(u(f.id),l(f))},h=()=>{r||(u("__remove__"),c())};return e.jsxs("div",{className:"space-y-2","data-testid":"popover-time-method-picker",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[11px] font-semibold text-slate-700",children:"Time adjustment · Pick a method"}),a&&e.jsxs("span",{className:"text-[10px] font-medium text-blue-700 inline-flex items-center gap-1",children:[e.jsx(kr,{className:"w-3 h-3"})," Active"]})]}),n?e.jsxs("div",{className:"flex items-center gap-2 py-3 text-[11px] text-slate-500","data-testid":"time-picker-loading",children:[e.jsx(za,{className:"w-3.5 h-3.5 animate-spin"})," Loading time-trend data…"]}):t.length===0?e.jsxs("div",{className:"rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[11px] text-amber-800 flex items-start gap-2","data-testid":"time-picker-empty",children:[e.jsx(Ns,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:"No time-trend results yet. Open the full wizard to lock the market and derive rates."})]}):e.jsx("div",{className:"space-y-1.5 max-h-[260px] overflow-auto pr-1",children:t.map(f=>{const v=f.id===a,S=p===f.id&&r,N=JH(f.r2);return e.jsxs("button",{type:"button",disabled:!!r||!!s,onClick:()=>m(f),title:s?"Open the full wizard to lock and derive rates first":void 0,className:Q("w-full text-left rounded-md border px-2.5 py-2 transition-colors","focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500",v?"bg-blue-50 border-blue-300":"bg-white border-slate-200 hover:bg-slate-50 hover:border-slate-300",(r||s)&&"opacity-60 cursor-not-allowed"),"data-testid":`time-method-option-${f.id}`,"data-active":v?"true":"false",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-[12px] font-semibold text-slate-800 truncate",children:f.label}),f.isRecommended&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[9px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 rounded px-1 py-0.5","data-testid":`time-method-recommended-${f.id}`,children:[e.jsx(ul,{className:"w-2.5 h-2.5"})," Suggested"]})]}),e.jsx("span",{className:"text-[12px] font-mono font-semibold text-slate-900 whitespace-nowrap",children:ZH(f.monthlyRatePct)})]}),e.jsxs("div",{className:"mt-0.5 flex items-center gap-2 text-[10px] text-slate-500",children:[f.sampleSize!=null&&e.jsxs("span",{"data-testid":`time-method-n-${f.id}`,children:["n = ",f.sampleSize]}),N&&e.jsx("span",{"data-testid":`time-method-r2-${f.id}`,children:N}),v&&e.jsx("span",{className:"text-blue-700 font-semibold",children:"Currently applied"}),S&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-blue-700",children:[e.jsx(za,{className:"w-2.5 h-2.5 animate-spin"})," Saving…"]})]}),e.jsx("div",{className:"mt-1 text-[10px] text-slate-600 leading-snug",children:f.explanation})]},f.id)})}),i&&e.jsx("div",{className:"text-[10px] text-red-600 rounded bg-red-50 border border-red-200 px-2 py-1","data-testid":"time-picker-error",children:i}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1 border-t border-slate-100",children:[e.jsxs(De,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-[11px] text-slate-500 hover:text-red-600",onClick:h,disabled:!!r||!a,"data-testid":"button-time-method-remove",children:[e.jsx(Ci,{className:"w-3 h-3 mr-1"}),"Remove"]}),e.jsxs(De,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-[11px] text-blue-700 hover:text-blue-900 hover:bg-blue-50",onClick:d,"data-testid":"button-time-method-open-wizard",children:[e.jsx(rf,{className:"w-3 h-3 mr-1"}),"Open full wizard"]})]})]})},Gk=({currentRatePct:t,currentBasis:a,isManualLocked:s,disabledReason:r,compact:n,onApply:i})=>{const[l,c]=o.useState(()=>
15t!=null&&Number.isFinite(t)?t.toFixed(2):""),[d,p]=o.useState(a??"SALE"),[u,m]=o.useState(!1),[h,f]=o.useState(null),[v,S]=o.useState(!1);o.useEffect(()=>{t!=null&&Number.isFinite(t)&&c(t.toFixed(2))},[t]),o.useEffect(()=>{a&&p(a)},[a]);const N=!!r,x=async()=>{f(null);const y=parseFloat(l);if(!Number.isFinite(y)){f("Enter a numeric rate (e.g. 0.50 for 0.50%/mo).");return}if(Math.abs(y)>5){f("Rate must be within ±5%/mo.");return}m(!0);try{await i(y,d),S(!0),setTimeout(()=>S(!1),1500)}catch(b){f(b instanceof Error?b.message:"Failed to apply manual rate.")}finally{m(!1)}};return e.jsxs("div",{className:Q("rounded-md border border-slate-200 bg-white",n?"p-2":"p-3 space-y-2"),"data-testid":"time-custom-rate-panel",children:[e.jsxs("div",{className:Q("flex items-center justify-between",n?"mb-1":""),children:[e.jsxs("div",{className:"text-[11px] font-semibold text-slate-700 inline-flex items-center gap-1",children:[s&&e.jsx(Hr,{className:"w-3 h-3 text-emerald-600"}),"Custom rate"]}),s&&e.jsx("span",{className:"text-[9px] font-semibold text-emerald-700 bg-emerald-50 border border-emerald-200 rounded px-1 py-0.5","data-testid":"time-custom-rate-locked-badge",children:"Manual locked"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{type:"number",step:"0.01",inputMode:"decimal",value:l,onChange:y=>{c(y.target.value),f(null)},onKeyDown:y=>{y.key==="Enter"&&!u&&!N&&(y.preventDefault(),x())},disabled:N||u,placeholder:"0.50",className:Q("w-full text-[12px] font-mono font-semibold text-slate-800 px-2 py-1 pr-10","border border-slate-200 rounded","focus:outline-none focus:ring-2 focus:ring-blue-500","disabled:bg-slate-50 disabled:text-slate-400 disabled:cursor-not-allowed"),"data-testid":"input-time-custom-rate"}),e.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-[10px] text-slate-400 font-medium pointer-events-none",children:"%/mo"})]}),e.jsx("div",{className:"inline-flex border border-slate-200 rounded overflow-hidden text-[10px] font-semibold",role:"group","aria-label":"Price basis",children:["CTR","SALE"].map(y=>e.jsx("button",{type:"button",onClick:()=>p(y),disabled:N||u,className:Q("px-2 py-1 transition-colors",d===y?"bg-[#072034] text-white":"bg-white text-slate-500 hover:bg-slate-50",(N||u)&&"opacity-50 cursor-not-allowed"),"data-testid":`button-time-basis-${y.toLowerCase()}`,"data-active":d===y?"true":"false",title:y==="CTR"?"Apply rate to Contract price":"Apply rate to Sale price",children:y},y))}),e.jsx(De,{type:"button",size:"sm",onClick:x,disabled:N||u||!l,className:Q("h-7 px-2.5 text-[11px] font-semibold","bg-[#072034] text-white hover:bg-[#0c2f4d]"),"data-testid":"button-time-custom-rate-apply",children:u?e.jsx(za,{className:"w-3 h-3 animate-spin"}):v?e.jsx(Bs,{className:"w-3 h-3"}):"Apply"})]}),h&&e.jsx("div",{className:"text-[10px] text-red-600 bg-red-50 border border-red-200 rounded px-2 py-1","data-testid":"text-time-custom-rate-error",children:h}),r&&e.jsx("div",{className:"text-[10px] italic text-slate-500","data-testid":"text-time-custom-rate-disabled-reason",children:r}),!n&&!h&&!r&&e.jsx("p",{className:"text-[9px] text-slate-400 leading-snug",children:"Submit overrides the model-derived rate. Persists with `manual` method; CTR/SALE basis is recorded in the audit trail."})]})};function UP(t,a){if(a==="%sf"||a.startsWith("%"))return`${t.toFixed(2)}${a}`;const s=Math.round(t);return`${s<0?"-":""}$${Math.abs(s).toLocaleString("en-US")}${a.startsWith("$/")?a.slice(1):a}`}const XH=({attribute:t,prefix:a,rate:s,unit:r,defaultUnit:n,supportsPctSf:i,isHydrating:l,isApplying:c,onApply:d,onClear:p,disabledReason:u,sourceMethod:m,sourceDataset:h,aggregation:f})=>{const[v,S]=o.useState(!1),[N,x]=o.useState(""),[y,b]=o.useState(r||n);if(o.useEffect(()=>{v&&(x(s!=null?String(s):""),b(r||n))},[v,s,r,n]),l)return e.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-medium bg-slate-100 text-slate-300","data-testid":`chip-master-rate-${t}-hydrating`,children:[e.jsx(za,{className:"w-2.5 h-2.5 animate-spin"}),a??"·"]});const j=s!=null,T=j?`${a?a+" ":""}${UP(s,r||n)}`:`${a?a+" ":""}Set rate`,O=parseFloat(N),E=isFinite(O)&&O>0,R=N.trim()===""?null:isFinite(O)?O<=0?"Must be greater than 0":null:"Enter a number",G=()=>{E&&(d(O,y),S(!1))},U=()=>{p(),S(!1)},C=e.jsxs("button",{type:"button",disabled:!!u,title:u??`Master rate for ${t}`,className:Q("inline-flex max-w-full items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-semibold transition-colors",j?"bg-emerald-50 border border-emerald-200 text-emerald-700 hover:bg-emerald-100":"bg-slate-100 border border-slate-200 text-slate-500 hover:bg-slate-200 hover:text-slate-700",u&&"opacity-40 cursor-not-allowed"),"data-testid":`chip-master-rate-${t}`,children:[c?e.jsx(za,{className:"w-2.5 h-2.5 shrink-0 animate-spin"}):j?e.jsx(Hr,{className:"w-2.5 h-2.5 shrink-0"}):null,e.jsx("span",{className:"min-w-0 leading-tight [overflow-wrap:anywhere]",children:T})]}),F=m?uf[m]??m:null,A=h?af[h]??h:null,M=j&&(F||A)?`Locked from ${[F==="Manual (chip)"?"Master Rate chip":"Multi-Method",A,F&&F!=="Manual (chip)"?F:null].filter(
15Boolean).join(" · ")}`:null,B=f&&f.siblings.length>1?`${f.fieldLabel} combines ${f.siblings.join(" + ")}`:null,ae=!u&&(M||B)?e.jsx(gr,{delayDuration:150,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:C}),e.jsx(Wa,{side:"top",className:"max-w-xs text-[11px]","data-testid":`tooltip-master-rate-${t}`,children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"font-semibold text-slate-700",children:[qd[t],a?` (${a})`:""," · ",UP(s,r||n)]}),M&&e.jsx("p",{className:"text-muted-foreground","data-testid":`tooltip-master-rate-${t}-source`,children:M}),B&&e.jsx("p",{className:"text-muted-foreground","data-testid":`tooltip-master-rate-${t}-aggregation`,children:B})]})})]})}):C;return e.jsxs(xn,{open:v,onOpenChange:S,children:[e.jsx(bn,{asChild:!0,children:ae}),e.jsx(yn,{className:"w-64 p-3",align:"start","data-testid":`popover-master-rate-${t}`,children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-[11px] font-semibold text-slate-700",children:["Master rate · ",t,a?` (${a})`:""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{type:"number",step:"any",value:N,onChange:D=>x(D.target.value),onKeyDown:D=>{D.key==="Enter"&&G(),D.key==="Escape"&&S(!1)},className:"h-8 text-xs",placeholder:"e.g. 107",autoFocus:!0,"data-testid":`input-master-rate-${t}`}),i?e.jsxs("select",{value:y,onChange:D=>b(D.target.value),className:"h-8 text-[11px] border border-slate-200 rounded px-1 bg-white","data-testid":`select-unit-${t}`,children:[e.jsx("option",{value:"$/sqft",children:"$/sf"}),e.jsx("option",{value:"%sf",children:"%sf"})]}):e.jsx("span",{className:"text-[11px] text-slate-500 whitespace-nowrap",children:y})]}),R&&e.jsx("div",{className:"text-[10px] text-red-600","data-testid":`error-master-rate-${t}`,children:R}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-1",children:[e.jsx(De,{size:"sm",variant:"ghost",className:"h-7 text-[11px] text-slate-500 hover:text-red-600",onClick:U,disabled:!j,"data-testid":`button-clear-master-rate-${t}`,children:"Clear"}),e.jsx(De,{size:"sm",className:"h-7 text-[11px] bg-emerald-600 hover:bg-emerald-700",onClick:G,disabled:c||!E,"data-testid":`button-apply-master-rate-${t}`,children:c?e.jsx(za,{className:"w-3 h-3 animate-spin"}):"Apply"})]})]})})]})},e8=({monthlyRateLabel:t,isLocked:a,disabledReason:s,isHydrating:r,picker:n,manual:i,onOpenFullWizard:l})=>{const[c,d]=o.useState(!1),p=t??"Time…",u=e.jsxs("button",{type:"button",disabled:!!s,title:s??"Pick a time-adjustment method",className:Q("inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-semibold transition-colors",a?"bg-blue-50 border border-blue-200 text-blue-700 hover:bg-blue-100":"bg-slate-100 border border-slate-200 text-slate-500 hover:bg-slate-200 hover:text-slate-700",s&&"opacity-40 cursor-not-allowed"),"data-testid":"chip-master-rate-time",children:[a?e.jsx(Hr,{className:"w-2.5 h-2.5 shrink-0"}):e.jsx(Pu,{className:"w-2.5 h-2.5 shrink-0"}),e.jsx("span",{className:"min-w-0 leading-tight [overflow-wrap:anywhere]",children:p})]});return n?e.jsxs(xn,{open:c,onOpenChange:d,children:[e.jsx(bn,{asChild:!0,children:u}),e.jsxs(yn,{className:"w-[380px] p-3 space-y-3",align:"start","data-testid":"popover-master-rate-time",children:[e.jsx(Yk,{...n,isHydrating:r,onOpenFullWizard:()=>{d(!1),n.onOpenFullWizard?n.onOpenFullWizard():l()}}),i&&e.jsx("div",{className:"border-t border-slate-100 pt-2",children:e.jsx(Gk,{compact:!0,currentRatePct:i.rate,currentBasis:i.basis,isManualLocked:i.isManualLocked,disabledReason:i.needsWizard?"Open the full wizard to lock + derive rates first.":null,onApply:i.onApply})})]})]}):e.jsxs("button",{type:"button",onClick:l,disabled:!!s,title:s??"Open time-adjustment wizard",className:Q("inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-semibold transition-colors",a?"bg-blue-50 border border-blue-200 text-blue-700 hover:bg-blue-100":"bg-slate-100 border border-slate-200 text-slate-500 hover:bg-slate-200 hover:text-slate-700",s&&"opacity-40 cursor-not-allowed"),"data-testid":"chip-master-rate-time",children:[a?e.jsx(Hr,{className:"w-2.5 h-2.5 shrink-0"}):e.jsx(Pu,{className:"w-2.5 h-2.5 shrink-0"}),e.jsx("span",{className:"min-w-0 leading-tight [overflow-wrap:anywhere]",children:p})]})};function t8({orderId:t,availableSlots:a=24}){const s=ku(),{data:r}=QV(t),n=r?.exclusions??[],{inspecting:i}=fc(),[l,c]=o.useState(()=>`manual-${Date.now()}`);o.useEffect(()=>{n.some(u=>u.compId===l)&&c(`manual-${Date.now()}`)},[n,l]);const d=async u=>{try{await fetch(`/api/orders/${t}/comp-exclusions/${u}`,{method:"DELETE"}),await JV({orderId:t,compId:u,queryClient:s}),s.invalidateQueries({queryKey:["comp-exclusions",t]})}catch(m){console.error("[AdditionalNotUsedSection] delete failed:",m)}},p=Math.max(0,a);return e.jsxs("div",{className:"mx-4 mb-4 max-w-6xl rounded-lg bg-slate-50 p-4 ring-1 ring-slate-200","data-testid":"not-used-section",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs("h2",{className:"text-sm font-semibold text-slate-900 shrink-0",children:["Additional Properties Analyzed Not Used",i&&e.jsx(Fs,{section:"salesGrid",fieldName:"
15compExclusions[]"})]}),e.jsxs("span",{className:Q("text-[11px] shrink-0",Math.max(0,p-n.length)===0?"text-red-500 font-medium":"text-slate-500"),children:["Slots available:"," ",e.jsx("span",{className:"font-semibold",children:Math.max(0,p-n.length)})]})]}),e.jsx(kI,{orderId:t,compId:l,compAddress:"",existing:null,trigger:e.jsxs(De,{variant:"ghost",size:"sm",className:"h-7 px-2 text-[11px] text-slate-600","data-testid":"button-add-not-used-row",children:[e.jsx(un,{className:"mr-1 h-3.5 w-3.5"}),"Add property"]})},l)]}),n.length===0?e.jsx("div",{className:"rounded border border-dashed border-slate-200 bg-white px-3 py-4 text-center text-[11px] text-slate-400","data-testid":"text-not-used-empty",children:'No properties marked "Not Used" yet. Mark a comp as Not Used in Property Lab, or add one manually with "Add property".'}):e.jsx("div",{className:"flex flex-col divide-y divide-slate-100 overflow-hidden rounded-md border border-slate-200 bg-white",children:n.map((u,m)=>e.jsx(a8,{exclusion:u,orderId:t,overflow:m>=p,index:m+1,onDelete:()=>{d(u.compId)}},u.compId))})]})}function a8({exclusion:t,orderId:a,overflow:s,index:r,onDelete:n}){const l=[t.addressLine||t.compAddress||"",t.city,t.stateCode].filter(Boolean).join(", ")||"—",c=t.listingStatus?Hs("ListingStatusType",t.listingStatus)||t.listingStatus:null,d=t.saleDate?(()=>{try{return new Date(t.saleDate).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"numeric"})}catch{return t.saleDate}})():null,p=[c,d].filter(Boolean).join(" | "),u=ZV(t.reasons??[],null,t.customReasons??[]),m=[t.addressLine||t.compAddress,t.city,t.stateCode,t.postalCode].filter(Boolean).join(", "),h=s?"text-slate-400":"text-slate-800";return e.jsxs("div",{className:"group flex items-center gap-1 px-3 py-2","data-testid":`row-not-used-${t.compId}`,children:[s?e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("span",{className:"shrink-0 w-4 cursor-default text-amber-500",children:e.jsx(Xx,{className:"h-3.5 w-3.5"})})}),e.jsx(Wa,{side:"top",className:"max-w-[220px] text-center text-[11px]",children:"This entry won't appear in the report until a slot becomes available."})]}):e.jsx("span",{className:"shrink-0 w-4","aria-hidden":!0}),e.jsx(kI,{orderId:a,compId:t.compId,compAddress:m,compAddressLine:t.addressLine??void 0,compCity:t.city??void 0,compState:t.stateCode??void 0,compZip:t.postalCode??void 0,existing:t,trigger:e.jsxs("button",{type:"button",className:"-mx-1 flex flex-1 min-w-0 items-center gap-4 roun
15ded px-1 text-left transition-colors hover:bg-slate-50","data-testid":`button-nu-edit-${t.compId}`,children:[e.jsxs("span",{className:"inline-flex shrink-0 items-center",children:[e.jsx("span",{className:Q("w-4 text-right text-[11px] tabular-nums",h),children:r}),e.jsx("span",{className:"w-3 text-left text-[9px] font-bold leading-none text-blue-500",children:t.reconsiderationRequested?e.jsx("span",{title:"Reconsideration requested",children:"R"}):null})]}),e.jsx("span",{className:Q("min-w-0 flex-[2] truncate text-[12px] font-medium",h),children:l}),p&&e.jsx("span",{className:Q("shrink-0 text-[11px]",h),children:p}),u?e.jsx("span",{className:Q("min-w-0 flex-[3] truncate text-[11px]",h),children:u}):e.jsx("span",{className:"shrink-0 text-[11px] italic text-amber-500",children:"no reason"}),t.comment&&e.jsx("span",{className:Q("hidden min-w-0 flex-1 truncate text-[11px] sm:block",s?"text-slate-300":"text-slate-800"),children:t.comment})]})}),e.jsx("button",{type:"button",onClick:n,className:"ml-2 shrink-0 text-slate-200 transition-colors hover:text-red-500",title:"Remove this property","data-testid":`button-nu-delete-${t.compId}`,children:e.jsx(Ci,{className:"h-4 w-4"})})]})}const Fm={gla:"gla",bedrooms:"aboveGrade",bathrooms:"aboveGrade",garage:"garageCarport",basement:"basement",site:"site",condition:"qualityCondition",quality:"qualityCondition",location:"location"},Nj=(()=>{const t={};for(const[a,s]of Object.entries(Fm))t[s]||(t[s]=[]),t[s].push(a);return t})(),Kv=t=>{if(!t)return null;const a=String(t).match(/(\d+)/);return a?parseInt(a[1],10):null};function Hk(t,a){switch(t){case"gla":return a.gla??null;case"bedrooms":return a.bedrooms??null;case"bathrooms":return a.bathrooms??null;case"garage":return a.garageSpaces??0;case"basement":return a.basementSqft??0;case"site":return a.lotSize??null;case"condition":return Kv(a.condition);case"quality":return Kv(a.quality);case"location":return a.elsScore??null}}function Wk(t,a){switch(t){case"gla":return a.gla??null;case"bedrooms":return a.bedrooms??null;case"bathrooms":return a.bathrooms??null;case"garage":return a.garageSpaces??0;case"basement":return a.basementSqft??0;case"site":return a.lotSize??null;case"condition":return Kv(a.condition);case"quality":return Kv(a.quality);case"location":return a.elsScore??null}}function KT(t,a,s,r){const n={},i=Array.from(r);for(const u of s){n[u.id]={};for(const m of i)n[u.id][m]=0}const l={};let c=0,d=0;for(const[u,m]of Object.entries(t)){if(!m)continue;const h=u;if(!isFinite(m.rate)){d++,console.warn(`[ChipCascade] Skipping ${h}: non-finite locked rate (${String(m.rate)})`);continue}const f=Hk(h,a);if(f==null)continue;const v=Fm[h];for(const S of s){const N=Wk(h,S);if(N==null)continue;let x;if(h==="gla"&&m.unit==="%sf"){if(N===0)continue;x=Math.round(m.rate/100*S.salePrice*(f-N)/N)}else x=Math.round(m.rate*(f-N));x!==0&&(v in n[S.id]||(n[S.id][v]=0),n[S.id][v]+=x,l[h]=(l[h]??0)+1,c+=x)}}const p=Object.entries(n).map(([u,m])=>({compId:u,adjustments:m}));if(typeof window<"u"&&window.__ECHO_DEBUG_CASCADE)for(const[u,m]of Object.entries(t))m&&console.debug(`[ChipCascade] applied attr=${u} rate=${m.rate} unit=${m.unit} compsApplied=${l[u]??0} totalAmount=${c} skippedNonFinite=${d}`);return p}const CS=t=>`${t<0?"-":""}$${Math.abs(Math.round(t)).toLocaleString("en-US")}`,Hb=t=>Number.isInteger(t)?t.toLocaleString("en-US"):t.toLocaleString("en-US",{maximumFractionDigits:2});function s8(t,a,s,r,n,i,l){if(t==="gla"&&s==="%sf"&&l!=null)return`${CS(i)} = ${a.toFixed(2)}%sf × ${CS(l)} × (${Hb(r)} − ${Hb(n)}) / ${Hb(n)}`;const c=`${CS(a)}${s?`/${s.replace(/^\$\//,"")}`:""}`;return`${CS(i)} = ${c} × (${Hb(r)} − ${Hb(n)})`}function r8(t,a,s){const r=new Map;for(const[n,i]of Object.entries(t)){if(!i||!isFinite(i.rate))continue;const l=n,c=Hk(l,a);if(c==null)continue;const d=Fm[l];for(const p of s){const u=Wk(l,p);if(u==null)continue;let m;if(l==="gla"&&i.unit==="%sf"){if(u===0)continue;m=Math.round(i.rate/100*p.salePrice*(c-u)/u)}else m=Math.round(i.rate*(c-u));if(m===0)continue;const h=`${p.id}:${d}`,f=l==="gla"&&i.unit==="%sf"?p.salePrice:void 0,v={attribute:l,rate:i.rate,unit:i.unit,subjectValue:c,compValue:u,amount:m,formula:s8(l,i.rate,i.unit,c,u,m,f)};f!=null&&(v.compSalePrice=f);const S=r.get(h);S?S.push(v):r.set(h,[v])}}return r}const RS=50,iC=t=>{if(t==null)return null;if(typeof t=="number")return Number.isFinite(t)?t:null;const a=String(t).replace(/[^0-9.\-]/g,"");if(a===""||a==="-"||a===".")return null;const s=parseFloat(a);return Number.isFinite(s)?s:null};function Kk(t){if(!t)return null;const a=iC(t.value);return a!=null&&a>0?a:null}function n8(t){if(!t)return null;const a=iC(t.value);return a!=null&&a>0?a:null}function i8(t){if(!t)return null;const a=t.trim();if(a===""||a==="–"||a==="-")return null;const s=a.indexOf(".");if(s===-1){const i=parseFloat(a);return Number.isFinite(i)?i:null}const r=parseFloat(a.slice(0,s)),n=parseFloat(a.slice(s+1));return Number.isFinite(r)?Number.isFinite(n)?r+n*.5:r:null}function Qk(t){if(!t||t.value==null)return{bedrooms:null,bathrooms:null};const s=String(t.value).split("|");if(s.length<3)return{bedrooms:null,bathrooms:null};const r=s[1].trim(),n=s[2].trim(),i=r===""||r==="–"||r==="-"?null:(()=>{const c=parseFloat(r);return Number.isFinite(c)?c:null})(),l=i8(n);return{bedrooms:i,bathrooms:l}}function Zk(t){if(!t||t.value==null)return 0;const a=String(t.value).trim();if(a===""||a==="None"||a==="–"||a==="-")return 0;let s=0;for(const r of a.split(";")){const n=r.trim().match(/^(\d+)/);if(n){const i=parseInt(n[1],10);Number.isFinite(i)&&i>0&&(s+=i)}}return s}function Jk(t){if(!t||t.value==null)return 0;const a=String(t.value).trim();if(a===""||a==="0"||a==="–"||a==="-")return 0;const s=a.match(/^(\d+)/);if(!s)return 0;const r=parseInt(s[1],10);return Number.isFinite(r)&&r>=0?r:0}function Xk(t){if(!t)return null;const a=t.lotSizeSf;if(typeof a=="number"&&Number.isFinite(a)&&a>0)return a;const s=t.lotSizeAcres;if(typeof s=="number"&&Number.isFinite(s)&&s>0)return Math.round(s*43560);const r=iC(t.value);return r!=null&&r>0?r:null}function Qv(t){if(!t||t.value==null)return;const a=String(t.value).trim();if(!(a===""||a==="–"||a==="-"))return a}function o8(t){const{bedrooms:a,bathrooms:s}=Qk(t.fields?.aboveGrade),r=Kk(t.fields?.gla);return r==null?null:{gla:r,bedrooms:a??void 0,bathrooms:s??void 0,garageSpaces:Zk(t.fields?.garageCarport),basementSqft:Jk(t.fields?.basement),lotSize:Xk(t.fields?.site)??void 0,condition:Qv(t.fields?.condition),quality:Qv(t.fields?.quality),elsScore:t.elsScore??void 0}}function l8(t){const{bedrooms:a,bathrooms:s}=Qk(t.fields?.aboveGrade),r=Kk(t.fields?.gla),n=n8(t.fields?.salePrice);return{id:t.id,address:t.address,salePrice:n??0,saleDate:"",gla:r??void 0,bedrooms:a??void 0,bathrooms:s??void 0,yearBuilt:void 0,lotSize:Xk(t.fields?.site)??void 0,garageSpaces:Zk(t.fields?.garageCarport),basementSqft:Jk(t.fields?.basement),condition:Qv(t.fields?.condition),quality:Qv(t.fields?.quality),elsScore:t.elsScore??void 0}}function c8(t){return[t.id,t.salePrice,t.gla??"",t.bedrooms??"",t.bathrooms??"",t.garageSpaces??"",t.basementSqft??"",t.lotSize??"",t.condition??"",t.quality??"",t.elsScore??""].join(":")}function d8(t){return[t.gla??"",t.bedrooms??"",t.bathrooms??"",t.garageSpaces??"",t.basementSqft??"",t.lotSize??"",t.condition??"",t.quality??"",t.elsScore??""].join(":")}function u8(t,a,s){const r=a.filter(u=>!s.has(u.id)),n=r.length,i=n>RS,l=i?r.slice(0,RS):r,c=o8(t),d=[];for(const u of l){const m=l8(u);m&&d.push(m)}i&&console.warn(`[ChipCascade] Visible grid comp count (${n}) exceeds the cascade cap of ${RS}; truncating to the first ${RS} rows for parity with the server compliance limit.`);const p=(c?d8(c):"no-subject")+"|"+d.map(c8).join("|");return{cascadeSubject:c,cascadeComps:d,signature:p,truncated:i,totalCount:n}}function VP(t){return t>=1e6?`$${(t/1e6).toFixed(2).replace(/\.?0+$/,"")}
15M`:`$${Math.round(t).toLocaleString()}`}function p8(t){return t<.1?`${Math.round(t*5280)} ft`:`${t.toFixed(2)} mi`}function m8(t){const a=t.fields?.gla;if(!a)return null;const s=a.value;return s==null||s===""?null:String(s)}function h8(){return e.jsx("div",{className:"w-full h-full flex items-center justify-center bg-slate-100","data-testid":"comp-photo-placeholder",children:e.jsxs("svg",{viewBox:"0 0 48 48",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"w-10 h-10 text-slate-300","aria-hidden":"true",children:[e.jsx("path",{d:"M6 22L24 6l18 16",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("rect",{x:"10",y:"22",width:"28",height:"20",rx:"1",stroke:"currentColor",strokeWidth:"3"}),e.jsx("rect",{x:"19",y:"30",width:"10",height:"12",rx:"1",stroke:"currentColor",strokeWidth:"2.5"})]})})}function f8({comp:t,compNum:a,salePrice:s,adjustedPrice:r,distance:n,anchor:i,mapWidth:l}){const c=i.x>l*.6,d={position:"absolute",top:i.y-8,...c?{right:l-i.x+16}:{left:i.x+16},zIndex:40,pointerEvents:"none",transform:"translateY(-50%)"},p=t.photoUrl?rb(t.photoUrl):null,u=m8(t);return e.jsx("div",{style:d,"data-testid":`comp-map-photo-card-${a}`,children:e.jsxs("div",{className:"w-52 bg-white rounded-lg shadow-xl border border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"relative w-full h-28 bg-slate-100",children:[p?e.jsx("img",{src:p,alt:`Comp ${a} photo`,className:"w-full h-full object-cover",onError:m=>{m.currentTarget.style.display="none"}}):e.jsx(h8,{}),e.jsx("div",{className:`absolute top-1.5 left-1.5 w-6 h-6 rounded-full bg-blue-600 border-2 border-white
16                       flex items-center justify-center text-white font-bold text-[11px] shadow`,"data-testid":`comp-map-badge-${a}`,children:a})]}),e.jsxs("div",{className:"px-2.5 py-2 space-y-0.5",children:[e.jsxs("div",{className:"text-[11px] font-semibold text-slate-800 truncate leading-tight","data-testid":`comp-map-address-${a}`,children:["Comp ",a," · ",t.address]}),e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-0.5 mt-1 text-[10px] text-slate-600",children:[s!=null&&e.jsxs("span",{"data-testid":`comp-map-sale-price-${a}`,children:[e.jsx("span",{className:"text-slate-400",children:"Sale "}),e.jsx("span",{className:"font-semibold text-slate-700",children:VP(s)})]}),r!=null&&r!==s&&e.jsxs("span",{"data-testid":`comp-map-adj-price-${a}`,children:[e.jsx("span",{className:"text-slate-400",children:"Adj "}),e.jsx("span",{className:"font-semibold text-emerald-700",children:VP(r)})]}),u&&e.jsxs("span",{"data-testid":`comp-map-gla-${a}`,children:[e.jsx("span",{className:"font-semibold text-slate-700",children:u}),e.jsx("span",{className:"text-slate-400",children:" sf"})]}),e.jsxs("span",{"data-testid":`comp-map-distance-${a}`,children:[e.jsx("span",{className:"text-slate-400",children:"· "}),e.jsx("span",{className:"font-semibold text-slate-700",children:p8(n)})]})]})]})]})})}function QT(t){const a=t.fields?.salePrice?.value;if(typeof a=="number")return a;
16if(typeof a=="string"){const s=parseFloat(a.replace(/[^0-9.-]/g,""));return isNaN(s)?null:s}return null}const g8=new Set(["netAdjustment","grossAdjustment","adjustedSalePrice"]);function $P(t,a){const s=QT(t);if(s===null)return null;if(!a)return s;const r=Object.entries(a).filter(([n])=>!g8.has(n)).reduce((n,[,i])=>n+(i||0),0);return s+r}function BP(t){return t>=1e6?`$${(t/1e6).toFixed(2).replace(/\.?0+$/,"")}M`:`$${Math.round(t).toLocaleString()}`}function ZT(t){return t<.1?`${Math.round(t*5280)} ft`:`${t.toFixed(2)} mi`}function ES(t,a,s,r){const i=(s-t)*Math.PI/180,l=(r-a)*Math.PI/180,c=Math.sin(i/2)**2+Math.cos(t*Math.PI/180)*Math.cos(s*Math.PI/180)*Math.sin(l/2)**2;return 3959*2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))}const zP={road:"mapbox://styles/mapbox/streets-v12",satellite:"mapbox://styles/mapbox/satellite-streets-v12"};function x8({subject:t,comps:a,adjustments:s,onSnapshotChange:r,onCompLocationUpdate:n,onCompClick:i}){const l=o.useRef(null),c=o.useRef(null),d=o.useRef([]),p=o.useRef(!1),u=o.useRef(null),[m,h]=o.useState(!1),[f,v]=o.useState(!0),S=EV(),N=o.useRef(null),[x,y]=o.useState(null),[b,j]=o.useState(null),[T,O]=o.useState(0),[E,R]=o.useState("road"),[G,U]=o.useState(null),[C,F]=o.useState(null),[A,M]=o.useState({}),[B,oe]=o.useState(null),[ae,D]=o.useState(null),_=o.useMemo(()=>a.filter(pe=>pe.lat!=null&&pe.lng!=null),[a]),$=t.lat!=null&&t.lng!=null,z=o.useMemo(()=>_.map(pe=>{const se=a.indexOf(pe),fe=QT(pe),ue=$P(pe,s?.[pe.id]),be=A[pe.id],H=be?.lat??pe.lat,ye=be?.lng??pe.lng,de=$?ES(t.lat,t.lng,H,ye):pe.distance??0;return{comp:pe,index:se>=0?se:0,salePrice:fe,adjustedPrice:ue,distance:de}}),[_,a,s,t,$,A]),V=o.useMemo(()=>G?z.find(pe=>pe.comp.id===G)??null:null,[G,z]);o.useEffect(()=>{if(E$()){v(!1);return}let pe=!1;const se=new AbortController;return w$(se.signal).then(()=>{pe||v(!1)}).catch(fe=>{pe||fe instanceof DOMException&&fe.name==="AbortError"||(y("Failed to load map"),v(!1))}),()=>{pe=!0,se.abort()}},[]),o.useEffect(()=>{if(!S||f||x||b||!l.current||c.current||!$)return;const pe=[t.lat,..._.map(de=>de.lat)],se=[t.lng,..._.map(de=>de.lng)],fe=pe.reduce((de,ge)=>de+ge,0)/pe.length,ue=se.reduce((de,ge)=>de+ge,0)/se.length,be=N.current,{map:H,error:ye}=P$({container:l.current,style:zP[E],center:be?.center??[ue,fe],zoom:be?.zoom??12,attributionControl:!1},"CompsSummaryMap");if(!H){j(ye);return}return H.addControl(new ox.NavigationControl,"top-right"),H.on("load",()=>{if(h(!0),!be&&_.length>0){const de=new ox.LngLatBounds;de.extend([t.lng,t.lat]),_.forEach(ge=>de.extend([ge.lng,ge.lat])),H.fitBounds(de,{padding:60,maxZoom:15})}}),c.current=H,()=>{try{const de=H.getCenter();N.current={center:[de.lng,de.lat],zoom:H.getZoom()}}catch{}d.current.forEach(de=>de.remove()),d.current=[],H.remove(),c.current=null,h(!1),p.current=!1,oe(null),D(null)}},[S,f,x,b,T,$]),o.useEffect(()=>{const pe=c.current;!pe||!m||(pe.setStyle(zP[E]),pe.once("style.load",()=>{p.current=!1,le()}))},[E]);const le=o.useCallback(()=>{const pe=c.current;if(!pe||!m||!$)return;d.current.forEach(ue=>ue.remove()),d.current=[];const se=document.createElement("div");se.className="comps-summary-subject-marker",se.innerHTML=`
17      <div style="
18        width: 36px; height: 36px; border-radius: 50%;
19        background: #d97706; border: 3px solid #fff;
20        box-shadow: 0 2px 8px rgba(0,0,0,0.3);
21        display: flex; align-items: center; justify-content: center;
22        color: white; font-weight: 700; font-size: 14px;
23      ">S</div>
24    `,se.setAttribute("data-testid","marker-subject");const fe=new ox.Marker({element:se,anchor:"center"}).setLngLat([t.lng,t.lat]).setPopup(new ox.Popup({offset:20}).setHTML(`<div style="font-size:12px;font-weight:600;max-width:200px">${t.address}</div><div style="font-size:11px;color:#666">Subject Property</div>`)).addTo(pe);d.current.push(fe),_.forEach(ue=>{const be=a.indexOf(ue),H=(be>=0?be:0)+1,ye=C===ue.id,de=A[ue.id],ge=de?.lng??ue.lng,Be=de?.lat??ue.lat,He=document.createElement("div");He.className="comps-summary-comp-marker",He.setAttribute("data-testid",`marker-comp-${H}`),He.style.cursor=ye?"grab":"pointer",He.innerHTML=`
25        <div style="
26          width: 28px; height: 28px; border-radius: 50%;
27          background: ${ye?"#059669":"#2563eb"}; border: 2.5px solid #fff;
28          box-shadow: 0 2px 6px rgba(0,0,0,0.25);
29          display: flex; align-items: center; justify-content: center;
30          color: white; font-weight: 700; font-size: 13px;
31          position: relative;
32          transition: background 0.15s;
33        ">${H}</div>
34      `;const Ie=new ox.Marker({element:He,anchor:"center",draggable:ye}).setLngLat([ge,Be]).addTo(pe);He.addEventListener("click",ce=>{ce.stopPropagation(),ye||(U(ue.id),i&&i(ue))}),He.addEventListener("mouseenter",()=>{const ce=c.current;if(!ce)return;const Pe=ce.project([ge,Be]),We=QT(ue),Re=$P(ue,s?.[ue.id]),ne=$?ES(t.lat,t.lng,Be,ge):ue.distance??0;oe({comp:ue,compNum:H,salePrice:We,adjustedPrice:Re,distance:ne}),D({x:Pe.x,y:Pe.y})}),He.addEventListener("mouseleave",()=>{oe(null),D(null)}),ye&&Ie.on("dragend",()=>{const ce=Ie.getLngLat();M(Pe=>({...Pe,[ue.id]:{lat:ce.lat,lng:ce.lng}}))}),d.current.push(Ie)});try{p.current&&(pe.getLayer("distance-lines")&&pe.removeLayer("distance-lines"),pe.getSource("distance-lines")&&pe.removeSource("distance-lines"),p.current=!1)}catch(ue){console.warn("[CompsSummaryMap] Error cleaning up distance-lines:",ue)}if(_.length>0){const ue=_.map(be=>{const H=A[be.id];return{type:"Feature",properties:{},geometry:{type:"LineString",coordinates:[[t.lng,t.lat],[H?.lng??be.lng,H?.lat??be.lat]]}}});try{pe.addSource("distance-lines",{type:"geojson",data:{type:"FeatureCollection",features:ue}}),pe.addLayer({id:"distance-lines",type:"line",source:"distance-lines",paint:{"line-color":"#94a3b8","line-width":1.5,"line-dasharray":[4,4]}}),p.current=!0}catch(be){console.warn("[CompsSummaryMap] Error adding distance-lines:",be)}_.forEach(be=>{const H=A[be.id],ye=H?.lat??be.lat,de=H?.lng??be.lng,ge=(t.lat+ye)/2,Be=(t.lng+de)/2,He=ES(t.lat,t.lng,ye,de),Ie=document.createElement("div");
34Ie.className="comps-distance-label",Ie.innerHTML=`<span style="
35          font-size: 10px; font-weight: 600; color: #475569;
36          background: rgba(255,255,255,0.92); padding: 1px 5px;
37          border-radius: 3px; border: 1px solid #e2e8f0;
38          white-space: nowrap;
39        ">${ZT(He)}</span>`;const ce=new ox.Marker({element:Ie,anchor:"center"}).setLngLat([Be,ge]).addTo(pe);d.current.push(ce)})}},[m,t,_,a,C,A,s,$,i]);o.useEffect(()=>{le()},[le]);const W=o.useCallback(()=>{const pe=c.current;if(!pe||!$||!r)return;const se=pe.getCenter(),fe=pe.getZoom(),ue=pe.getBounds(),be={viewport:{center:{lat:se.lat,lng:se.lng},zoom:fe,bounds:ue?{north:ue.getNorth(),south:ue.getSouth(),east:ue.getEast(),west:ue.getWest()}:void 0},subject:{lat:t.lat,lng:t.lng,address:t.address},comps:z.map(ye=>({id:ye.comp.id,lat:A[ye.comp.id]?.lat??ye.comp.lat,lng:A[ye.comp.id]?.lng??ye.comp.lng,address:ye.comp.address,index:ye.index,distance:ye.distance,salePrice:ye.salePrice,adjustedPrice:ye.adjustedPrice}))},H=JSON.stringify(be);H!==u.current&&(u.current=H,r(be))},[t,z,$,r,A]);o.useEffect(()=>{const pe=c.current;if(!pe||!m)return;W();const se=()=>W();return pe.on("moveend",se),()=>{pe.off("moveend",se)}},[m,W]);const me=pe=>{if(C===pe){const se=A[pe];if(se&&$&&n){const fe=ES(t.lat,t.lng,se.lat,se.lng);n(pe,se.lat,se.lng,fe)}F(null)}else F(pe)},Z=pe=>{M(se=>{const fe={...se};return delete fe[pe],fe}),F(null)};return $?f?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"text-sm text-slate-500",children:"Loading map..."})}):x?e.jsx("div",{className:"flex items-center justify-center h-full text-slate-400",children:e.jsx("div",{className:"text-sm",children:x})}):b?e.jsx(O$,{className:"h-full",style:{minHeight:"300px"},testId:"comps-summary-map-init-error",onRetry:()=>{j(null),O(pe=>pe+1)}}):e.jsxs("div",{className:"flex flex-col h-full relative","data-testid":"comps-summary-map",children:[e.jsxs("div",{className:"absolute top-3 left-3 z-20 flex items-center gap-1 bg-white/95 rounded-lg border border-slate-200 shadow-sm p-0.5","data-testid":"map-style-toggle",children:[e.jsxs("button",{onClick:()=>R("road"),className:Q("flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium transition-colors",E==="road"?"bg-blue-600 text-white shadow-sm":"text-slate-600 hover:bg-slate-100"),"data-testid":"button-map-road",children:[e.jsx(mN,{className:"w-3.5 h-3.5"}),"Road"]}),e.jsxs("button",{onClick:()=>R("satellite"),className:Q("flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium transition-colors",E==="satellite"?"bg-blue-600 text-white shadow-sm":"text-slate-600 hover:bg-slate-100"),"data-testid":"button-map-satellite",children:[e.jsx(E5,{className:"w-3.5 h-3.5"}),"Satellite"]})]}),e.jsx("div",{ref:l,className:"flex-1 min-h-0",style:{minHeight:"300px"}}),B&&ae&&e.jsx(f8,{comp:B.comp,compNum:B.compNum,salePrice:B.salePrice,adjustedPrice:B.adjustedPrice,distance:B.distance,anchor:ae,mapWidth:l.current?.clientWidth??0}),V&&!i&&e.jsx(b8,{comp:V.comp,index:V.index,distance:V.distance,salePrice:V.salePrice,adjustedPrice:V.adjustedPrice,isDragging:C===V.comp.id,hasDraggedPosition:!!A[V.comp.id],onClose:()=>{C===V.comp.id&&Z(V.comp.id),U(null)},onToggleDrag:()=>me(V.comp.id),onCancelDrag:()=>Z(V.comp.id)}),V&&i&&e.jsxs("div",{className:"absolute bottom-4 left-4 z-30 bg-white rounded-lg shadow-xl border border-slate-200 px-3 py-2 flex items-center gap-2","data-testid":`drag-controls-comp-${V.index+1}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-slate-600",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-blue-600 text-white flex items-center justify-center font-bold text-[11px]",children:V.index+1}),e.jsxs("span",{className:"font-medium",children:["Comp ",V.index+1]}),e.jsx("span",{className:"text-slate-400",children:"·"}),e.jsx("span",{className:"text-[10px] text-slate-400",children:ZT(V.distance)})]}),C===V.comp.id?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>me(V.comp.id),className:"flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-medium bg-emerald-600 text-white hover:bg-emerald-700 transition-colors","data-testid":`button-lock-comp-${V.index+1}`,children:[e.jsx(Hr,{className:"w-3 h-3"}),"Lock"]}),e.jsx("button",{onClick:()=>Z(V.comp.id),className:"flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-medium bg-slate-100 text-slate-600 hover:bg-slate-200 transition-colors","data-testid":`button-cancel-drag-${V.index+1}`,children:"Cancel"})]}):e.jsxs("button",{onClick:()=>me(V.comp.id),className:"flex items-center gap-1 px-2.5 py-1 rounded-md text-xs font-medium bg-slate-100 text-slate-600 hover:bg-slate-200 transition-colors","data-testid":`button-move-comp-${V.index+1}`,children:[e.jsx(lf,{className:"w-3 h-3"}),"Adjust Location"]}),e.jsx("button",{onClick:()=>U(null),className:"p-0.5 rounded hover:bg-slate-100 text-slate-400 hover:text-slate-600 transition-colors","data-testid":`button-close-drag-control
39s-${V.index+1}`,children:e.jsx(ur,{className:"w-3.5 h-3.5"})})]})]}):e.jsx("div",{className:"flex flex-col items-center justify-center h-full text-slate-400 gap-2","data-testid":"map-no-coords",children:e.jsx("div",{className:"text-sm font-medium",children:"No coordinates available for subject property"})})}function b8({comp:t,index:a,distance:s,salePrice:r,adjustedPrice:n,isDragging:i,hasDraggedPosition:l,onClose:c,onToggleDrag:d,onCancelDrag:p}){const u=a+1,m=t.fields||{},h=f=>{const v=m[f];return!v||v.value==null||v.value===""?"—":String(v.value)};return e.jsxs("div",{className:"absolute bottom-4 left-4 z-30 w-80 bg-white rounded-xl shadow-2xl border border-slate-200 overflow-hidden","data-testid":`comp-modal-${u}`,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-slate-50 border-b border-slate-200",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-600 text-white flex items-center justify-center font-bold text-sm",children:u}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-semibold text-slate-800",children:["Comp ",u]}),e.jsxs("div",{className:"text-[10px] text-slate-500",children:[ZT(s)," from subject"]})]})]}),e.jsx("button",{onClick:c,className:"p-1 rounded-md hover:bg-slate-200 text-slate-400 hover:text-slate-600 transition-colors","data-testid":`button-close-comp-modal-${u}`,children:e.jsx(ur,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"px-4 py-3 space-y-2",children:[e.jsx("div",{className:"text-xs font-medium text-slate-800 truncate",children:t.address}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-[11px]",children:[r!=null&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-400",children:"Sale Price"}),e.jsx("span",{className:"text-right font-medium text-slate-700",children:BP(r)})]}),n!=null&&n!==r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-400",children:"Adj. Price"}),e.jsx("span",{className:"text-right font-medium text-emerald-700",children:BP(n)})]}),e.jsx("span",{className:"text-slate-400",children:"GLA"}),e.jsxs("span",{className:"text-right font-medium text-slate-700",children:[h("gla")," sf"]}),e.jsx("span",{className:"text-slate-400",children:"Beds / Baths"}),e.jsxs("span",{className:"text-right font-medium text-slate-700",children:[h("bedrooms")," / ",h("bathrooms")]}),e.jsx("span",{className:"text-slate-400",children:"Year Built"}),e.jsx("span",{className:"text-right font-medium text-slate-700",children:h("yearBuilt")}),e.jsx("span",{className:"text-slate-400",children:"Lot Size"}),e.jsx("span",{className:"text-right font-medium text-slate-700",children:h("lotSize")}),e.jsx("span",{className:"text-slate-400",children:"$/GLA"}),e.jsx("span",{className:"text-right font-medium text-slate-700",children:h("pricePerSqft")})]})]}),e.jsx("div",{className:"px-4 py-2.5 border-t border-slate-100 flex items-center gap-2",children:i?e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:d,className:"flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium bg-emerald-600 text-white hover:bg-emerald-700 transition-colors","data-testid":`button-lock-comp-${u}`,children:[e.jsx(Hr,{className:"w-3.5 h-3.5"}),"Lock Position"]}),e.jsx("button",{onClick:p,className:"flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium bg-slate-100 text-slate-600 hover:bg-slate-200 transition-colors","data-testid":`button-cancel-drag-${u}`,children:"Cancel"})]}):e.jsxs("button",{onClick:d,className:"flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium bg-slate-100 text-slate-600 hover:bg-slate-200 transition-colors","data-testid":`button-move-comp-${u}`,children:[e.jsx(lf,{className:"w-3.5 h-3.5"}),"Adjust Location"]})})]})}const qP=[{rowId:"NeighborhoodName",label:"Neighborhood Name",description:"Name of the neighborhood where the property is located"},{rowId:"ProjectName",label:"Project Name",description:"Name of the condo project, PUD, or cooperative"},{rowId:"PropertyInProjectIndicator",label:"In PUD / Project",description:"Whether the property is part of a PUD, condo, or co-op project"},{rowId:"ProjectCommonAmenitiesServicesDescription",label:"Project Amenities/Services",description:"Common amenities or services included in the project (pool, doorman, etc.)"},{rowId:"SiteInfluenceType",label:"Site Influence",description:"External factors influencing site value (golf, water, etc.)"},{rowId:"ViewType",label:"View",description:"View from the unit (city, water, golf, etc.)"},{rowId:"FloorNumber",label:"Floor Number",description:"Floor level of the unit within the building"},{rowId:"SiteAreaMeasure",label:"Site Size (SF)",description:"Land area of the rental property site (common-interest properties)"},{rowId:"GradeLevelType",label:"Grade Level",description:"Above-grade, at-grade, or below-grade unit placement"},{rowId:"InteriorConditionRatingCode",label:"Interior Condition",description:"Condition rating of the unit interior (C1–C6)"},{rowId:"UnitFurnishedIndicator",label:"Furnished",description:"Whether the unit is rented furnished"},{rowId:"UnitChargesIncludeUtilitiesIndicator",label:"Utilities Included",description:"Whether charges include utilities or services (gas, electric, etc.)"},{rowId:"RentControlStatusType",label:"Rent Control",description:"Rent control status of the unit (subject to, exempt, etc.)"},{rowId:"FinancialRentalConcessionIndicator",label:"Rent Concessions",de
39scription:"Whether the landlord offered rent-free periods or other concessions"},{rowId:"RentalUnitToSubjectComparisonType",label:"Overall Comparison",description:"Overall rating of this comp vs the subject unit"}];function y8({selectedRelRowIds:t,existingCustomRowCount:a,onAdd:s,onRemove:r,onAddCustomRow:n,visibilityCtx:i,disabled:l=!1}){const[c,d]=o.useState(!1),[p,u]=o.useState(""),m=o.useRef(null),h=a<ev,f=(y,b)=>{b?s(y):r(y)},v=()=>{const y=p.trim();!y||!h||(n(y),u(""),m.current?.focus())},S=t.size+a,N=qP.filter(y=>t.has(y.rowId)),x=qP.filter(y=>!t.has(y.rowId));return e.jsxs(xn,{open:c,onOpenChange:d,children:[e.jsx(bn,{asChild:!0,children:e.jsxs(De,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs gap-1",disabled:l,"data-testid":"btn-rental-add-row",children:[e.jsx(un,{className:"w-3 h-3"}),"Optional rows",S>0&&e.jsx("span",{className:"ml-0.5 rounded-full bg-slate-200 px-1.5 py-0 text-[10px] font-medium tabular-nums",children:S}),e.jsx(Rr,{className:"w-3 h-3 ml-0.5 text-muted-foreground"})]})}),e.jsxs(yn,{className:"w-80 p-0",align:"end","data-testid":"popover-rental-row-picker",children:[e.jsxs("div",{className:"p-3 space-y-2.5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"UAD 3.6 optional rows"}),x.map(y=>{const b=aU(y.rowId,i),j=b?null:sU(y.rowId,i);return e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx(Pa,{id:`rental-rel-${y.rowId}`,checked:!1,disabled:!b,onCheckedChange:T=>{T===!0&&f(y.rowId,!0)},"data-testid":`chk-rental-rel-${y.rowId}`,className:"mt-0.5 shrink-0"}),e.jsxs("label",{htmlFor:`rental-rel-${y.rowId}`,className:"flex flex-col cursor-pointer select-none flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm font-medium leading-tight",children:y.label}),!b&&j&&e.jsx(kt,{className:"bg-amber-100 text-amber-700 border-amber-200 text-[10px] px-1.5 py-0 font-medium","data-testid":`badge-gated-rental-${y.rowId}`,children:"not yet applicable"})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight mt-0.5",children:!b&&j?j:y.description})]})]},y.rowId)})]}),N.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Rv,{}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Already added"}),N.map(y=>e.jsxs("div",{className:"flex items-start gap-2.5 bg-muted/40 rounded px-2 py-1.5",children:[e.jsx(Pa,{id:`rental-rel-added-${y.rowId}`,checked:!0,onCheckedChange:b=>{b===!1&&f(y.rowId,!1)},"data-testid":`chk-rental-rel-${y.rowId}`,className:"mt-0.5 shrink-0"}),e.jsxs("label",{htmlFor:`rental-rel-added-${y.rowId}`,className:"flex flex-col cursor-pointer select-none",children:[e.jsx("span",{className:"text-sm font-medium leading-tight text-muted-foreground",children:y.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight mt-0.5",children:"Already added to this grid."})]})]},y.rowId))]})]}),e.jsx(Rv,{}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:["Custom rows"," ",e.jsxs("span",{className:"normal-case font-normal",children:["(",a,"/",ev," used)"]})]}),h?e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(ze,{ref:m,value:p,onChange:y=>u(y.target.value),placeholder:"Row label (max 21 chars)",maxLength:21,className:"h-7 text-xs flex-1","data-testid":"input-rental-custom-row-label",onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),v())}}),e.jsx(De,{type:"button",size:"sm",className:"h-7 px-2 text-xs shrink-0",disabled:!p.trim(),onClick:v,"data-testid":"btn-rental-add-custom-row",children:"Add"})]}):e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Maximum of ",ev," custom rows reached."]})]})]})]})}function lb(t,a,s,r){const i=(s-t)*Math.PI/180,l=(r-a)*Math.PI/180,c=Math.sin(i/2)**2+Math.cos(t*Math.PI/180)*Math.cos(s*Math.PI/180)*Math.sin(l/2)**2;return 3958.8*2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))}function eM(t,a,s,r){const n=(r-a)*Math.PI/180,i=t*Math.PI/180,l=s*Math.PI/180,c=Math.cos(l)*Math.sin(n),d=Math.cos(i)*Math.sin(l)-Math.sin(i)*Math.cos(l)*Math.cos(n);return(Math.atan2(c,d)*180/Math.PI+360)%360}function tM(t){return["North","NorthEast","East","SouthEast","South","SouthWest","West","NorthWest"][Math.round(t/45)%8]}function oC(t,a,s){return a===s?Math.round(t*100)/100:a==="Miles"&&s==="Kilometers"?Math.round(t*1.60934*100)/100:Math.round(t/1.60934*100)/100}
39function S8(t,a,s,r,n){const i={distance:null,unit:"Miles",direction:null};if(t==null||a==null||s==null||r==null)return i;if(typeof n=="number"&&n!==0)return{distance:n,unit:"Miles",direction:null};const l=Math.round(lb(t,a,s,r)*100)/100,c=eM(t,a,s,r),d=l>0?tM(c):null;return{distance:l,unit:"Miles",direction:d}}const v8=Object.freeze(Object.defineProperty({__proto__:null,bearingDegrees:eM,bearingToDirectionToken:tM,convertProximityDistance:oC,getProximityFields:S8,haversineMiles:lb},Symbol.toStringTag,{value:"Module"}));function Aj(t){return Array.isArray(t)?t.filter(a=>typeof a=="number"&&a>0):typeof t=="number"&&t>0?[t]:[]}function N8(t){return t.length===0?"—":t.length===1?`Unit ${t[0]}`:`Units ${t.join(", ")}`}function A8({selectedUnits:t,maxUnits:a,onChange:s,disabled:r,disabledUnits:n=[],testId:i}){const l=c=>{const d=t.includes(c)?t.filter(p=>p!==c):[...t,c].sort((p,u)=>p-u);s(d.length?d:[])};return e.jsxs(xn,{children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:r,"data-testid":i,className:"flex items-center gap-1 h-6 rounded border border-slate-200 bg-white px-1.5 text-xs text-slate-700 disabled:opacity-50 hover:border-slate-300",children:[e.jsx("span",{className:"flex-1 text-left",children:N8(t)}),e.jsx(Rr,{className:"h-3 w-3 text-slate-400 shrink-0"})]})}),e.jsx(yn,{align:"start",className:"p-2 w-36 space-y-1",children:Array.from({length:a},(c,d)=>d+1).map(c=>{const d=n.includes(c)&&!t.includes(c);return e.jsxs("label",{className:`flex items-center gap-2 text-sm select-none ${d?"cursor-not-allowed opacity-40":"cursor-pointer"}`,children:[e.jsx(Pa,{checked:t.includes(c),onCheckedChange:()=>!d&&l(c),disabled:r||d,id:`${i}-unit-${c}`}),e.jsxs("span",{children:["Unit ",c,d?" (full)":""]})]},c)})})]})}function wc(t){if(t==null||t==="")return null;const a=Number(t);return Number.isFinite(a)?a:null}function Ro(t){return t==null?"":String(t)}function j8(t){if(typeof t!="string")return null;const a=t.match(/^([\d.]+)\s*(Miles?|Kilometers?|Km?)$/i);if(!a)return null;const s=parseFloat(a[1]);if(!Number.isFinite(s))return null;const n=a[2].toLowerCase().startsWith("k")?"Kilometers":"Miles";return{dist:s,unit:n}}function T8({n:t,section:a,fieldName:s,readOnly:r,types:n,identifiers:i,customDescription:l,getFieldMeta:c,onToggle:d,onSetIdentifier:p,onSetCustomDescription:u}){const[m,h]=o.useState(!1),[f,v]=o.useState(""),S=o.useRef(null);o.useEffect(()=>{if(!m)return;const b=j=>{S.current&&!S.current.contains(j.target)&&h(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[m]);const N=()=>{const b=f.trim();!b||n.includes("Other")||(d("Other",!0),u(b),v(""))},x=b=>aV[b]??b,y=n.includes("Other");return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:a,field:s,getFieldMeta:c}),e.jsxs("div",{className:"relative",ref:S,children:[e.jsxs("button",{type:"button",className:"w-full text-left text-xs border rounded px-2 py-1 bg-white hover:bg-slate-50 flex items-center justify-between",onClick:()=>h(b=>!b),disabled:r,"data-testid":`btn-comp${t}-datasource`,children:[e.jsx("span",{className:"truncate",children:n.length===0?e.jsx("span",{className:"text-slate-400",children:"Select…"}):n.map(b=>{const j=i[b],T=x(b);return j?`${T} ${j}`:T}).join(" | ")}),e.jsx(Rr,{className:"w-3 h-3 shrink-0 ml-1 text-slate-400"})]}),m&&!r&&e.jsxs("div",{className:"absolute z-20 top-full left-0 mt-1 w-64 bg-white border rounded shadow-lg text-xs",children:[e.jsx("div",{className:"max-h-52 overflow-y-auto",children:eV.map(b=>{const j=n.includes(b);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-1.5 hover:bg-slate-50 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:T=>d(b,T.target.checked),className:"h-3 w-3"}),e.jsx("span",{children:x(b)})]},b)})}),e.jsxs("div",{className:"border-t p-2 flex gap-1",children:[e.jsx(ze,{value:f,onChange:b=>v(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),N())},placeholder:"Custom source…",className:"h-6 text-xs flex-1","data-testid":`input-comp${t}-datasource-custom`}),e.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-slate-100 hover:bg-slate-200 rounded",onClick:N,"data-testid":`btn-comp${t}-datasource-custom-add`,children:"Add"})]})]})]}
39),y&&e.jsx(ze,{value:l,onChange:b=>u(b.target.value.slice(0,50)),placeholder:"Other source description",className:"h-6 text-xs mt-1",disabled:r,"data-testid":`input-comp${t}-datasource-other-desc`}),n.map(b=>e.jsx("div",{className:"mt-1",children:e.jsx(ze,{value:i[b]??"",onChange:j=>p(b,j.target.value.slice(0,tV)),placeholder:b==="MLS"?"MLS # (required)":`${x(b)} # (if available)`,className:`h-6 text-xs ${b==="MLS"&&!i[b]?"border-amber-400":""}`,disabled:r,"data-testid":`input-comp${t}-datasource-id-${b}`})},b))]})}const I8=new Set(["BedroomCount","FullBathroomCount","HalfBathroomCount","UnitTotalFinishedAreaMeasure","FloorNumber","ViewType","InteriorConditionRatingCode","UnitFurnishedIndicator","UnitChargesIncludeUtilitiesIndicator","RentControlStatusType","FinancialRentalConcessionIndicator","LeaseStartDate","GradeLevelType","ActualRentPerUnitFinishedAreaAmount","UnitMonthlyActualRentAmount","RentalUnitToSubjectComparisonType","RentalUnitAdjustedRentAmount","UnitMonthlyMarketRentAmount","ComparableWeightType"]);function C8({formData:t,updateField:a,getFieldValue:s,getFieldMeta:r,readOnly:n=!1,unitCount:i,subjectPrefill:l,visibilityCtx:c,incomeApproachActive:d=!1,maxComps:p}){const u=DE,{inspecting:m}=fc(),[h,f]=o.useState("properties"),[v,S]=o.useState(1),N=Ie=>{f(Ie),Ie==="unit-analysis"&&S(1)},x=Math.min(Zy,p??Zy),y=wc(s(u,"CompCount")),[b,j]=o.useState(y&&y>0?y:HU),T=Math.min(x,Math.max(0,b)),O=Ie=>{const ce=Math.min(x,Math.max(0,Ie));j(ce),a(u,"CompCount",ce)},E=Math.max(1,Math.min(4,Math.max(l?.UnitCount??1,i??1))),R=o.useMemo(()=>new Set(WU.map(Ie=>Ie.rowId).filter(Ie=>{const ce=s(u,`_relRow_${Ie}`);return ce===!0||ce==="true"})),[t,u]),G=Ie=>{a(u,`_relRow_${Ie}`,!0)},U=Ie=>{a(u,`_relRow_${Ie}`,!1)},C=o.useMemo(()=>{const Ie=s(u,"_rentalCustomRowDefs");return Array.isArray(Ie)?Ie.filter(ce=>!!ce&&typeof ce.label=="string").slice(0,ev):[]},[t,u]),F=Ie=>{const ce=[...C,{label:Ie}];a(u,"_rentalCustomRowDefs",ce.map(Pe=>({label:Pe.label})))},A=Ie=>{const ce=C.filter((We,Re)=>Re!==Ie);a(u,"_rentalCustomRowDefs",ce.map(We=>({label:We.label})));const Pe=C.length-1;for(let We=Ie;We<Pe;We++){const Re=s(u,Fd(`_rentalCustomSubjectRow${We+1}`));a(u,Fd(`_rentalCustomSubjectRow${We}`),Re);for(let ne=1;ne<=Zy;ne++){const Me=s(u,`_rentalCustomComp${ne}Row${We+1}`);a(u,`_rentalCustomComp${ne}Row${We}`,Me)}}a(u,Fd(`_rentalCustomSubjectRow${Pe}`),null);for(let We=1;We<=Zy;We++)a(u,`_rentalCustomComp${We}Row${Pe}`,null)},M=(Ie,ce)=>{Uk(t,u,Ie,ce,a)},B=Ie=>{const ce=t[u]??{},Pe=Lk(ce,Ie,T,u);for(const{field:We,value:Re}of Pe)a(u,We,Re);O(Math.max(0,T-1))},oe=Array.from({length:T},(Ie,ce)=>ce+1),ae=o.useMemo(()=>oe.filter(Ie=>Aj(s(u,Qy(Ie))).includes(v)),[T,v,t]),D=h==="unit-analysis"?ae:oe,_=o.useRef(new Set),$=o.useMemo(()=>c??rU(t,{useIncomeApproach:d},T),[c,t,d,T]),z=o.useMemo(()=>{const Ie=[];for(const ce of KU)ce.rowId!=="AdditionalComparisonLineItemDescription"&&(ce.class==="REL"&&!R.has(ce.rowId)||h==="unit-analysis"&&!I8.has(ce.rowId)||Ie.push(ce));return Ie},[R,h]),V=o.useMemo(()=>{const Ie={};for(let ce=1;ce<=T;ce++){const Pe=s(u,Qy(ce)),We=Aj(Pe);for(const Re of We)Ie[Re]=(Ie[Re]??0)+1}return Ie},[T,t]),le=Ie=>{const ce=s(u,Vn("DataSourceTypes",Ie));return Array.isArray(ce)?ce:[]},W=Ie=>{const ce=s(u,Vn("DataSourceIdentifiers",Ie));return ce&&typeof ce=="object"&&!Array.isArray(ce)?ce:{}},me=Ie=>Ro(s(u,Vn("DataSourceTypeOtherDescription",Ie))),Z=(Ie,ce,Pe)=>{const We=le(Ie),Re=Pe?[...We,ce]:We.filter(ne=>ne!==ce);a(u,Vn("DataSourceTypes",Ie),Re)},pe=(Ie,ce,Pe)=>{const Re={...W(Ie),[ce]:Pe};a(u,Vn("DataSourceIdentifiers",Ie),Re)},se=(Ie,ce)=>{a(u,Vn("DataSourceTypeOtherDescription",Ie),ce)},fe=(Ie,ce)=>{const Pe=s(Ie,ce);if(Pe!==""&&Pe!==null&&Pe!==void 0)return Pe;const We=Object.entries(XU).find(([,Re])=>Re===ce);return We?s(Ie,We[0]):Pe},ue=Ie=>{if(Ie==="subject"){const Re=wc(s(u,Fd("UnitMonthlyActualRentAmount"))),ne=wc(l?.UnitTotalFinishedAreaMeasure??fe(u,Fd("UnitTotalFinishedAreaMeasure")));return kE(Re,ne)}const ce=Ie,Pe=wc(s(u,Vn("UnitMonthlyActualRentAmount",ce))),We=wc(fe(u,Vn("UnitTotalFinishedAreaMeasure",ce)));return kE(Pe,We)};o.useEffect(()=>{for(let Ie=1;Ie<=T;Ie++){const ce=ue(Ie),Pe=wc(s(u,Vn("ActualRentPerUnitFinishedAreaAmount",Ie)));ce!==Pe&&a(u,Vn("ActualRentPerUnitFinishedAreaAmount",Ie),ce)}},[t,T]);const be=Ie=>{if(Ie.subjectGray)return e.jsx("td",{className:"border border-slate-200 bg-slate-100/60 p-2",children:e.jsx("div",{className:"h-6 flex items-center justify-center",children:e.jsx("span",{className:"text-xs text-slate-300 select-none",children:"—"})})});if(Ie.computed&&Ie.rowId==="ActualRentPerUnitFinishedAreaAmount"){const We=ue("subject");return e.jsx("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:e.jsx("div",{className:"h-6 flex items-center text-xs text-muted-foreground","data-testid":"text-subject-ActualRentPerUnitFinishedAreaAmount",children:We!==null?`$${We.toFixed(2)}`:"—"})})}if(Ie.rowId==="NeighborhoodName"){const We=Ro(l?.NeighborhoodName??s(u,Fd("NeighborhoodName")));return e.jsx("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:e.jsx("div",{className:"h-6 flex items-center text-xs","data-testid":"text-subject-NeighborhoodName",children:We||e.jsx("span",{className:"text-slate-400",children:"—"})})})}if(Ie.rowId==="AddressLineText"){const We=Ro(l?.AddressLineText??s(u,Fd("AddressLineText")));return e.jsx("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:e.jsx("div",{className:"text-xs","data-testid":"text-subject-AddressLineText",children:We||e.jsx("span",{className:"text-slate-400",children:"—"})})})}if(Ie.rowId==="UnitTotalFinishedAreaMeasure"){const We=l?.UnitTotalFinishedAreaMeasure??wc(fe(u,Fd("UnitTotalFinishedAreaMeasure")));return e.jsx("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:e.jsx("div",{className:"h-6 flex items-center text-xs","data-testid":"text-subject-UnitTotalFinishedAreaMeasure",children:We!==null?We.toLocaleStr
39ing():e.jsx("span",{className:"text-slate-400",children:"—"})})})}const ce=Fd(Ie.rowId),Pe=Ro(s(u,ce));if(Ie.inputType==="boolean"){const We=Pe==="true"||Pe==="Yes"||Pe==="yes"?"true":Pe==="false"||Pe==="No"||Pe==="no"?"false":"";return e.jsx("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:e.jsxs("select",{value:We,onChange:Re=>a(u,ce,Re.target.value==="true"?!0:Re.target.value==="false"?!1:null),disabled:n,className:"w-full text-xs border-0 bg-transparent focus:outline-none focus:ring-1 focus:ring-blue-300 rounded","data-testid":`select-subject-${Ie.rowId}`,children:[e.jsx("option",{value:"",children:"—"}),e.jsx("option",{value:"true",children:"Yes"}),e.jsx("option",{value:"false",children:"No"})]})})}if(Ie.inputType==="enum")return e.jsxs("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:[e.jsx(vo,{section:u,field:ce,getFieldMeta:r}),e.jsx(ze,{type:"text",value:Pe,onChange:We=>a(u,ce,We.target.value||null),disabled:n,className:"h-7 text-xs","data-testid":`input-subject-${Ie.rowId}`})]});if(Ie.inputType==="amount"||Ie.inputType==="number"){const We=wc(s(u,ce));return e.jsxs("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:[e.jsx(vo,{section:u,field:ce,getFieldMeta:r}),e.jsx(ze,{type:"number",value:We==null?"":String(We),onChange:Re=>{const ne=Re.target.value===""?null:Number(Re.target.value);a(u,ce,Number.isFinite(ne)?ne:null)},disabled:n,className:"h-7 text-xs","data-testid":`input-subject-${Ie.rowId}`})]})}return e.jsxs("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:[e.jsx(vo,{section:u,field:ce,getFieldMeta:r}),e.jsx(ze,{type:"text",value:Pe,onChange:We=>a(u,ce,We.target.value||null),disabled:n,maxLength:Ie.maxLength,className:"h-7 text-xs","data-testid":`input-subject-${Ie.rowId}`})]})},H=(Ie,ce)=>{const Pe=Vn(Ie.rowId,ce);if(Ie.compGray)return e.jsx("td",{className:"border border-slate-200 bg-slate-100/60 p-2",children:e.jsx("div",{className:"h-6 flex items-center justify-center",children:e.jsx("span",{className:"text-xs text-slate-300 select-none",children:"—"})})},ce);if(Ie.computed&&Ie.rowId==="ActualRentPerUnitFinishedAreaAmount"){const Re=ue(ce);return e.jsx("td",{className:"border border-slate-200 p-2",children:e.jsx("div",{className:"h-6 flex items-center text-xs text-muted-foreground tabular-nums","data-testid":`text-comp${ce}-ActualRentPerUnitFinishedAreaAmount`,children:Re!==null?`$${Re.toFixed(2)}`:"—"})},ce)}if(Ie.rowId==="DataSource")return e.jsx(T8,{n:ce,section:u,fieldName:Pe,readOnly:n,types:le(ce),identifiers:W(ce),customDescription:me(ce),getFieldMeta:r,onToggle:(Re,ne)=>Z(ce,Re,ne),onSetIdentifier:(Re,ne)=>pe(ce,Re,ne),onSetCustomDescription:Re=>se(ce,Re)},ce);if(Ie.rowId==="ProximityToSubjectDistanceLinearMeasure"){const Re=s(u,Vn("ProximityToSubjectDistanceLinearMeasure",ce)),ne=j8(Re),Me=ne!=null?ne.dist:wc(Re),Tt=Ro(s(u,Vn("LinearUnitOfMeasureType",ce)))||(ne?.unit??"Miles"),je=Ro(s(u,Vn("ComparableToSubjectDirectionType",ce)));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ze,{type:"number",step:"0.01",min:"0",value:Me==null?"":String(Me),onChange:Le=>{_.current.add(ce);const ut=Le.target.value===""?null:Number(Le.target.value);a(u,Vn("ProximityToSubjectDistanceLinearMeasure",ce),ut)},disabled:n,className:"h-6 text-xs w-16","data-testid":`input-comp${ce}-proximity-distance`}),e.jsx("select",{value:Tt,onChange:Le=>{_.current.add(ce);const ut=Le.target.value;if(Me!=null){const st=oC(Me,Tt,ut);a(u,Vn("ProximityToSubjectDistanceLinearMeasure",ce),st)}a(u,Vn("LinearUnitOfMeasureType",ce),ut)},disabled:n,className:"text-xs border rounded px-1 h-6 bg-white","data-testid":`select-comp${ce}-proximity-unit`,children:QU.map(Le=>e.jsx("option",{value:Le.value,children:Le.label},Le.value))})]}),(Me==null||Me>0)&&e.jsxs("select",{value:je,onChange:Le=>{_.current.add(ce),a(u,Vn("ComparableToSubjectDirectionType",ce),Le.target.value||null)},disabled:n,className:"mt-1 text-xs border rounded px-1 h-6 bg-white w-full","data-testid":`select-comp${ce}-proximity-direction`,children:[e.jsx("option",{value:"",children:"—"}),ZU.map(Le=>e.jsx("option",{value:Le.value,children:Le.label},Le.value))]})]},ce)}if(Ie.rowId==="ComparableWeightType"){const Re=Ro(s(u,Pe)),ne=!Re;return e.jsx("td",{className:`border p-2 align-top ${ne?"border-red-300 bg-red-50":"border-slate-200"}`,"data-testid":`warn-comp${ce}-weight`,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:JU.map(Me=>e.jsx("button",{type:"button",disabled:n,onClick:()=>a(u,Pe,Re===Me.value?null:Me.value),className:`px-2 py-0.5 rounded text-xs border transition-colors ${Re===Me.value?"bg-blue-600 text-white border-blue-600":"bg-white text-slate-700 border-slate-300 hover:border-blue-400"}`,"data-testid":`pill-comp${ce}-weight-${Me.value}`,children:Me.label},Me.value))})},ce)}if(Ie.rowId==="LeaseStartDate"){const Re=Ro(s(u,Pe));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsx(L$,{value:Re,onChange:ne=>a(u,Pe,ne||null),testId:`input-comp${ce}-LeaseStartDate`})]},ce)}if(Ie.rowId==="UnitMonthlyActualRentAmount"){const Re=wc(s(u,Pe));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsx(ze,{type:"number",step:"1",min:"0",value:Re==null?"":String(Re),onChange:ne=>{const Me=ne.target.value===""?null:Math.round(Number(ne.target.value));a(u,Pe,Number.isFinite(Me)?Me:null)},disabled:n,className:"h-7 text-xs","data-testid":`input-comp${ce}-${Ie.rowId}`})]},ce)}if(Ie.inputType==="boolean"){const Re=s(u,Pe),ne=Re===!0||Re==="true"||Re==="Yes"?"true":Re===!1||Re==="false"||Re==="No"?"false":"";return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsxs("select",{value:ne,onChange:Me=>a(u,Pe,Me.target.value==="true"?!0:Me.target.value==="false"?!1:null),disabled:n,className:"w-full text-xs border rounded px-1 h-7 bg-white","data-testid":`select-comp${ce}-${Ie.rowId}`,children:[e.jsx("option",{value:"",children:"—"}),e.jsx("option",{value:"true",children:"Yes"}),e.jsx("option",{value:"false",children:"No"})]})]},ce)}if(Ie.rowId==="UnitTotalFinishedAreaMeasure"){const Re=wc(fe(u,Pe));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsx(ze,{type:"number",step:"1",min:"0",value:Re==null?"":String(Re),onChange:ne=>{const Me=ne.target.value===""?null:Math.round(Number(ne.target.value));a(u,Pe,Number.isFinite(Me)?Me:null)},disabled:n,className:"h-7 text-xs","data-testid":`input-comp${ce}-${Ie.rowId}`})]},ce)}if(Ie.rowId==="AddressLineText"){const Re=Ro(s(u,Pe));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsx(ze,{type:"text",value:Re,onChange:ne=>a(u,Pe,ne.target.value),disabled:n,maxLength:100,className:"h-7 text-xs",placeholder:"Street address","data-testid":`input-comp${ce}-${Ie.rowId}`}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx(ze,{type:"text",value:Ro(s(u,Vn("AddressUnitDesignatorType",ce))),onChange:ne=>a(u,Vn("AddressUnitDesignatorType",ce),ne.target.value||null),disabled:n,maxLength:10,className:"h-6 text-xs w-16",placeholder:"Unit","data-testid":`input-comp${ce}-AddressUnitDesignatorType`}),e.jsx(ze,{type:"text",value:Ro(s(u,Vn("AddressUnitIdentifier",ce))),onChange:ne=>a(u,Vn("AddressUnitIdentifier",ce),ne.target.value||null),disabled:n,maxLength:20,className:"h-6 text-xs flex-1",placeholder:"ID","data-testid":`input-comp${ce}-AddressUnitIdentifier`})]}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx(ze,{type:"text",value:Ro(s(u,Vn("CityName",ce))),onChange:ne=>a(u,Vn("CityName",ce),ne.target.value),disabled:n,maxLength:50,className:"h-6 text-xs flex-1",placeholder:"City","data-testid":`input-comp${ce}-CityName`}),e.jsx(ze,{type:"text",value:Ro(s(u,Vn("StateCode",ce))),onChange:ne=>a(u,Vn("StateCode",ce),ne.target.value.slice(0,2)),disabled:n,maxLength:2,className:"h-6 text-xs w-12",placeholder:"ST","data-testid":`input-comp${ce}-StateCode`}),e.jsx(ze,{type:"text",value:Ro(s(u,Vn("PostalCode",ce))),onChange:ne=>a(u,Vn("PostalCode",ce),ne.target.value.slice(0,10)),disabled:n,maxLength:10,className:"h-6 text-xs w-20",placeholder:"ZIP","data-testid":`input-comp${ce}-PostalCode`})]})]},ce)}if(Ie.inputType==="enum"){const Re=Ro(s(u,Pe));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsx(ze,{type:"text",value:Re,onChange:ne=>a(u,Pe,ne.target.value||null),disabled:n,className:"h-7 text-xs","data-testid":`input-comp${ce}-${Ie.rowId}`})]},ce)}if(Ie.inputType==="amount"||Ie.inputType==="number"){const Re=wc(s(u,Pe));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsx(ze,{type:"number",step:Ie.format?.includes(".0")?"1":"0.01",value:Re==null?"":String(Re),onChange:ne=>
39{const Me=ne.target.value,lt=Me===""?null:Ie.format?.includes(".0")?Math.round(Number(Me)):Number(Me);a(u,Pe,Number.isFinite(lt)?lt:null)},disabled:n,className:"h-7 text-xs","data-testid":`input-comp${ce}-${Ie.rowId}`})]},ce)}if(Ie.rowId==="VehicleStorageType"){const Re=Ro(s(u,Pe)),ne=Vn("VehicleStorageSpaceCount",ce),Me=wc(s(u,ne));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsx(ze,{type:"text",value:Re,onChange:lt=>a(u,Pe,lt.target.value||null),disabled:n,placeholder:"Garage, Carport, None…",maxLength:40,className:"h-7 text-xs w-full","data-testid":`input-comp${ce}-VehicleStorageType`}),e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(ze,{type:"number",step:"1",min:"0",value:Me==null?"":String(Me),onChange:lt=>{const Tt=lt.target.value===""?null:Math.round(Number(lt.target.value));a(u,ne,Number.isFinite(Tt)?Tt:null)},disabled:n,className:"h-6 text-xs w-16","data-testid":`input-comp${ce}-VehicleStorageSpaceCount`}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"spaces"})]})]},ce)}const We=Ro(s(u,Pe));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Pe,getFieldMeta:r}),e.jsx(ze,{type:"text",value:We,onChange:Re=>a(u,Pe,Re.target.value||null),disabled:n,maxLength:Ie.maxLength,className:"h-7 text-xs","data-testid":`input-comp${ce}-${Ie.rowId}`})]},ce)},ye=Ie=>{const ce=Ro(s(u,Vn("AddressLineText",Ie))),Pe=wc(s(u,Vn("UnitMonthlyActualRentAmount",Ie))),We=Pe!=null?`${YT(Pe)}/mo`:null;return e.jsx("th",{className:"border border-slate-200 p-2 align-bottom w-[160px] sticky top-0 z-20 bg-white",children:e.jsxs("div",{className:"w-[150px]",children:[e.jsx(Hv,{label:`Comp ${Ie}`,address:ce,figure:We,testId:`rental-photo-card-comp${Ie}`,controls:e.jsx("span",{className:"rounded bg-white/80",children:e.jsx(_k,{comp:Ie,compCount:T,onDuplicate:M,readOnly:n,testId:`button-duplicate-comp${Ie}`})})}),h==="properties"&&E>1&&e.jsxs("div",{className:"mt-1.5 flex items-center gap-1 text-xs overflow-hidden",children:[e.jsx("span",{className:"text-slate-400 shrink-0",children:"vs unit:"}),e.jsx(A8,{selectedUnits:Aj(s(u,Qy(Ie))),maxUnits:E,onChange:Re=>a(u,Qy(Ie),Re.length?Re:null),disabled:n,disabledUnits:Array.from({length:E},(Re,ne)=>ne+1).filter(Re=>(V[Re]??0)>=Lb),testId:`select-comp${Ie}-subject-unit`})]})]})},Ie)},de=Ro(l?.AddressLineText??s(u,Fd("AddressLineText"))),ge=wc(s(u,Fd("UnitMonthlyActualRentAmount"))),Be=()=>h==="unit-analysis"&&E>1?e.jsxs("th",{className:"border border-slate-200 bg-amber-50/30 p-2 align-bottom w-[160px] sticky top-0 z-20",children:[e.jsx("div",{className:"text-xs font-semibold text-center text-amber-800",children:"Subject"}),e.jsxs("div",{className:"text-xs text-center mt-1 font-medium text-amber-700 bg-amber-100 rounded px-2 py-0.5 inline-block w-full",children:["Unit ",v]})]}):e.jsx("th",{className:"border border-slate-200 bg-amber-50/30 p-2 align-bottom w-[160px] sticky top-0 z-20",children:e.jsx(Hv,{label:"Subject",isSubject:!0,address:de,figure:ge!=null?`${YT(ge)}/mo`:null,testId:"rental-photo-card-subject"})}),He=h==="properties"?"Comparable Rental Properties":"Comparable Rental Analysis";return e.jsxs("div",{className:"space-y-4","data-testid":"rental-comparison-grid",children:[e.jsxs(ja,{children:[e.jsx(Fk,{}),e.jsxs(Do,{className:"pb-4 flex-row items-center justify-between space-y-0 flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ko,{className:"text-base",children:He}),e.jsxs("div",{className:"flex items-center gap-0.5 rounded-md border bg-muted/30 p-0.5",children:[e.jsx("button",{type:"button",onClick:()=>N("properties"),className:`px-2.5 py-1 text-xs rounded font-medium transition-colors ${h==="properties"?"bg-white shadow-sm text-slate-900":"text-muted-foreground hover:text-slate-700"}`,"data-testid":"btn-rental-view-properties",children:"Properties"}),e.jsx("button",{type:"button",onClick:()=>N("unit-analysis"),className:`px-2.5 py-1 text-xs rounded font-medium transition-colors ${h==="unit-analysis"?"bg-white shadow-sm text-slate-900":"text-muted-foreground hover:text-slate-700"}`,"data-testid":"btn-rental-view-unit-analysis",children:"Unit Analysis"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(y8,{selectedRelRowIds:R,existingCustomRowCount:C.length,onAdd:G,onRemove:U,onAddCustomRow:F,visibilityCtx:$,disabled:n}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Comps"}),e.jsx(De,{type:"button",variant:"outline",size:"sm",className:"h-8 w-8 p-0",disabled:n||T<=1,onClick:()=>B(T),"data-testid":"btn-remove-rental-comp",children:e.jsx(ur,{className:"w-4 h-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums w-16 text-center","data-testid":"text-rental-comp-count",children:[T," comps"]}),e.jsx(De,{type:"button",variant:"outline",size:"sm",className:"h-8 w-8 p-0",disabled:n||T>=x,onClick:()=>O(T+1),"data-testid":"btn-add-rental-comp",children:e.jsx(un,{className:"w-4 h-4"})})]})]}),e.jsxs(Ta,{children:[E>1&&e.jsx("div",{className:"mb-3 flex flex-wrap gap-2 text-xs","data-testid":"rental-per-unit-hint",children:Array.from({length:E},(Ie,ce)=>ce+1).map(Ie=>{const ce=V[Ie]??0,Pe=ce>=ix&&ce<=Lb,We=h==="unit-analysis"&&v===Ie;return h==="unit-analysis"?e.jsxs("button",{type:"button",onClick:()=>S(Ie),className:`px-2 py-1 rounded border font-medium transition-colors ${We?Pe?"border-green-500 bg-green-100 text-green-800 ring-1 ring-green-400":"border-amber-500 bg-amber-100 text-amber-800 ring-1 ring-amber-400":Pe?"border-green-300 bg-green-50 text-green-700 hover:bg-green-100":"border-amber-300 bg-amber-50 text-amber-700 hover:bg-amber-100"}`,"data-testid":`rental-unit-${Ie}-comp-count`,children:["Unit ",Ie,": ",ce,"/",Lb,ce<ix?` (min ${ix})`:" ✓"]},Ie):e.jsxs("span",{className:`px-2 py-1 rounded border ${Pe?"border-green-300 bg-green-50 text-green-700":"border-amber-300 bg-amber-50 text-amber-700"}`,"data-testid":`rental-unit-${Ie}-comp-count`,children:["Unit ",Ie,": ",ce,"/",Lb,ce<ix?` (min ${ix})`:" ✓"]},Ie)})}),e.jsx("div",{className:"overflow-auto max-h-[calc(100vh-260px)]",children:e.jsxs("table",{className:"w-full table-fixed border-collapse text-sm text-slate-700",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"border border-slate-200 p-2 text-left align-bottom w-44 sticky top-0 z-20 bg-white",children:e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-500",children:h==="properties"?"Property details":"Unit details"})}),Be(),D.map(Ie=>ye(Ie))]})}),e.jsxs("tbody",{children:[z.map(Ie=>e.jsxs("tr",{"data-testid":`rental-row-${Ie.rowId}`,children:[e.jsxs("td",{className:"border border-slate-200 p-2 font-medium text-xs",children:[Ie.label,m&&!Ie.computed&&e.jsx(Fs,{section:"rentalGrid",fieldName:Ie.rowId})]}),be(Ie),D.map(ce=>H(Ie,ce))]},Ie.rowId)),C.map((Ie,ce)=>e.jsxs("tr",{"data-testid":`rental-row-custom-${ce}`,children:[e.jsxs("td",{className:"border border-slate-200 p-2 font-medium text-xs",children:[Ie.label,!n&&e.jsx("button",{type:"button",title:"Remove this custom row",className:"ml-2 text-slate-400 hover:text-red-500",onClick:()=>A(ce),"data-testid":`btn-rental-remove-custom-row-${ce}`,children:e.jsx(ur,{className:"w-3 h-3 inline"})})]}),e.jsx("td",{className:"border border-slate-200 p-2 bg-amber-50/30",children:e.jsx(ze,{type:"text",value:Ro(s(u,Fd(`_rentalCustomSubjectRow${ce}`))),onChange:Pe=>a(u,Fd(`_rentalCustomSubjectRow${ce}`),Pe.target.value||null),disabled:n,className:"h-7 text-xs","data-testid":`input-subject-custom-row-${ce}`})}),D.map(Pe=>e.jsx("td",{className:"border border-slate-200 p-2",children:e.jsx(ze,{type:"text",value:Ro(s(u,`_rentalCustomComp${Pe}Row${ce}`)),onChange:We=>a(u,`_rentalCustomComp${Pe}Row${ce}`,We.target.value||null),disabled:n,className:"h-7 text-xs","data-testid":`input-comp${Pe}-custom-row-${ce}`})},Pe))]},`custom-${ce}`))]})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Each subject unit requires between ",ix," and ",Lb,' comparable rentals (per B-1). Use the "vs unit:" selector on each comp column to assign it to the correct subject unit.']}
39)]})]}),e.jsx(CL,{sectionId:DE,commentFieldName:"ValuationCommentText",commentLabel:"Comparable Rental Analysis",commentRequired:!0,title:"Rental Analysis Commentary & Exhibits",commentPlaceholder:"Additional details and analysis to support conclusions, including how Comparable Weight was determined.",expanded:!0,getFieldValue:s,updateField:a,photoMenuItems:[{label:"Map of Rental Comparables",mismoCategory:"RentalComparableMap",predefinedCaption:"Map of Rental Comparables",required:!0},{label:"Additional photo",mismoCategory:"RentalInformationExhibit"}]})]})}const wS="grmComparison",kN=[{rowId:"AddressLineText",label:"Property Address",inputType:"text",class:"ALW",subjectGray:!1,maxLength:100},{rowId:"DataSource",label:"Data Source",inputType:"special",class:"ALW",subjectGray:!0},{rowId:"ProximityToSubjectDistanceLinearMeasure",label:"Proximity to Subject",inputType:"special",class:"ALW",subjectGray:!0,format:"+3.2"},{rowId:"LivingUnitExcludingADUCount",label:"Units Excl. ADUs",inputType:"number",class:"ALW",subjectGray:!1,format:"+1.0"},{rowId:"AccessoryDwellingUnitTotalCount",label:"Accessory Dwelling Units",inputType:"number",class:"APP",subjectGray:!1,format:"+1.0"},{rowId:"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure",label:"Gross Building Finished Area",inputType:"number",class:"REL",subjectGray:!1,format:"+6.0"},{rowId:"PropertyRentControlStatusType",label:"Rent Control",inputType:"enum",class:"REL",subjectGray:!1},{rowId:"AdditionalComparisonLineItemDescription",label:"[Additional Row]",inputType:"text",class:"REL",subjectGray:!1,maxLength:21},{rowId:"OwnershipTransferTransactionAmount",label:"Sale Price",inputType:"amount",class:"ALW",subjectGray:!0,format:"+9.2"},{rowId:"OwnershipTransferDate",label:"Sale Date",inputType:"date",class:"ALW",subjectGray:!0},{rowId:"TotalMonthlyActualRentAmount",label:"Gross Monthly Rent",inputType:"amount",class:"ALW",subjectGray:!1,format:"+5.0"},{rowId:"GrossMonthlyRentMultiplierNumber",label:"Gross Rent Multiplier",inputType:"number",class:"ALW",subjectGray:!0,computed:!0,format:"+3.0"},{rowId:"ComparableWeightType",label:"Comparable Weight",inputType:"enum",class:"ALW",subjectGray:!0}];kN.filter(t=>t.class==="ALW");kN.filter(t=>t.class==="APP");kN.filter(t=>t.class==="REL");function fn(t,a){return`Comp${a}${t}`}const aM={GrossRentMultiplier:"GrossRentMultiplierFactorNumber",IncomeApproachValue:"ValueIndicatedByIncomeApproachAmount"},R8=["AssessorRecord","BuilderOrDeveloper","CondominiumQuestionnaire","CooperativeBoard","CooperativeQuestionnaire","CostService","CostSurvey","DataAggregator","Deed","ExteriorInspection","HomeownersAssociation","InteriorInspection","LandSurvey","Lender","MLS","PhysicalMeasurement","PlansAndSpecifications","PlatMap","PreviousAppraisalFile","PropertyDataReport","PropertyManagementCompany","PropertyOwner","PropertyTenant","RealEstateAgent","ThreeDimensionalScan","Zoning"],E8=45,ov=3,w8=3,Wb=8;function P8(t,a){return t===null||a===null||a<=0?null:Math.round(t/a)}const O8=[{value:"Less",label:"Less"},{value:"Most",label:"Most"},{value:"NoWeight",label:"No Weight"}],YP=[{value:"Yes",label:"Yes"},{value:"No",label:"No"}],L8=[{value:"North",label:"N"},{value:"NorthEast",label:"NE"},{value:"East",label:"E"},{value:"SouthEast",label:"SE"},{value:"South",label:"S"},{value:"SouthWest",label:"SW"},{value:"West",label:"W"},{value:"NorthWest",label:"NW"}],D8=[{value:"Miles",label:"Miles"},{value:"Kilometers",label:"Km"}],k8=[{rowId:"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure",label:"Gross Building Finished Area",description:"Sum of finished area across all units incl. ADUs (sq ft)"},{rowId:"PropertyRentControlStatusType",label:"Rent Control",description:"Whether rent control applies — Yes or No"}];function M8({selectedRelRowIds:t,existingCustomRowCount:a,onAdd:s,onRemove:r,onAddCustomRow:n,visibilityCtx:i,disabled:l=!1}){const[c,d]=o.useState(!1),[p,u]=o.useState(""),m=o.useRef(null),h=i.subject.incomeApproachActive===!0||i.comps.some(x=>x.incomeApproachActive===!0),f=a<ov,v=(x,y)=>{y?s(x):r(x)},S=()=>{const x=p.trim();!x||!f||(n(x),u(""),m.current?.focus())},N=t.size+a;return e.jsxs(xn,{open:c,onOpenChange:d,children:[e.jsx(bn,{asChild:!0,children:e.jsxs(De,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs gap-1",disabled:l,"data-testid":"btn-grm-add-row",children:[e.jsx(un,{className:"w-3 h-3"}),"Optional rows",N>0&&e.jsx("span",{className:"ml-0.5 rounded-full bg-slate-200 px-1.5 py-0 text-[10px] font-medium tabular-nums",children:N}),e.jsx(Rr,{className:"w-3 h-3 ml-0.5 text-muted-foreground"})]})}),e.jsxs(yn,{className:"w-72 p-0",align:"end","data-testid":"popover-grm-row-picker",children:[e.jsxs("div",{className:"p-3 space-y-2.5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"UAD 3.6 optional rows"}),k8.map(x=>{const y=t.has(x.rowId),b=!h;return e.jsxs("div",{className:`flex items-start gap-2.5 ${b?"opacity-50":""}`,children:[e.jsx(Pa,{id:`grm-rel-${x.rowId}`,checked:y,disabled:b&&!y,onCheckedChange:j=>v(x.rowId,j===!0),"data-testid":`chk-grm-rel-${x.rowId}`,className:"mt-0.5 shrink-0"}),e.jsxs("label",{htmlFor:`grm-rel-${x.rowId}`,className:"flex flex-col cursor-pointer select-none",children:[e.jsx("span",{className:"text-sm font-medium leading-tight",children:x.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight mt-0.5",children:b&&!y?"Requires Income Approach":x.description})]})]}
39,x.rowId)})]}),e.jsx(Rv,{}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:["Custom rows"," ",e.jsxs("span",{className:"normal-case font-normal",children:["(",a,"/",ov," used)"]})]}),f?e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(ze,{ref:m,value:p,onChange:x=>u(x.target.value),placeholder:"Row label (max 21 chars)",maxLength:21,className:"h-7 text-xs flex-1","data-testid":"input-grm-custom-row-label",onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),S())}}),e.jsx(De,{type:"button",size:"sm",className:"h-7 px-2 text-xs shrink-0",disabled:!p.trim(),onClick:S,"data-testid":"btn-grm-add-custom-row",children:"Add"})]}):e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Maximum of ",ov," custom rows reached."]})]})]})]})}function F8({n:t,section:a,fieldName:s,readOnly:r,types:n,identifiers:i,getFieldMeta:l,onToggle:c,onSetIdentifier:d}){const[p,u]=o.useState(!1),[m,h]=o.useState(""),f=o.useRef(null);o.useEffect(()=>{if(!p)return;const S=N=>{f.current&&!f.current.contains(N.target)&&u(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[p]);const v=()=>{const S=m.trim();!S||n.includes(S)||(c(S,!0),h(""))};return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:a,field:s,getFieldMeta:l}),e.jsxs("div",{className:"relative",ref:f,children:[e.jsxs("button",{type:"button",className:"w-full text-left text-xs border rounded px-2 py-1 bg-white hover:bg-slate-50 flex items-center justify-between",onClick:()=>u(S=>!S),disabled:r,"data-testid":`btn-comp${t}-datasource`,children:[e.jsx("span",{className:"truncate",children:n.length===0?e.jsx("span",{className:"text-slate-400",children:"Select…"}):n.map(S=>{const N=i[S];return N?`${S} ${N}`:S}).join(" | ")}),e.jsx(Rr,{className:"w-3 h-3 shrink-0 ml-1 text-slate-400"})]}),p&&!r&&e.jsxs("div",{className:"absolute z-20 top-full left-0 mt-1 w-60 bg-white border rounded shadow-lg text-xs",children:[e.jsx("div",{className:"max-h-48 overflow-y-auto",children:R8.map(S=>{const N=n.includes(S);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-1.5 hover:bg-slate-50 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:N,onChange:x=>c(S,x.target.checked),className:"h-3 w-3"}),e.jsx("span",{children:S})]},S)})}),e.jsxs("div",{className:"border-t p-2 flex gap-1",children:[e.jsx(ze,{value:m,onChange:S=>h(S.target.value),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),v())},placeholder:"Custom source…",className:"h-6 text-xs flex-1","data-testid":`input-comp${t}-datasource-custom`}),e.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-slate-100 hover:bg-slate-200 rounded",onClick:v,"data-testid":`btn-comp${t}-datasource-custom-add`,children:"Add"})]})]})]}),n.map(S=>e.jsx("div",{className:"mt-1",children:e.jsx(ze,{value:i[S]??"",onChange:N=>d(S,N.target.value.slice(0,E8)),placeholder:S==="MLS"?"MLS # (required)":`${S} # (optional)`,className:"h-6 text-xs",disabled:r,"data-testid":`input-comp${t}-datasource-id-${S}`})},S))]})}function Bl(t){if(t==null||t==="")return null;const a=Number(t);return Number.isFinite(a)?a:null}function jl(t){return t==null?"":String(t)}const Au="incomeApproach",jj="GrossRentMultiplierFactorNumber",_8=aM.GrossRentMultiplier,GP="ValueIndicatedByIncomeApproachAmount",U8=aM.IncomeApproachValue;function V8({formData:t,updateField:a,getFieldValue:s,getFieldMeta:r,readOnly:n=!1,subjectCoordinates:i,subjectPrefill:l,visibilityCtx:c,incomeApproachActive:d=!1,selectedRelRows:p}){const u=wS,m=Bl(s(u,"CompCount")),[h,f]=o.useState(m&&m>0?m:w8),v=Math.min(Wb,Math.max(1,h)),S=de=>{const ge=Math.min(Wb,Math.max(1,de));f(ge),a(u,"CompCount",ge)},[N,x]=o.useState(()=>{if(p)return p;const de=["TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure","PropertyRentControlStatusType"];return new Set(de.filter(ge=>{const Be=s(u,`_relRow_${ge}`);return Be===!0||Be==="true"}))}),y=p??N,[b,j]=o.useState(()=>{const de=s(u,"_grmCustomRowDefs");return Array.isArray(de)?de.filter(ge=>!!ge&&typeof ge.label=="string").slice(0,ov):[]}),T=de=>{p||x(ge=>new Set(Array.from(ge).concat(de))),a(u,`_relRow_${de}`,!0)},O=de=>{p||x(ge=>{const Be=new Set(ge);return Be.delete(de),Be}),a(u,`_relRow_${de}`,!1)},E=de=>{j(ge=>{const Be=[...ge,{label:de}];return a(u,"_grmCustomRowDefs",Be.map(He=>({label:He.label}))),Be})},R=(de,ge)=>{Uk(t,u,de,ge,a)},G=de=>{const ge=t[u]??{},Be=Lk(ge,de,v,u);for(const{field:He,value:Ie}of Be)a(u,He,Ie);S(Math.max(1,v-1))},U=Array.from({length:v},(de,ge)=>ge+1),C=o.useRef(new Map),F=o.useRef(new Set),A=o.useCallback(async de=>{const ge=jl(s(u,fn("AddressLineText",de))),Be=jl(s(u,fn("CityName",de))),He=jl(s(u,fn("StateCode",de)));if(!(!ge||!Be||!He))try{const Ie=await fetch("/api/mapbox/geocode",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({address:`${ge}, ${Be}, ${He}`})});if(!Ie.ok)return;const ce=await Ie.json();if(ce.lat==null||ce.lng==null||(C.current.set(de,{lat:ce.lat,lng:ce.lng}),F.current.has(de))||!i)return;const{haversineMiles:Pe,bearingDegrees:We,bearingToDirectionToken:Re}=await ri(async()=>{const{haversineMiles:je,bearingDegrees:Le,bearingToDirectionToken:ut}=await Promise.resolve().then(()=>v8);return{haversineMiles:je,bearingDegrees:Le,bearingToDirectionToken:ut}},void 0),ne=Pe(i.lat,i.lng,ce.lat,ce.lng),Me=Math.round(ne*100)/100,lt=Bl(s(u,fn("ProximityToSubjectDistanceLinearMeasure",de)));if((lt==null||lt===0)&&(a(u,fn("ProximityToSubjectDistanceLinearMeasure",de),Me),a(u,fn("LinearUnitOfMeasureType",de),"Miles")),!jl(s(u,fn("ComparableToSubjectDirectionType",de)))&&Me>0){const je=We(i.lat,i.lng,ce.lat,ce.lng),Le=Re(je);a(u,fn("ComparableToSubjectDirectionType",de),Le)}}catch{}},[s,u,i,a]),M=l?.TotalMonthlyActualRentAmount??Bl(s(Au,"TotalMonthlyActualRentAmount"))??Bl(s(Au,"EstimatedMonthlyRent")),B=M!=null?`$${M.toLocaleStr
39ing(void 0,{maximumFractionDigits:0})}/mo`:null,oe=Bl(s(Au,jj))??Bl(s(Au,_8)),ae=Bl(s(Au,"TotalMonthlyMarketRentAmount")),D=ae!==null&&oe!==null?Math.round(ae*oe):null;o.useEffect(()=>{(Bl(s(Au,GP))??Bl(s(Au,U8)))!==D&&a(Au,GP,D)},[D]);const _=de=>P8(Bl(s(u,fn("OwnershipTransferTransactionAmount",de))),Bl(s(u,fn("TotalMonthlyActualRentAmount",de)))??Bl(s(u,fn("UnitMonthlyActualRentAmount",de)))),$=o.useMemo(()=>{const de=[];for(let ge=1;ge<=v;ge++){const Be=_(ge);Be!==null&&de.push(Be)}return de.length===0?null:Math.round(de.reduce((ge,Be)=>ge+Be,0)/de.length)},[v,t]),z=o.useMemo(()=>({subject:{aduCount:l?.AccessoryDwellingUnitTotalCount??Bl(s("subjectProperty","AccessoryDwellingUnitTotalCount")),incomeApproachActive:d},comps:U.map(de=>({aduCount:Bl(s(u,fn("AccessoryDwellingUnitTotalCount",de))),incomeApproachActive:d}))}),[t,v,l,d]),V=c??z,le=kN.filter(de=>de.class==="REL"?de.rowId==="AdditionalComparisonLineItemDescription"?!1:y.has(de.rowId):nU(de.rowId,V)),W=le.findIndex(de=>de.rowId==="OwnershipTransferTransactionAmount"),me=W>=0?le.slice(0,W):le,Z=W>=0?le.slice(W):[],pe=de=>de===null?"":String(de),se=de=>{const ge=s(u,fn("DataSourceTypes",de));return Array.isArray(ge)?ge:[]},fe=de=>{const ge=s(u,fn("DataSourceIdentifiers",de));return ge&&typeof ge=="object"&&!Array.isArray(ge)?ge:{}},ue=(de,ge,Be)=>{const He=se(de),Ie=Be?[...He,ge]:He.filter(ce=>ce!==ge);a(u,fn("DataSourceTypes",de),Ie)},be=(de,ge,Be)=>{const Ie={...fe(de),[ge]:Be};a(u,fn("DataSourceIdentifiers",de),Ie)},H=de=>{if(de.subjectGray)return e.jsx("td",{className:"border border-slate-200 bg-slate-100/60 p-2",children:e.jsx("div",{className:"h-6 flex items-center justify-center",children:e.jsx("span",{className:"text-xs text-slate-300 select-none",children:"—"})})});let ge="";if(de.rowId==="AddressLineText")ge=l?.AddressLineText??s("subjectProperty","AddressLineText")??"";else if(de.rowId==="LivingUnitExcludingADUCount")ge=l?.LivingUnitExcludingADUCount??"";else if(de.rowId==="AccessoryDwellingUnitTotalCount")ge=l?.AccessoryDwellingUnitTotalCount??"";else if(de.rowId==="TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure")ge=l?.TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure??"";else if(de.rowId==="TotalMonthlyActualRentAmount")ge=M??"";else if(de.rowId==="PropertyRentControlStatusType"){const He=jl(l?.PropertyRentControlStatusType??s(Au,"PropertyRentControlStatusType"));return e.jsx("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:e.jsxs("select",{value:He,onChange:Ie=>a(Au,"PropertyRentControlStatusType",Ie.target.value||null),disabled:n,className:"w-full text-xs border-0 bg-transparent focus:outline-none focus:ring-1 focus:ring-blue-300 rounded","data-testid":"select-subject-PropertyRentControlStatusType",children:[e.jsx("option",{value:"",children:"—"}),YP.map(Ie=>e.jsx("option",{value:Ie.value,children:Ie.label},Ie.value))]})})}const Be=ge===""||ge==null?e.jsx("span",{className:"text-slate-400 text-xs",children:"—"}):e.jsx("span",{className:"text-xs",children:String(ge)});return e.jsx("td",{className:"border border-slate-200 bg-amber-50/30 p-2",children:e.jsx("div",{className:"h-6 flex items-center","data-testid":`text-subject-${de.rowId}`,children:Be})})},ye=(de,ge)=>{const Be=fn(de.rowId,ge);if(de.rowId==="GrossMonthlyRentMultiplierNumber")return e.jsx("td",{className:"border border-slate-200 p-2",children:e.jsx("div",{className:"h-6 flex items-center text-xs text-slate-700 tabular-nums","data-testid":`text-comp${ge}-${de.rowId}`,children:pe(_(ge))})},ge);if(de.rowId==="DataSource")return e.jsx(F8,{n:ge,section:u,fieldName:Be,readOnly:n,types:se(ge),identifiers:fe(ge),getFieldMeta:r,onToggle:(Ie,ce)=>ue(ge,Ie,ce),onSetIdentifier:(Ie,ce)=>be(ge,Ie,ce)},ge);if(de.rowId==="ProximityToSubjectDistanceLinearMeasure"){const Ie=Bl(s(u,fn("ProximityToSubjectDistanceLinearMeasure",ge))),ce=jl(s(u,fn("LinearUnitOfMeasureType",ge)))||"Miles",Pe=jl(s(u,fn("ComparableToSubjectDirectionType",ge)));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Be,getFieldMeta:r}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ze,{type:"number",step:"0.01",min:"0",value:Ie==null?"":String(Ie),onChange:We=>{F.current.add(ge);const Re=We.target.value===""?null:Number(We.target.value);a(u,fn("ProximityToSubjectDistanceLinearMeasure",ge),Re)},disabled:n,className:"h-6 text-xs w-16","data-testid":`input-comp${ge}-proximity-distance`}),e.jsx("select",{value:ce,onChange:We=>{F.current.add(ge);const Re=We.target.value;if(Ie!=null){const ne=oC(Ie,ce,Re);a(u,fn("ProximityToSubjectDistanceLinearMeasure",ge),ne)}a(u,fn("LinearUnitOfMeasureType",ge),Re)},disabled:n,className:"text-xs border rounded px-1 h-6 bg-white","data-testid":`select-comp${ge}-proximity-unit`,children:D8.map(We=>e.jsx("option",{value:We.value,children:We.label},We.value))})]}),(Ie==null||Ie>0)&&e.jsxs("select",{value:Pe,onChange:We=>{F.current.add(ge),a(u,fn("ComparableToSubjectDirectionType",ge),We.target.value||null)},disabled:n,className:"mt-1 text-xs border rounded px-1 h-6 bg-white w-full","data-testid":`select-comp${ge}-proximity-direction`,children:[e.jsx("option",{value:"",children:"—"}),L8.map(We=>e.jsx("option",{value:We.value,children:We.label},We.value))]})]},ge)}if(de.rowId==="ComparableWeightType"){const Ie=jl(s(u,Be)),ce=!Ie;return e.jsx("td",{className:`border p-2 align-top ${ce?"border-red-300 bg-red-50":"border-slate-200"}`,"data-testid":`warn-comp${ge}-weight`,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:O8.map(Pe=>e.jsx("button",{type:"button",disabled:n,onClick:()=>a(u,Be,Ie===Pe.value?null:Pe.value),className:`px-2 py-0.5 rounded text-xs border transition-colors ${Ie===Pe.value?"bg-blue-600 text-white border-blue-600":"bg-white text-slate-700 border-slate-300 hover:border-blue-400"}`,"data-testid":`pill-comp${ge}-weight-${Pe.value}`,children:Pe.label},Pe.value))})},ge)}if(de.rowId==="PropertyRentControlStatusType"){const Ie=jl(s(u,Be));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Be,getFieldMeta:r}),e.jsxs("select",{value:Ie,onChange:ce=>a(u,Be,ce.target.value||null),disabled:n,className:"w-full text-xs border rounded px-1 h-7 bg-white","data-testid":`select-comp${ge}-${de.rowId}`,children:[e.jsx("option",{value:"",children:"—"}),YP.map(ce=>e.jsx("option",{value:ce.value,children:ce.label},ce.value))]})]},ge)}if(de.rowId==="TotalMonthlyActualRentAmount"){const Ie=Bl(s(u,Be)??s(u,fn("UnitMonthlyActualRentAmount",ge))),ce=fn("TotalMonthlyActualRentAmountEstimatedIndicator",ge),Pe=s(u,ce)===!0||s(u,ce)==="true";return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Be,getFieldMeta:r}),e.jsxs("div",{className:"flex items-center gap-1",children:[Pe&&e.jsx("span",{className:"text-xs text-slate-500 font-mono",children:"~"}),e.jsx(ze,{type:"number",step:"1",min:"0",value:Ie==null?"":String(Ie),onChange:We=>{const Re=We.target.value===""?null:Math.round(Number(We.target.value));a(u,Be,Re)},disabled:n,className:"h-7 text-xs flex-1","data-testid":`input-comp${ge}-${de.rowId}`}),e.jsx("button",{type:"button",title:"Toggle estimated",onClick:()=>a(u,ce,!Pe),disabled:n,className:`text-xs px-1 rounded border ${Pe?"bg-amber-100 border-amber-400 text-amber-700":"bg-white border-slate-200 text-slate-400"}`,"data-testid":`btn-comp${ge}-rent-estimated`,children:"~"})]}),Pe&&e.jsx("div",{className:"text-xs text-amber-600 mt-0.5",children:"Estimated"})]},ge)}if(de.rowId==="AddressLineText"){const Ie=jl(s(u,Be));return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Be,getFieldMeta:r}),e.jsx(ze,{type:"text",value:Ie,onChange:ce=>a(u,Be,ce.target.value),onBlur:()=>A(ge),disabled:n,maxLength:100,className:"h-7 text-xs",placeholder:"Street address","data-testid":`input-comp${ge}-${de.rowId}`}),e.jsx(ze,{type:"text",value:jl(s(u,fn("AddressUnitIdentifier",ge))),onChange:ce=>a(u,fn("AddressUnitIdentifier",ge),ce.target.value.slice(0,12)||null),disabled:n,maxLength:12,className:"h-6 text-xs mt-1",placeholder:"Unit / Apt (optional)","data-testid":`input-comp${ge}-AddressUnitIdentifier`}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx(ze,{type:"text",value:jl(s(u,fn("CityName",ge))),onChange:ce=>a(u,fn("CityName",ge),ce.target.value),onBlur:()=>A(ge),disabled:n,maxLength:50,className:"h-6 text-xs flex-1",placeholder:"City","data-testid":`input-comp${ge}-CityName`}),e.jsx(ze,{type:"text",value:jl(s(u,fn("StateCode",ge))),onChange:ce=>a(u,fn("StateCode",ge),ce.target.value.slice(0,2)),onBlur:()=>A(ge),disabled:n,maxLength:2,className:"h-6 text-xs w-12",placeholder:"ST","data-testid":`input-comp${ge}-StateCode`}),e.jsx(ze,{type:"text",value:jl(s(u,fn("PostalCode",ge))),onChange:ce=>a(u,fn("PostalCode",ge),ce.target.value.slice(0,10)),disabled:n,maxLength:10,className:"h-6 text-xs w-20",placeholder:"ZIP","data-testid":`input-comp${ge}-PostalCode`})]})]},ge)}const He=jl(s(u,Be));if(de.inputType==="number"||de.inputType==="amount")return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Be,getFieldMeta:r}),e.jsx(ze,{type:"number",step:de.format?.includes(".0")?"1":"0.01",value:He,onCh
39ange:Ie=>{const ce=Ie.target.value,Pe=ce===""?null:de.format?.includes(".0")?Math.round(Number(ce)):Number(ce);a(u,Be,Number.isFinite(Pe)?Pe:null)},disabled:n,className:"h-7 text-xs","data-testid":`input-comp${ge}-${de.rowId}`})]},ge);if(de.inputType==="date"){const Ie=(()=>{if(!He||!/^\d{4}-\d{2}-\d{2}$/.test(He))return He;const[Pe,We,Re]=He.split("-");return`${We}/${Re}/${Pe}`})(),ce=Pe=>{const We=Pe.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);return We?`${We[3]}-${We[1].padStart(2,"0")}-${We[2].padStart(2,"0")}`:/^\d{4}-\d{2}-\d{2}$/.test(Pe)?Pe:Pe||null};return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Be,getFieldMeta:r}),e.jsx(ze,{type:"text",value:Ie,onChange:Pe=>a(u,Be,ce(Pe.target.value)),disabled:n,placeholder:"MM/DD/YYYY",className:"h-7 text-xs","data-testid":`input-comp${ge}-${de.rowId}`})]},ge)}return e.jsxs("td",{className:"border border-slate-200 p-2 align-top",children:[e.jsx(vo,{section:u,field:Be,getFieldMeta:r}),e.jsx(ze,{type:"text",value:He,onChange:Ie=>a(u,Be,Ie.target.value),disabled:n,maxLength:de.maxLength,className:"h-7 text-xs","data-testid":`input-comp${ge}-${de.rowId}`})]},ge)};return e.jsxs("div",{className:"space-y-4","data-testid":"grm-comparison-grid",children:[e.jsxs(ja,{children:[e.jsx(Fk,{}),e.jsxs(Do,{className:"pb-2 flex-row items-center justify-between space-y-0",children:[e.jsx(ko,{className:"text-base",children:"GRM Comparables"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(M8,{selectedRelRowIds:y,existingCustomRowCount:b.length,onAdd:T,onRemove:O,onAddCustomRow:E,visibilityCtx:V,disabled:n}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(De,{type:"button",variant:"outline",size:"sm",className:"h-7 w-7 p-0",disabled:n||v<=1,onClick:()=>G(v),"data-testid":"btn-remove-grm-comp",children:e.jsx(ur,{className:"w-3 h-3"})}),e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums","data-testid":"text-grm-comp-count",children:[v," comps"]}),e.jsx(De,{type:"button",variant:"outline",size:"sm",className:"h-7 w-7 p-0",disabled:n||v>=Wb,onClick:()=>S(v+1),"data-testid":"btn-add-grm-comp",children:e.jsx(un,{className:"w-3 h-3"})})]})]})]}),e.jsx(Ta,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full border-collapse text-sm text-slate-700",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"border border-slate-200 p-2 text-left align-bottom w-44 bg-slate-50",children:e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-500",children:"Property details"})}),e.jsx("th",{className:"border border-slate-200 bg-amber-50/30 p-2 align-bottom min-w-[150px]",children:e.jsx(Hv,{label:"Subject",isSubject:!0,figure:B,testId:"grm-photo-card-subject"})}),U.map(de=>e.jsx("th",{className:"border border-slate-200 p-2 align-bottom min-w-[160px]",children:e.jsx(Hv,{label:`Comp ${de}`,address:jl(s(u,fn("AddressLineText",de))),figure:YT(Bl(s(u,fn("OwnershipTransferTransactionAmount",de)))),testId:`grm-photo-card-comp${de}`,controls:e.jsx("span",{className:"rounded bg-white/80",children:e.jsx(_k,{comp:de,compCount:v,onDuplicate:R,readOnly:n,testId:`button-duplicate-comp${de}`})})})},de))]})}),e.jsxs("tbody",{children:[me.map(de=>e.jsxs("tr",{"data-field-name":de.rowId,"data-testid":`grm-row-${de.rowId}`,children:[e.jsx("td",{className:"border border-slate-200 p-2 font-medium text-xs bg-slate-50 align-top",children:e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsx("span",{children:de.label}),de.class==="REL"&&!n&&e.jsx("button",{type:"button",onClick:()=>O(de.rowId),className:"shrink-0 text-slate-400 hover:text-slate-700 leading-none",title:"Remove optional row","data-testid":`btn-grm-remove-rel-${de.rowId}`,children:e.jsx(ur,{className:"w-3 h-3"})}),de.class==="APP"&&e.jsx(kt,{variant:"outline",className:"ml-1 text-[9px] py-0",children:"APP"})]})}),H(de),U.map(ge=>ye(de,ge))]},de.rowId)),b.map((de,ge)=>e.jsxs("tr",{"data-testid":`grm-row-custom-${ge}`,children:[e.jsxs("td",{className:"border border-slate-200 p-2 text-xs bg-slate-50 italic align-top",children:[de.label,!n&&e.jsx("button",{type:"button",className:"ml-2 text-slate-400 hover:text-red-500",onClick:()=>j(Be=>{const He=Be.filter((ce,Pe)=>Pe!==ge);a(u,"_grmCustomRowDefs",He.map(ce=>({label:ce.label})));const Ie=Be.length-1;for(let ce=ge;ce<Ie;ce++){const Pe=s(u,`_grmCustomSubjectRow${ce+1}`);a(u,`_grmCustomSubjectRow${ce}`,Pe);for(let We=1;We<=Wb;We++){const Re=s(u,`_grmCustomComp${We}Row${ce+1}`);a(u,`_grmCustomComp${We}Row${ce}`,Re)}}a(u,`_grmCustomSubjectRow${Ie}`,null);for(let ce=1;ce<=Wb;ce++)a(u,`_grmCustomComp${ce}Row${Ie}`,null);return He}),children:e.jsx(ur,{className:"w-3 h-3 inline"})})]}),e.jsx("td",{className:"border border-slate-200 bg-amber-50/30 p-2 al
39ign-top",children:e.jsx(ze,{type:"text",value:jl(s(u,`_grmCustomSubjectRow${ge}`)),onChange:Be=>a(u,`_grmCustomSubjectRow${ge}`,Be.target.value),disabled:n,maxLength:21,className:"h-6 text-xs","data-testid":`input-subject-custom-${ge}`})}),U.map(Be=>e.jsx("td",{className:"border border-slate-200 p-2 align-top",children:e.jsx(ze,{type:"text",value:jl(s(u,`_grmCustomComp${Be}Row${ge}`)),onChange:He=>a(u,`_grmCustomComp${Be}Row${ge}`,He.target.value),disabled:n,maxLength:21,className:"h-6 text-xs","data-testid":`input-comp${Be}-custom-${ge}`})},Be))]},ge)),Z.map(de=>e.jsxs("tr",{"data-field-name":de.rowId,"data-testid":`grm-row-${de.rowId}`,children:[e.jsx("td",{className:"border border-slate-200 p-2 font-medium text-xs bg-slate-50 align-top",children:e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsx("span",{children:de.label}),de.class==="APP"&&e.jsx(kt,{variant:"outline",className:"ml-1 text-[9px] py-0",children:"APP"})]})}),H(de),U.map(ge=>ye(de,ge))]},de.rowId))]})]})})})]}),e.jsxs(ja,{"data-testid":"card-grm-reconciliation",children:[e.jsx(Do,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ko,{className:"text-base",children:"GRM Reconciliation"}),$!==null&&!n&&e.jsxs("button",{type:"button",className:"text-xs text-blue-600 hover:underline",onClick:()=>a(Au,jj,$),"data-testid":"btn-grm-use-average",children:["Use avg ",$]})]})}),e.jsxs(Ta,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ja,{className:"text-xs",children:"Total Monthly Market Rent"}),e.jsx("div",{className:"h-9 flex items-center px-3 rounded-md border bg-slate-50 text-sm font-medium text-slate-700","data-testid":"text-grm-market-rent",children:ae!=null?`$${ae.toLocaleString(void 0,{maximumFractionDigits:0})}`:e.jsx("span",{className:"text-slate-400 text-xs",children:"Set in Income Approach"})}),e.jsx("p",{className:"text-[10px] text-slate-400",children:"Auto-summed from Income Approach section"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ja,{className:"text-xs",children:"Reconciled GRM"}),e.jsx(ze,{type:"number",step:"1",min:"0",value:oe==null?"":String(oe),onChange:de=>{const ge=de.target.value,Be=ge===""?null:Math.round(Number(ge));a(Au,jj,Number.isFinite(Be)?Be:null)},disabled:n,placeholder:"e.g. 150","data-testid":"input-grm-reconciled"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ja,{className:"text-xs",children:"Indicated Value by Income Approach"}),e.jsx("div",{className:"h-9 flex items-center px-3 rounded-md border bg-slate-50 text-lg font-semibold","data-testid":"text-grm-indicated-value",children:D!=null?`$${D.toLocaleString(void 0,{maximumFractionDigits:0})}`:e.jsx("span",{className:"text-slate-400 text-sm",children:"—"})})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:"Indicated value = reconciled GRM × total monthly market rent. Flows to the income approach line in final value reconciliation."})]})]}),(()=>{const de=s(wS,"exhibitPhotos"),ge=Array.isArray(de)?de:[];return e.jsx(CL,{hidePhotos:!0,sectionId:wS,commentFieldName:"IncomeAnalysisCommentDescription",commentLabel:"Income Analysis",commentRequired:!0,title:"Income Approach Commentary & Exhibits",commentPlaceholder:"Additional details and analysis to support conclusions, including how Comparable Weight and Gross Rent Multiplier were determined.",expanded:!0,getFieldValue:s,updateField:a,extraContent:e.jsx(mD,{items:ge,onChange:Be=>a(wS,"exhibitPhotos",Be),otherReportImageCount:RL(s)-EL(ge),mapCaption:"Map of GRM Comparables",mapImageType:"GrossRentMultiplierComparableMap",mapRequired:!0,idPrefix:"grm-exhibits",testIdBase:"grm-exhibits"})})})()]})}function Tj(t,a){if(!t)return;const s=t[a];return s&&typeof s=="object"&&"value"in s?s.value:s}function PS(t){if(t==null||t==="")return null;const a=Number(t);return Number.isFinite(a)?a:null}function $8(t){const{subjectAddress:a,buildings:s,incomeApproach:r}=t,n={AddressLineText:a?.AddressLineText??void 0,AddressUnitIdentifier:a?.AddressUnitIdentifier??void 0,CityName:a?.CityName??void 0,StateCode:a?.StateCode??void 0,PostalCode:a?.PostalCode??void 0};if(Array.isArray(s)&&s.length>0){let c=0,d=0,p=null;for(const u of s){const m=Array.isArray(u.units)?u.units:[];for(const f of m)if(f.isAdu===!0||f.isAdu==="true")d++;else{const S=PS(f.LivingUnitCount);c+=S??1}const h=PS(u.TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure);h!=null&&(p=(p??0)+h)}n.LivingUnitExcludingADUCount=c>0?c:null,n.AccessoryDwellingUnitTotalCount=d,n.TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure=p}const i=PS(Tj(r,"TotalMonthlyActualRentAmount"))??PS(Tj(r,"EstimatedMonthlyRent"));n.TotalMonthlyActualRentAmount=i;const l=Tj(r,"PropertyRentControlStatusType");return n.PropertyRentControlStatusType=typeof l=="string"&&l.trim()?l.trim():null,n}function Ij(t,a){if(!t)return;const s=t[a];return s&&typeof s=="object"&&"value"in s?s.value:s}function Ax(t){if(t==null||t==="")return null;const a=Number(t);return Number.isFinite(a)?a:null}function B8(t){const{subjectAddress:a,buildings:s,marketData:r,subjectPropertyData:n}=t,i={AddressLineText:a?.AddressLineText??void 0,AddressUnitIdentifier:a?.AddressUnitIdentifier??void 0,CityName:a?.CityName??void 0,StateCode:a?.StateCode??void 0,PostalCode:a?.PostalCode??void 0};if(Array.isArray(s)&&s.length>0){let d=0,p=null;for(const u of s){const m=Array.isArray(u.units)?u.units:[];for(const h of m){if(h.isAdu===!0||h.isAdu==="true")continue;const v=Ax(h.LivingUnitCount)??1;d+=v;const S=Ax(h.FinishedAboveGradeAreaMeasure)??0,N=Ax(h.NonStandardFinishedAboveGradeAreaMeasure)??0,x=Ax(h.FinishedBelowGradeAreaMeasure)??0,y=Ax(h.NonStandardFinishedBelowGradeAreaMeasure)??0,b=S+N+x+y,j=b>0?b:Ax(h.UnitTotalFinishedAreaMeasure)??0;j>0&&(p=(p??0)+j*v)}}i.UnitCount=d>0?d:null,i.UnitTotalFinishedAreaMeasure=p}const l=Ij(r,"NeighborhoodName")??Ij(r,"MarketAreaDescription");i.NeighborhoodName=typeof l=="string"&&l.trim()?l.trim():null;const c=Ij(n,"SiteInfluenceType");return i.SiteInfluenceType=typeof c=="string"&&c.trim()?c.trim():null,i}
39const z8=new Set(["AddressLineText","AddressUnitIdentifier","CityName","StateCode","PostalCode","Latitude","Longitude","ProximityToSubjectDistanceLinearMeasure","LinearUnitOfMeasureType","ComparableToSubjectDirectionType","SiteAreaMeasure","LandOwnedInCommonIndicator","LivingUnitExcludingADUCount","AccessoryDwellingUnitTotalCount","ProjectName","PropertyInProjectIndicator","PUDIndicator","NeighborhoodName","SiteInfluenceType","PropertyPhotoUrl"]),HP=["rentalComparison","grmComparison"];function q8(t,a,s,r){if(!HP.includes(a))return[];const n=s.match(/^Comp(\d+)(.+)$/);if(!n)return[];const i=parseInt(n[1],10),l=n[2];if(!z8.has(l))return[];const c=`Comp${i}SourceCompId`,d=t[a]?.[c]?.value;if(!d||typeof d!="string")return[];const p=[];for(const u of HP){if(u===a)continue;const m=t[u];if(!m)continue;const h=Number(m.CompCount?.value??Y8);for(let f=1;f<=h;f++)m[`Comp${f}SourceCompId`]?.value===d&&p.push({sec:u,fld:`Comp${f}${l}`,val:r})}return p}const Y8=8,G8="rentalComparison",H8="grmComparison";function W8({orderId:t,variant:a,onActiveCompCount:s,maxRentalComps:r,subjectCoordinates:n,subjectImprovements:i,subjectAddress:l}){const{data:c,isLoading:d,isError:p}=Vr({queryKey:["/api/uad36/prefill",t],queryFn:async()=>{const U=await fetch(`/api/uad36/prefill/${t}`);if(!U.ok)throw new Error("Failed to load UAD 3.6 report data");return U.json()},enabled:!!t&&t!=="new"}),[u,m]=o.useState({}),[h,f]=o.useState(!1),[v,S]=o.useState("idle"),N=o.useRef(void 0),x=o.useRef(null);o.useEffect(()=>{c&&!h&&(m(c.sections??{}),N.current=c.conditionality,f(!0))},[c,h]);const y=o.useCallback((U,C)=>u[U]?.[C]?.value??"",[u]),b=o.useCallback((U,C)=>u[U]?.[C],[u]),j=o.useCallback(U=>{x.current&&clearTimeout(x.current),S("saving"),x.current=setTimeout(async()=>{try{const C=await fetch(`/api/uad36/save/${t}`,{method:"POST",headers:{"Content-Type":"application/json",...ho(t)},body:JSON.stringify({sections:U,conditionality:N.current})});S(C.ok?"saved":"idle")}catch{S("idle")}},800)},[t]),T=o.useCallback((U,C,F)=>{m(A=>{const M={value:F,confidence:"manual",source:"user",userEdited:!0};let B={...A,[U]:{...A[U],[C]:M}};const oe=q8(A,U,C,F);for(const{sec:ae,fld:D,val:_}of oe)B={...B,[ae]:{...B[ae],[D]:{value:_,confidence:"manual",source:"user",userEdited:!0}}};return j(B),B})},[j]);o.useEffect(()=>{if(!s||!h)return;const C=Number(u[a==="rental"?G8:H8]?.CompCount?.value??0);s(C>0?C:0)},[u,h,a,s]),o.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]);const O=N.current?.unitCount??c?.conditionality?.unitCount??1,E=N.current?.useIncomeApproach??c?.conditionality?.useIncomeApproach??!1,R=o.useMemo(()=>{if(a!=="rental")return null;const U=l??{AddressLineText:String(u.subjectProperty?.AddressLineText?.value??""),AddressUnitIdentifier:String(u.subjectProperty?.AddressUnitIdentifier?.value??""),CityName:String(u.subjectProperty?.CityName?.value??""),StateCode:String(u.subjectProperty?.StateCode?.value??""),PostalCode:String(u.subjectProperty?.PostalCode?.value??"")},C=i??(()=>{const F=u.improvements?.buildings?.value;return Array.isArray(F)?F:void 0})();return B8({subjectAddress:U,buildings:C,marketData:u.marketConditions,subjectPropertyData:u.subjectProperty})},[a,u,l,i]),G=o.useMemo(()=>{if(a!=="grm")return null;const U=l??{AddressLineText:String(u.subjectProperty?.AddressLineText?.value??""),AddressUnitIdentifier:String(u.subjectProperty?.AddressUnitIdentifier?.value??""),CityName:String(u.subjectProperty?.CityName?.value??""),StateCode:String(u.subjectProperty?.StateCode?.value??""),PostalCode:String(u.subjectProperty?.PostalCode?.value??"")},C=i??(()=>{const F=u.improvements?.buildings?.value;return Array.isArray(F)?F:void 0})();return $8({subjectAddress:U,buildings:C,incomeApproach:u.incomeApproach})},[a,u,l,i]);return d||!h?e.jsxs("div",{className:"flex-1 flex items-center justify-center text-slate-500 gap-2 text-sm","data-testid":"uad36-wizard-grid-loading",children:[e.jsx(za,{className:"w-4 h-4 animate-spin"})," Loading ",a==="rental"?"rental":"GRM"," grid…"]}):p?e.jsx("div",{className:"flex-1 flex items-center justify-center text-red-600 text-sm","data-testid":"uad36-wizard-grid-error",children:"Couldn't load the UAD 3.6 report data for this order."}):e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4","data-testid":`uad36-wizard-grid-${a}`,children:[e.jsx("div",{className:"mb-2 h-4 text-[11px] text-slate-400","data-testid":"uad36-wizard-grid-savestate",children:v==="saving"?"Saving…":v==="saved"?"Saved":""}),a==="rental"?e.jsx(C8,{formData:u,updateField:T,getFieldValue:y,getFieldMeta:b,unitCount:O,subjectPrefill:R,incomeApproachActive:E,maxComps:r}):e.jsx(V8,{formData:u,updateField:T,getFieldValue:y,getFieldMeta:b,subjectCoordinates:n,subjectPrefill:G,incomeApproachActive:E})]})}function K8(t){if(t==null)return null;const a=typeof t=="number"?t:parseInt(String(t).replace(/[^0-9]/g,""),10);return Number.isFinite(a)?a:null}function Q8(t){return typeof t=="string"&&t.toLowerCase().includes("tenant")}function Z8(t){const a=K8(t);return a!=null&&a>=2&&a<=4}
39const WP=[{key:"useSalesComparison",label:"Sales Comparison",desc:"Comparable sales grid",testid:"switch-approach-sales"},{key:"useCostApproach",label:"Cost Approach",desc:"Site value + cost new − depreciation",testid:"switch-approach-cost"},{key:"useSiteValuation",label:"Site Valuation",desc:"Opinion of site value",testid:"switch-approach-site"},{key:"useIncomeApproach",label:"Income Approach",desc:"GRM, Comps, Market Rent",testid:"switch-approach-income"},{key:"useRentalApproach",label:"Rental Information",desc:"Comparable rent schedule",testid:"switch-approach-rental"}];function J8({orderId:t,enableUad36:a=!1,occupancy:s,unitCount:r,variant:n="inline",className:i}){const{enabled:l,approaches:c,setApproach:d,rawConditionality:p,hasManufacturedDwelling:u}=AN(t,a),[m,h]=o.useState(!1),[f,v]=o.useState(!1),[S,N]=o.useState(null);if(!l)return null;const x=c.useRentalApproach.checked,y=c.useIncomeApproach.checked,b=c.useCostApproach.checked,j=Q8(s),T=Z8(r),E=(j||T)&&!x&&!y&&!f,R=WP.filter(B=>!(B.key==="useSiteValuation"&&b||B.key==="useRentalApproach"&&y)),G=WP.some(B=>c[B.key].checked);let U="";j&&T?U="This is a tenant-occupied, 2–4 unit property.":j?U="This property is tenant-occupied.":T&&(U="This looks like a 2–4 unit property.");const C=async B=>{h(!0);try{await d(B)}finally{h(!1)}},F=async()=>{x||await C({useRentalApproach:!0})},A=B=>{const oe=c[B.key],ae=p?.[B.key],D=ae===!0?!0:ae===!1?!1:B.key==="useSalesComparison"?!0:null;return e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-slate-200 bg-white px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Ja,{htmlFor:B.testid,className:"flex items-center gap-1.5 text-[13px] font-medium text-slate-800",children:[B.label,oe.locked&&e.jsx(Hr,{className:"h-3 w-3 shrink-0 text-slate-400"})]}),e.jsx("p",{className:"text-[11px] text-slate-500",children:oe.locked&&oe.reason?oe.reason:B.desc})]}),e.jsx(cy,{value:D,onChange:_=>{if(!oe.locked){if(B.key==="useCostApproach"){if(_!==!0&&oe.checked&&u){N(()=>()=>{C({[B.key]:_})});return}if(_===!0){C({useCostApproach:!0,useSiteValuation:null});return}}C({[B.key]:_})}},testId:B.testid,className:Q("shrink-0 [&_button]:h-5 [&_button]:px-2 [&_button]:text-[11px]",oe.locked&&"pointer-events-none opacity-50")})]},B.key)},M=e.jsxs("div",{className:"space-y-3","data-testid":"uad36-approach-activation",children:[E&&e.jsxs("div",{className:"relative flex items-start gap-2.5 rounded-lg border border-amber-200 bg-amber-50 p-3 pr-7","data-testid":"uad36-approach-suggestion",children:[e.jsx(Ng,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-[13px] font-medium text-amber-900",children:"Add rental information?"}),e.jsxs("p",{className:"mt-0.5 text-[12px] leading-snug text-amber-800",children:[U," Appraisers often include the comparable rent schedule (Form 1007) for these."]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx(De,{size:"sm",className:"h-7 bg-amber-600 px-2.5 text-[12px] hover:bg-amber-700",disabled:m,onClick:F,"data-testid":"button-approach-suggestion-accept",children:"Turn on"}),e.jsx(De,{size:"sm",variant:"ghost",className:"h-7 px-2 text-[12px] text-amber-800 hover:bg-amber-100 hover:text-amber-900",onClick:()=>v(!0),"data-testid":"button-approach-suggestion-dismiss",children:"Not now"})]})]}),e.jsx("button",{type:"button","aria-label":"Dismiss suggestion",className:"absolute right-1.5 top-1.5 rounded p-0.5 text-amber-500 hover:bg-amber-100 hover:text-amber-700",onClick:()=>v(!0),"data-testid":"button-approach-suggestion-close",children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"space-y-2",children:R.map(A)}),e.jsx(WL,{open:S!==null,onOpenChange:B=>{B||N(null)},children:e.jsxs(KL,{overlayClassName:"bg-transparent",className:"max-w-md gap-3 p-4","data-testid":"dialog-mh-cost-approach-confirm",children:[e.jsxs(QL,{className:"space-y-1",children:[e.jsx(ZL,{className:"font-sans text-sm font-semibold",children:"Turn off the Cost Approach?"}),e.jsx(JL,{className:"text-xs leading-relaxed",children:"This report includes a manufactured home. The Selling Guide requires the cost approach for manufactured homes. Are you sure you want to turn it off?"})]}),e.jsxs(XL,{children:[e.jsx(eD,{className:"h-7 px-3 text-xs","data-testid":"button-mh-cost-approach-cancel",children:"Keep Cost Approach"}),e.jsx(tD,{className:"h-7 px-3 text-xs","data-testid":"button-mh-cost-approach-confirm",onClick:()=>{S?.(),N(null)},children:"Turn Off Anyway"})]})]})})]});return n==="compact"?e.jsxs(xn,{children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{type:"button",className:Q("inline-flex items-center gap-1 rounded-md px-2.5 py-1 text-[11px] font-medium ring-1 ring-slate-200 transition-colors",G?"bg-amber-50 text-amber-700 ring-amber-200 hover:bg-amber-100":"bg-white text-slate-600 hover:bg-slate-50 hover:text-slate-800",i),"data-testid":"button-approach-activation",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),"Approaches",E&&e.jsx("span",{className:"ml-0.5 h-1.5 w-1.5 rounded-full bg-amber-500","data-testid":"dot-approach-suggestion"})]})}),e.jsx(yn,{align:"start",className:"w-80 p-3",children:M})]}):e.jsxs("div",{className:Q("rounded-xl border border-slate-200 bg-slate-50/60 p-3",i),children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(Ql,{className:"h-4 w-4 text-slate-500"}),e.jsx("span",{className:"text-[13px] font-medium text-slate-700",children:"Valuation approaches"})]}),M]})}const iy=new Map;function lC(t){const a=iy.get(t);if(a)return a;const s={reconciled:!1};return iy.set(t,s),s}function sM(t){if(typeof t=="number")return Number.isFinite(t)&&t>0?t:null;if(typeof t!="string"||t.trim()==="")return null;const a=Number(t.replace(/[$,\s]/g,""));return Number.isFinite(a)&&a>0?a:null}function rM(t){const a=iy.get(t);
39if(!(!a?.eval?.hydrated||!a.grid?.hydrated||a.reconciled)){if(a.reconciled=!0,a.pendingEdit){const{source:s,value:r}=a.pendingEdit,n=s==="eval"?a.grid:a.eval;n.value!==r&&n.apply(r,"edit"),n.value=r,delete a.pendingEdit;return}a.eval.value!==null?(a.grid.value!==a.eval.value&&a.grid.apply(a.eval.value,"hydrate"),a.grid.value=a.eval.value):a.grid.value!==null&&(a.eval.apply(a.grid.value,"hydrate"),a.eval.value=a.grid.value)}}function nM(t,a,s){const r=lC(t),n={hydrated:!1,value:null,apply:s};return r[a]=n,rM(t),()=>{const i=iy.get(t);!i||i[a]!==n||(delete i[a],i.reconciled=!1,!i.eval&&!i.grid&&iy.delete(t))}}function JT(t,a,s){const r=lC(t)[a];r&&(r.value=sM(s),r.hydrated=!0,rM(t))}function lv(t,a,s){const r=lC(t),n=r[a];if(!n)return;const i=sM(s);n.value=i,n.hydrated=!0,r.reconciled=!0;const l=a==="eval"?r.grid:r.eval;l?.hydrated&&l.value!==i?(l.apply(i,"edit"),l.value=i):l?.hydrated||(r.pendingEdit={source:a,value:i},r.reconciled=!1)}function X8(t){if(!t)return null;const a=iU(t).filter(s=>s.CarStorageType!=="None");return a.length>0?a:null}const jx=(t,a)=>{for(const s of a){const r=t?.[s];if(r!=null&&r!=="")return r}};function iM(t,a,s){const r=[],n=new Set;let i=!1;const l=(h,f)=>{const v=String(h.CarStorageType??"");if(!v)return;const S=r.findIndex(N=>N.CarStorageType===v);if(S>=0){const N=r[S];r[S]={...N,...N.ParkingSpacesCount==null&&h.ParkingSpacesCount!=null?{ParkingSpacesCount:h.ParkingSpacesCount}:{},...!N.CarStorageAttachmentType&&h.CarStorageAttachmentType?{CarStorageAttachmentType:h.CarStorageAttachmentType}:{},fieldSources:{...N.fieldSources??{},...h.fieldSources??{}}},f==="MLS"&&(i=!0);return}n.add(v),r.push(h),f==="MLS"&&(i=!0)},c=dy({compData:t,mlsData:a,prData:s});if(c.kind==="value"){const h=String(c.raw.type??"").toLowerCase(),f=c.source==="PublicRecord"?"public_records":"mls",v=h.includes("carport")?"Carport":"Garage",S=h.includes("detach")?"Detached":h.includes("built")?"BuiltIn":h.includes("attach")?"Attached":void 0,N=c.source==="PublicRecord"?"PublicRecord":"MLS",x=c.source==="PublicRecord"?{...t,...s??{}}:{...t,...a??{}},y=jx(x,v==="Carport"?["CarportSpaces","carportSpaces","CarportSpacesCount","carportSpacesCount","GarageSpaces","garageSpaces","GarageSpacesCount","garageSpacesCount"]:["GarageSpaces","garageSpaces","GarageSpacesCount","garageSpacesCount"]),b=Number(y),j=Number.isFinite(b)&&b>0?b:null;l({id:`source-${c.source.toLowerCase()}-${v.toLowerCase()}`,CarStorageType:v,ParkingSpacesCount:j,...S?{CarStorageAttachmentType:S}:{},fieldSources:{CarStorageType:f,...j!==null?{ParkingSpacesCount:f}:{},...S?{CarStorageAttachmentType:f}:{}}},N)}for(const[h,f,v]of[[{...t,...a??{}},"MLS","mls"],[s,"PublicRecord","public_records"]]){const S=Number(jx(h,["CarportSpaces","carportSpaces","CarportSpacesCount","carportSpacesCount"]));!Number.isFinite(S)||S<=0||l({id:`source-${v}-carport`,CarStorageType:"Carport",ParkingSpacesCount:S,fieldSources:{CarStorageType:v,ParkingSpacesCount:v}},f)}const d=["OpenParkingSpaces","openParkingSpaces","OpenParkingSpacesCount","openParkingSpacesCount"],p=["TotalParkingSpaces","totalParkingSpaces","ParkingTotal","parkingTotal","ParkingSpaces","parkingSpaces"],u=["ParkingFeatures","parkingFeatures","ParkingDescription","parkingDescription"];for(const[h,f,v]of[[{...t,...a??{}},"MLS","mls"],[s,"PublicRecord","public_records"]]){const S=String(jx(h,u)??"").toLowerCase(),N=Number(jx(h,d)),x=Number(jx(h,p)),y=Number.isFinite(N)&&N>0?N:r.length===0&&Number.isFinite(x)&&x>0?x:null,b=Number.isFinite(N)&&N>0?"OpenLot":S.includes("shared driveway")?"SharedDriveway":S.includes("driveway")?"Driveway":S.includes("open parking")||S.includes("open lot")?"OpenLot":S.includes("parking garage")?"ParkingGarage":null;!b||y===null||l({id:`source-${v}-${b.toLowerCase()}`,CarStorageType:b,ParkingSpacesCount:y,fieldSources:{CarStorageType:v,ParkingSpacesCount:v}},f)}if(r.length>0)return{explicitNone:!1,source:i?"MLS":"PublicRecord",items:r};const m=[[{...t,...a??{}},"MLS"],[s,"PublicRecord"]];for(const[h,f]of m){const v=String(jx(h,u)??"").trim();if(/^(?:none|no parking|no vehicle storage)$/i.test(v))return{explicitNone:!0,source:f}}return{explicitNone:!1}}function eW(t,a,s,r){const n=(r-a)*Math.PI/180,i=t*Math.PI/180,l=s*Math.PI/180,c=Math.cos(l)*Math.sin(n),d=Math.cos(i)*Math.sin(l)-Math.sin(i)*Math.cos(l)*Math.cos(n),p=(Math.atan2(c,d)*180/Math.PI+360)%360;return["N","NE","E","SE","S","SW","W","NW"][Math.round(p/45)%8]}
39function KP(t,a,s,r,n){return typeof n=="number"&&n!==0?n:typeof t!="number"||typeof a!="number"||typeof s!="number"||typeof r!="number"?null:Math.round(cW(t,a,s,r)*100)/100}function oM(t,a){if(typeof t!="number"||!Number.isFinite(t))return null;const s=Math.max(0,t).toFixed(t===0?1:2),r=t>0&&a?.trim()?` ${a.trim()}`:"";return`${s} Miles${r}`}function lM(t){const a=String(t??"").trim().toLowerCase();return a==="mls"?"MLS":a==="publicrecord"||a==="public_record"||a==="public record"?"PublicRecord":a==="ai"||a==="ai_derived"?"AI":a==="airbnb"?"Airbnb":"User"}function OS(t){switch(TN(t)){case"SettledSale":return"Sold";case"Active":return"Active";case"Pending":return"Pending";default:return"Unknown"}}function tW(t,a,s,r,n){if(!t||t<=0)return null;const i=String(s??"").toLowerCase().trim(),l=r!=null?parseFloat(String(r)):null;let c=null;if(/bi[\s-]?level|split[\s-]?(level|entry)|raised\s*ranch/.test(i)?c="bilevel":/ranch|rambler|bungalow/.test(i)||l===1?c="ranch":(/2[\s-]?stor|two[\s-]?stor|colonial|cape\s*cod|tudor|victorian|craftsman|georgian/.test(i)||l!=null&&l>=1.5)&&(c="2story"),!c||a===null&&c!=="bilevel")return null;let d;c==="ranch"?d=100:c==="2story"?d=50:d=33;const p=Math.round(t*d/100);let u,m;n==="Finished"?(u=100,m=!1):n==="Partially Finished"?(u=50,m=!1):n==="Unfinished"?(u=0,m=!1):(u=0,m=!0);const h=Math.round(p*u/100);return{basementType:a,estimatedTotal:p,estimatedFinished:h,styleCategory:c,homeStyleLabel:c==="ranch"?"Ranch/1-story":c==="2story"?"2-story":"Bi-level/Split",multiplierPct:d,finishMultiplierPct:u,gla:t,storyCount:l,isInferred:!1,...m?{finishUnknown:!0}:{}}}function cC(t){if(t==null)return{acres:null,sf:null,cleared:!0};const a=String(t).trim();if(a===""||a==="–"||a==="-")return{acres:null,sf:null,cleared:!0};const s=a.toLowerCase(),r=s.replace(/,/g,"").match(/-?\d+(\.\d+)?/);if(!r)return{acres:null,sf:null,cleared:!0};const n=parseFloat(r[0]);return!isFinite(n)||n<0?{acres:null,sf:null,cleared:!0}:/\bac(re)?s?\b/.test(s)?{acres:n,sf:Math.round(n*43560),cleared:!1}:{acres:n/43560,sf:n,cleared:!1}}function aW(t,a=!1,s,r,n,i,l,c,d=!1,p=!1){let u=s;const m=t.mlsData,h=t.publicRecordData,f=t,v=Array.isArray(f.transferHistory)?f.transferHistory:void 0,S=(Ne,Ue,ct,xt)=>{const Na=Ne?n?.[Ne]:void 0;return Na==="MLS"&&Ue!=null?{value:Ue,source:"MLS"}:Na==="PublicRecord"&&ct!=null?{value:ct,source:"PublicRecord"}:Na==="AI"&&xt!=null?{value:xt,source:"AI"}:Ue!=null?{value:Ue,source:"MLS"}:ct!=null?{value:ct,source:"PublicRecord"}:xt!=null?{value:xt,source:"AI"}:{value:null,source:"AI"}},N=(Ne,Ue,ct,xt)=>{let Na=m?.[Ue]??f[Ne]??null,qt=h?.[ct]??null;(Na===""||Na===0)&&(Na=null),(qt===""||qt===0)&&(qt=null);const la=Na!==null,fs=qt!==null,ps=la&&fs&&String(Na).toLowerCase()!==String(qt).toLowerCase(),Te=Na??qt??null,at=S(xt,Na,qt,Te);return{value:at.value,mlsValue:Na,prValue:qt,aiValue:Te,source:at.source,hasConflict:ps,isVerified:!ps&&(la||fs)}},x=(Ne,Ue,ct,xt,Na)=>{const qt=Ne!=null,la=Ue!=null,fs=qt?ct(Ne):null,ps=la?ct(Ue):null,Te=fs!==null&&ps!==null&&fs.toLowerCase()!==ps.toLowerCase(),at=xt??null,yt=S(Na,fs,ps,at);return{value:yt.value,mlsValue:fs,prValue:ps,aiValue:at,source:yt.source,hasConflict:Te,isVerified:!Te&&(qt||la)}},y=t.rawMlsStatus??m?.rawMlsStatus??m?.status??t.status,b=J0(String(y??"")),j=t.isStrProperty?"Rental":b==="CLSD"?"Sold":O0(b)?"Active":"Pending",T=t.photos?.length?t.photos:m?.photos?.length?m.photos:t.photoUrl?[t.photoUrl]:[],O=Ne=>Ne===""||Ne===null||Ne===void 0?null:Ne,E=O(f.saleDate)??O(m?.CloseDate)??O(m?.CloseDateTime)??O(m?.ClosedDate)??O(m?.SoldDate)??O(m?.closeDate),R=O(f.contractDate)??O(m?.contractDate)??O(m?.ContractDate)??O(m?.PurchaseContractDate)??O(m?.purchaseContractDate),G=O(h?.CloseDate)??O(h?.closeDate)??O(h?.saleDate),U=m?.YearBuilt??m?.yearBuilt??f.yearBuilt,C=h?.YearBuilt??h?.yearBuilt,F=m?.RoomsTotal??m?.totalRooms??m?.roomsTotal??f.totalRooms,A=m?.BedroomsTotal??m?.Bedrooms??m?.bedrooms??f.beds,M=m?.BathroomsTotalInteger??m?.BathroomsFull??m?.bathrooms??f.baths,B=F??(()=>{if(A!=null&&M!=null){const Ne=typeof A=="string"?parseInt(A,10)||0:Number(A)||0,Ue=typeof M=="str
39ing"?parseFloat(M)||0:Number(M)||0;return Math.round(Ne+Math.ceil(Ue)+3)}return null})(),oe=h?.BedroomsTotal??h?.bedrooms,ae=h?.BathroomsTotalInteger??h?.bathrooms,D=m?.BathroomsFull??m?.fullBaths??f.fullBathrooms??null,_=m?.BathroomsHalf??m?.halfBaths??f.halfBathrooms??null,$=h?.BathroomsFull??h?.fullBaths??null,z=h?.BathroomsHalf??h?.halfBaths??null,V=m?.BasementBathroomsFull??m?.BathroomsFullBasement??m?.BelowGradeBathroomsFull??m?.basementFullBaths??m?.BsmtFullBaths??f.basementFullBaths??0,le=m?.BasementBathroomsHalf??m?.BathroomsHalfBasement??m?.BelowGradeBathroomsHalf??m?.basementHalfBaths??m?.BsmtHalfBaths??f.basementHalfBaths??0;m?.BasementArea??m?.basementSqft??m?.basementTotalArea??m?.BasementTotalArea??m?.BelowGradeTotalArea??f.basementSqft,m?.BasementFinishedArea??m?.basementFinishedSqft??m?.basementFinishedSf??m?.belowGradeFinishedArea??m?.BelowGradeFinishedArea??m?.BasementFinishedSqFt??f.basementFinishedSqft,h?.BasementArea??h?.basementSqft??h?.basementTotalArea,h?.BasementFinishedArea??h?.basementFinishedSqft??h?.basementFinishedSf,m?.garageSpaces??m?.GarageSpaces??f.garageSpaces;const W=Ne=>Ne&&String(Ne).trim().toLowerCase()!=="none"?Ne:null,me=W(m?.garageType)??W(m?.GarageType)??W(m?.carStorageType)??W(f.garageType)??W(f.carStorageType)??(()=>{if(m?.attachedGarageYN===!0||m?.attachedGarageYN==="Y")return"Attached";const Ne=(m?.parkingFeatures||m?.ParkingFeatures||f.parkingFeatures||"").toString().toLowerCase();return Ne.includes("attached")?"Attached":Ne.includes("detached")?"Detached":Ne.includes("built-in")?"Built-in":Ne.includes("carport")?"Carport":m?.garageYN===!0||m?.garageYN==="Y"?"Attached":null})();h?.GarageSpaces??h?.garageSpaces;const Z=(()=>{const Ne=m?.LotSizeSquareFeet??m?.lotSizeSquareFeet;if(Ne!=null&&Number(Ne)>0)return Number(Ne);const Ue=m?.LotSizeAcres??m?.lotSizeAcres??f.lotSizeAcres;if(Ue!=null&&Number(Ue)>0)return Math.round(Number(Ue)*43560);const ct=m?.lotSize??f.lotSize;return ct!=null&&Number(ct)>0?Number(ct):null})(),pe=(()=>{const Ne=m?.LotSizeAcres??m?.lotSizeAcres??f.lotSizeAcres;if(Ne!=null&&Number(Ne)>0)return Number(Ne);const Ue=m?.LotSizeSquareFeet??m?.lotSizeSquareFeet;if(Ue!=null&&Number(Ue)>0)return Number(Ue)/43560;const ct=m?.lotSize??f.lotSize;return ct!=null&&Number(ct)>0?Number(ct)/43560:null})(),se=h?.LotSizeSquareFeet??h?.lotSize??f.prLotSize,fe=se!=null&&Number(se)>0?Number(se):null,ue=m?.StoriesTotal??m?.Stories??m?.stories??f.stories,be=m?.ArchitecturalStyle??m?.architecturalStyle??m?.style??f.architecturalStyle??f.style??m?.PropertySubType,H=h?.ArchitecturalStyle??h?.architecturalStyle??h?.style,ye=m?.Heating??m?.heating??f.heating,de=m?.Cooling??m?.cooling??f.cooling,ge=m?.squareFeet??m?.LivingArea??m?.GLA??f.gla,Be=h?.squareFeet??h?.LivingArea,He=(()=>{const Ne=[f.dom,f.daysOnMarket,m?.DaysOnMarket,m?.CumulativeDaysOnMarket,m?.CDOM,m?.daysOnMarket];for(const Ue of Ne)if(Ue!=null&&Ue!=="")return Ue;return null})(),Ie=m?.locationRating??f.locationRating,ce=m?.locationType??f.locationType,Pe=m?.viewRating??f.viewRating,We=m?.viewType??f.viewType??m?.view??f.view,Re=m?.attachmentType??f.attachmentType,ne=m?.quality??f.quality,Me=m?.condition??f.condition,lt=m?.functionalUtility??f.functionalUtility,Tt=m?.saleType??f.saleType??(()=>{const Ne=(m?.SpecialListingConditions??m?.specialListingConditions??m?.SaleConditions??m?.saleConditions??m?.SaleType??m?.StatusContractualSearchType??m?.saleTerms??m?.SaleTerms??m?.Terms??f.saleTerms??"").toString().toLowerCase();return Ne.includes("auction")?"ForeclosureSale":Ne.includes("reo")||Ne.includes("bank")||Ne.includes("foreclos")?"REO":Ne.includes("short")?"Short":Ne.includes("estate")?"Estate":Ne.includes("reloc")?"Relo":Ne.includes("court")||Ne.includes("probate")?"CrtOrd":Ne.includes("non-arm")||Ne.includes("nonarm")?"NonArm":Ne.includes("arm")||Ne.includes("standard")||Ne.includes("normal")||Ne.includes("typical")||Ne==="none"?"ArmLth":null})(),je=Tt==null?(()=>{const Ne=m?.saleTerms??m?.SaleTerms??m?.Terms??m?.SaleConditions??m?.SpecialListingConditions??m?.StatusContractualSearchType??f.saleTerms??null,Ue=m?.DistressedYN??m?.distressedYN??m?.distressedYn??f.distressedYN??f.distressedYn,ct=Ue===!0||Ue==="Y"||Ue==="Yes"||Ue==="1";return Ne!=null?ct?`${Ne} · Distressed (verify)`:Ne:ct?"Distressed (verify)":null})():null,Le=(()=>
39{if(Tt!=null||je!=null||!m||!["CLSD","Sold","Closed"].includes(t.status))return null;const Ue=[f.publicRemarks??m?.PublicRemarks??"",f.agentRemarks??m?.PrivateRemarks??""].join(" ").toLowerCase();return["reo","bank owned","bank-owned","foreclos","short sale","estate sale","court ordered","probate","relocation","non-arm","nonarm","distressed"].some(xt=>Ue.includes(xt))?null:"ArmLth"})(),st=m?.concessionsAmount??m?.ConcessionsAmount??m?.ConcessionAmount??m?.SellerConcessionAmount??f.concessionsAmount??null??m?.concessions??f.concessions,Xt=m?.financing??m?.Financing??m?.financingType??m?.FinancingType??m?.FinancingTerms??m?.BuyerFinancing??m?.buyerFinancing??m?.saleTerms??f.financing??f.financingType??f.saleTerms,ua=h?.Financing??h?.financing??h?.FinancingType??h?.financingType??h?.SaleTerms??h?.saleTerms??h?.LoanType??h?.loanType??h?.MortgageType??h?.mortgageType??h?.Terms??h?.terms??null,Oa=f.aiFinancing??f.aiFinancingType??f.aiSaleTerms??null,Xa=x(E?{saleDate:E,contractDate:R}:null,G?{saleDate:G}:null,Ne=>Mm(Ne.saleDate,Ne.contractDate),"–"),qa=Z??fe,os=pe??(fe!=null?fe/43560:null),ya=t.gridFieldOverrides?.site,At=ya&&ya.source==="User"?cC(ya.value):null,Fe=!!(At&&At.cleared),Oe=At?At.cleared?null:At.sf:qa,rt=At?At.cleared?null:At.acres:os,$t=Oe!=null&&Oe>=43560?"ac":"sf",na=x(Z,fe,Ne=>sb(Ne,"sqft"),"–"),zt=!!At,Ua=!!(c&&c.active),Ce=!!(c&&c.active&&c.cleared);if((zt||Ua)&&s){const Ne={...s};if(Fe||Ce)Ne.lotSize=void 0;else if(l==null||l===0)Ne.lotSize=void 0;else{const Ue=rt,ct=Ua?c.acres??null:i??null;Ue==null||ct==null?Ne.lotSize=void 0:Ne.lotSize=Math.round((ct-Ue)*l)}u=Ne}const vt=f.btNormalizedGla??null,sa={...x(ge,Be,Ne=>Iv(Ne),"–"),aiValue:vt!=null&&vt>0?Iv(vt):null},tt=x(U,C,Ne=>String(Ne),"–"),it=(()=>{const Ne=A!=null||M!=null,Ue=oe!=null||ae!=null,ct=Ne?jv(B,A,M,D,_):null,xt=Ue?jv(null,oe,ae,$,z):null,Na=ct!==null&&xt!==null&&ct!==xt,qt=S("aboveGrade",ct,xt,null);return{value:qt.value??"–",mlsValue:ct,prValue:xt,aiValue:ct??xt??null,source:qt.source,hasConflict:Na,isVerified:!Na&&(Ne||Ue)}})();m?.BasementPercentFinished??m?.BasementFinishedPercent;const Je=m?.BasementBedrooms??m?.basementBedrooms??m?.BelowGradeRooms??m?.BedroomsBelowGrade??f.bedroomsBelowGrade??0,ht=h?.BasementBedrooms??h?.BelowGradeRooms??0,Kt=(Ne,Ue,ct)=>{const xt=Ue({compData:f,mlsData:m,prData:null}),Na=Ue({compData:null,mlsData:null,prData:h}),qt=xt.kind==="value"||xt.kind==="confirmed-none"?xt.formatted:null,la=Na.kind==="value"||Na.kind==="confirmed-none"?Na.formatted:null;if(qt==null&&la==null)return{value:"–",mlsValue:null,prValue:null,aiValue:null,source:"AI",hasConflict:!1,isVerified:!1};const fs=S(Ne,qt,la,ct),ps=qt!=null&&la!=null&&qt!==la;return{value:fs.value??qt??la??ct,mlsValue:qt,prValue:la,aiValue:ct,source:fs.source,hasConflict:ps,isVerified:!ps}},Sa=(Ne,Ue)=>{const ct=xt=>{if(xt==null)return xt;const Na=String(xt);if(Na==="–"||Na==="-"||Na==="")return xt;const qt=Ue(Na);return qt===""?null:qt};return{...Ne,value:ct(Ne.value),mlsValue:ct(Ne.mlsValue),prValue:ct(Ne.prValue),aiValue:ct(Ne.aiValue)}},Qt=Sa(Kt("basement",Tv,"0"),nC);(()=>{if(String(Qt.value??"").includes("/"))return;const Ue=typeof ge=="number"&&ge>0?ge:typeof Be=="number"&&Be>0?Be:typeof f.gla=="number"&&f.gla>0?f.gla:null,ct=Tv({compData:f,mlsData:m,prData:null});if(ct.kind==="value"&&ct.raw.total===0&&(ct.raw.type==="Full"||ct.raw.type==="Parti
39al")){const Na=ct.raw.type,qt=ct.raw.qualifier;let la=tW(Ue,Na,be,ue,qt);if(!la&&Ue){const fs=ue!=null?parseFloat(String(ue)):null,ps=qt==="Finished"?100:qt==="Partially Finished"?50:0,Te=Math.round(Ue*.5),at=Math.round(Te*ps/100);la={basementType:Na,estimatedTotal:Te,estimatedFinished:at,styleCategory:null,homeStyleLabel:"Unknown",multiplierPct:50,finishMultiplierPct:ps,gla:Ue,storyCount:fs,isInferred:!1,...qt==null?{finishUnknown:!0}:{}}}la&&(la.isInferred=!0,Qt.value=uy(la.estimatedTotal,la.estimatedFinished),Qt.source="AI",Qt.isVerified=!1,Qt.basementHint=la);return}if(ct.kind==="missing"&&Ue){const Na=String(be??"").toLowerCase().trim(),qt=ue!=null?parseFloat(String(ue)):null;let la=null;/bi[\s-]?level|split[\s-]?(level|entry)|raised\s*ranch/.test(Na)?la="bilevel":/ranch|rambler|bungalow/.test(Na)||qt===1?la="ranch":(/2[\s-]?stor|two[\s-]?stor|colonial|cape\s*cod|tudor|victorian|craftsman|georgian/.test(Na)||qt!=null&&qt>=1.5)&&(la="2story");const fs=la==="ranch"?"Ranch/1-story":la==="2story"?"2-story":la==="bilevel"?"Bi-level/Split":"Unknown",ps=Math.round(Ue*.5);Qt.basementHint={basementType:null,estimatedTotal:ps,estimatedFinished:0,styleCategory:la,homeStyleLabel:fs,multiplierPct:50,finishMultiplierPct:0,gla:Ue,storyCount:qt,isInferred:!1,finishUnknown:!0}}})();const ea=Kt("belowGrade",OI,"0rr 0br 0ba"),tr=Sa(Kt("garageCarport",dy,"None"),rC),ir=(()=>{const Ne=be!=null||ue!=null||Re!=null,Ue=H!=null,ct=Ne&&gg(be)||null,xt=Ue&&gg(H)||null,Na=be?String(be).trim():null,qt=H?String(H).trim():null,la=ct!==null&&xt!==null&&ct!==xt,fs=gg(f.btDesignStyle||null)||null,ps=S("design",ct,xt,fs);return{value:ps.value??(d?Na??qt:null),mlsValue:ct??Na,prValue:xt??qt,aiValue:fs,source:ps.source,hasConflict:la,isVerified:!la&&(ct!=null||xt!=null)}})(),zs=(()=>{const Ne=ye!=null||de!=null,Ue=Ne&&sC(ye,de)||null,ct=Ne&&[ye,de].filter(Boolean).map(String).join(" / ")||null,xt=S("heatingCooling",Ue,null,null);return{value:xt.value,mlsValue:Ue??ct,aiValue:null,source:xt.source,hasConflict:!1,isVerified:Ne&&Ue!=null}})(),pr=Kt("porchPatioDeck",PI,"None"),$e=(()=>{const Ne=Ie!=null||ce!=null,Ue=Ne&&aC(ce)||null,ct=S("location",Ue,null,null);return{value:ct.value,mlsValue:Ue,aiValue:null,source:ct.source,hasConflict:!1,isVerified:Ne}})(),Ot=(()=>{const Ne=Pe!=null||We!=null,Ue=Ne&&tC(We)||null,ct=S("view",Ue,null,null);return{value:ct.value,mlsValue:Ue,aiValue:null,source:ct.source,hasConflict:!1,isVerified:Ne}})(),_e={},ma=f.strProvider??f.strSource??"Airbnb",pt=f.strProviderId??null,re=f.strListingUrl??t.strListingUrl??(pt&&ma?.toLowerCase().includes("airbnb")?`https://www.airbnb.com/rooms/${pt}`:pt&&ma?.toLowerCase().includes("vrbo")?`https://www.vrbo.com/${pt}`:null);if(t.isStrProperty){const Ne=f.strAverageDailyRate??f.price??null,Ue=f.strOccupancyRate??null,ct=f.strGrossRevenue12mo??null;f.strGuestCapacity??f.strMaxGuests,f.strRating,f.strReviewCount;const xt=f.strSource??f.strProvider??"Unknown",Na=Ue?Math.round(Ue/100*365):null,qt=ct?Math.round(ct/12):null;_e.strNightlyRate={value:Ne?`$${Ne}`:null,strValue:Ne?`$${Ne}`:null,strListingUrl:re??void 0,strProvider:ma??void 0,source:Ne!=null?"Airbnb":"AI",hasConflict:!1,isVerified:Ne!=null},_e.strOccupancy={value:Ue?`${Ue}%`:null,strValue:Ue?`${Ue}%`:null,strListingUrl:re??void 0,strProvider:ma??void 0,source:Ue!=null?"Airbnb":"AI",hasConflict:!1,isVerified:Ue!=null},_e.strAnnualNights={value:Na,source:"AI",hasConflict:!1,isVerified:Na!=null},_e.strGrossIncome={value:qt?`$${qt.toLocaleString()}`:null,source:"AI",hasConflict:!1,isVerified:qt!=null},_e.strDataSource={value:xt,source:"AI",hasConflict:!1,isVerified:!0}}else _e.strNightlyRate={value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},_e.strOccupancy={value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},_e.strAnnualNights={value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},_e.strGrossIncome={value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},_e.strDataSource={value:"MLS / Public Record",source:"MLS",hasConflict:!1,isVerified:!0};{const Ne=f.strBedrooms??A??null,Ue=f.strBathrooms??M??null,ct=f.strGLA??ge??null;_e.strBedrooms={value:Ne,strValue:f.strBedrooms??null,strListingUrl:re??void 0,strProvider:ma??void 0,source:f.strBedrooms!=null?"Airbnb":A!=null?"MLS":"AI",hasConflict:!1,isVerified:Ne!=null},_e.strBathrooms={value:Ue,strValue:f.strBathrooms??null,strListingUrl:re??void 0,strProvider:ma??void 0,source:f.strBathrooms!=null?"Airbnb":M!=null?"MLS":"AI",hasConflict:!1,isVerified:Ue!=null},_e.strGLA={value:ct?`${ct}
39 sf`:null,strValue:f.strGLA?`${f.strGLA} sf`:null,strListingUrl:re??void 0,strProvider:ma??void 0,source:f.strGLA!=null?"Airbnb":ge!=null?"MLS":"AI",hasConflict:!1,isVerified:ct!=null},_e.strLocation=$e;const xt=f.strParking??f.parking??null,Na=tr.value,qt=xt??Na??null,la=xt!=null?"Airbnb":Na!=null?"MLS":"AI";_e.strParking={value:qt,strValue:xt??null,strListingUrl:xt!=null?re??void 0:void 0,strProvider:xt!=null?ma??void 0:void 0,source:la,hasConflict:!1,isVerified:qt!=null}}const qe=iM(f,m,h),Ze=Ne=>p?{...Ne,value:null,mlsValue:null,prValue:null,aiValue:null,isVerified:!1}:Ne,It={id:t.id,snapshotId:t.snapshotId,address:t.address,city:t.city,state:t.state,zipCode:t.zip||"",lat:t.coordinates?.lat,lng:t.coordinates?.lng,distance:t.distance,photoUrl:t.primaryPhotoUrl||T[0]||t.photoUrl||null,photos:T,primaryPhotoUrl:t.primaryPhotoUrl||void 0,status:j,rawMlsStatus:y!=null?String(y):null,isSubject:a,isStrProperty:t.isStrProperty,strListingUrl:re??void 0,strProvider:t.isStrProperty?ma:void 0,strComparability:f.strComparability,elsScore:t.echoLocationScore?.score??null,elsTier:t.echoLocationScore?.tier??null,elsFactors:t.echoLocationScore?.factors??null,vehicleStorageItems:(()=>{const Ne=t.vehicleStorageItems;return Ne?.length?Ne:t.vehicleStorageExplicitNone?[]:qe.items})(),vehicleStorageSource:t.vehicleStorageSource??qe.source,vehicleStorageUserEdited:t.vehicleStorageUserEdited,vehicleStorageExplicitNone:t.vehicleStorageExplicitNone??qe.explicitNone,transferHistory:v,fields:{..._e,mlsNumber:{value:f.mlsNumber??m?.mlsNumber??null,source:"MLS",hasConflict:!1,isVerified:!!(f.mlsNumber??m?.mlsNumber)},salePrice:N("price","price","price","salePrice"),SalesContractDate:(()=>{const Ne=O(h?.ContractDate)??O(h?.contractDate)??O(h?.PurchaseContractDate)??O(h?.purchaseContractDate),Ue=S("SalesContractDate",R,Ne,null);return{value:Ue.value,mlsValue:R,prValue:Ne,aiValue:null,source:Ue.source,hasConflict:!1,isVerified:Ue.value!=null}})(),ContractDateUnknownIndicator:(()=>{const Ne=m?.ContractDateUnknownIndicator??m?.contractDateUnknownIndicator??m?.ContractDateUnknownYN??m?.contractDateUnknownYN,Ue=h?.ContractDateUnknownIndicator??h?.contractDateUnknownIndicator??h?.ContractDateUnknownYN??h?.contractDateUnknownYN,ct=S("ContractDateUnknownIndicator",Ne??null,Ue??null,null);return{value:ct.value,mlsValue:Ne??null,prValue:Ue??null,aiValue:null,source:ct.source,hasConflict:!1,isVerified:ct.value!=null}})(),salePricePerGLA:(()=>{const Ne=f.price,Ue=ge??Be,ct=typeof Ne=="number"&&Ne>0&&typeof Ue=="number"&&Ue>0?Math.round(Ne/Ue):null;return{value:ct!=null?`$${ct.toLocaleString()}/sf`:null,source:"AI",hasConflict:!1,isVerified:ct!=null}})(),...(()=>{const Ne=m?.mlsNumber??m?.MlsListingNumber??f.mlsNumber??m?.MLSNumber??null,Ue=Ne?String(Ne):null,ct=!!(Ue&&!Ue.startsWith("comp-")&&!Ue.match(/^[0-9a-f]{8}-[0-9a-f]{4}-/i));return{dataSource:{value:m||ct?"MLS":h?"AssessorRecord":null,source:"AI",hasConflict:!1,isVerified:!!(m||ct||h)},dataSourceIdentifier:{value:ct?`MLS#${Ue}`:null,source:"AI",hasConflict:!1,isVerified:!0}}})(),listPrice:(()=>{const Ne=m?.listPrice??m?.ListPrice??m?.CurrentListPrice??m?.FinalListPrice??f.listPrice??m?.OriginalListPrice??m?.originalListPrice??(j==="Active"&&typeof f.price=="number"&&f.price>0?f.price:null),Ue=Ne!=null&&Number(Ne)>0?Number(Ne):null;return{value:Ue!=null?String(Ue):null,mlsValue:Ue!=null?String(Ue):null,source:"MLS",hasConflict:!1,isVerified:Ue!=null}})(),attachedDetached:(()=>{const Ne=m?.attachmentType??f.attachmentType??null,Ue=m?.PropertyAttachedYN??m?.propertyAttachedYN??f.propertyAttachedYN??void 0,ct=Ne==="Attached"||Ne==="Detached"?Ne:Q0(Ne!=null?String(Ne):null,Ue)??Q0(m?.propertyType??m?.PropertySubType??m?.PropertyType??f.propertyType??null,Ue);return{value:ct,mlsValue:ct,source:"MLS",hasConflict:!1,isVerified:ct!=null}})(),listingStatus:(()=>{const Ne=TN(y!=null?String(y):"");return{value:Ne,mlsValue:Ne,source:"MLS",hasConflict:!1,isVerified:Ne!=null}})(),neighborhoodName:(()=>{const Ne=m?.subdivision??m?.SubdivisionName??m?.subdivisionName??m?.neighborhood??m?.Neighborhood??f.subdivision??null,Ue=Ne!=null&&String(Ne).trim()!==""?Str
39ing(Ne).trim():null;return{value:Ue,mlsValue:Ue,source:"MLS",hasConflict:!1,isVerified:Ue!=null}})(),proximity:(()=>{const Ne=typeof t.distance=="number"&&t.distance>=0?t.distance:null,Ue=oM(Ne,null);return{value:Ue,aiValue:Ue,source:"AI",hasConflict:!1,isVerified:Ne!=null}})(),...(()=>{const Ne=typeof f.price=="number"&&f.price>0?f.price:null,Ue=h?.deedHistory??h?.saleHistory??f.deedHistory??f.saleHistory,ct=lW(Ue,E,Ne),xt=E!=null?String(E).slice(0,10):null,Na=m?.previousSaleDate??m?.PreviousSaleDate??m?.PriorCloseDate??m?.priorCloseDate??null,qt=(()=>{const Wt=Na!=null?String(Na).trim():null;return!Wt||xt&&Wt.startsWith(xt)?null:Wt})(),la=m?.previousSalePrice??m?.PreviousSalePrice??m?.PriorClosePrice??m?.priorClosePrice??null,fs=(()=>{const Wt=la!=null?Number(la):NaN;return!isFinite(Wt)||Wt<=0||Ne!=null&&Math.abs(Wt-Ne)<1?null:String(Math.round(Wt))})(),ps="–",Te=ct.confirmedEmpty?ps:ct.priorSaleDate,at=ct.confirmedEmpty?ps:ct.priorSalePrice!=null?String(Math.round(ct.priorSalePrice)):null,yt=S("priorSaleDate",qt,Te,null),nt=S("priorSalePrice",fs,at,null);return{priorSaleDate:{value:yt.value,mlsValue:qt,prValue:Te,source:yt.source,hasConflict:!1,isVerified:yt.value!=null&&yt.value!==""},priorSalePrice:{value:nt.value,mlsValue:fs,prValue:at,source:nt.source,hasConflict:!1,isVerified:nt.value!=null&&nt.value!==""}}})(),...a?{}:(()=>{const Ne={},Ue=typeof f.price=="number"&&f.price>0?f.price:null,ct=E?String(E).slice(0,10):null;if(ct){Ne.saleHistory0_OwnershipTransferDate={value:ct,mlsValue:ct,source:"MLS",hasConflict:!1,isVerified:!0},Ne.saleHistory0_OwnershipTransferTransactionType={value:"Sale",mlsValue:"Sale",source:"MLS",hasConflict:!1,isVerified:!0};const la=Tt?cp(Tt):null,fs=la?"MLS":Le==="ArmLth"?"AI":null,ps=la??(Le==="ArmLth"?"TypicallyMotivated":null);ps&&fs&&(Ne.saleHistory0_SaleType={value:ps,mlsValue:fs==="MLS"?ps:null,aiValue:fs==="AI"?ps:null,source:fs,hasConflict:!1,isVerified:fs==="MLS"}),Ue!=null?Ne.saleHistory0_OwnershipTransferTransactionAmount={value:String(Ue),mlsValue:String(Ue),source:"MLS",hasConflict:!1,isVerified:!0}:Ne.saleHistory0_OwnershipTransferAmountNotAvailableReasonType={value:"NotDisclosed",mlsValue:"NotDisclosed",source:"MLS",hasConflict:!1,isVerified:!0},Ne.saleHistory0_DataSourceType={value:"MLS",mlsValue:"MLS",source:"MLS",hasConflict:!1,isVerified:!0}}const xt=m?.listingHistory,Na=h?.deedHistory??h?.saleHistory??h?.DeedHistory??h?.SaleHistory,qt=oW(xt,Na,E,Ue);for(let la=0;la<qt.length;la++){const fs=la+1,ps=qt[la],Te=ps.DataSourceType==="MLS"?"MLS":"PublicRecord";Ne[`saleHistory${fs}_OwnershipTransferDate`]={value:ps.OwnershipTransferDate,mlsValue:ps.DataSourceType==="MLS"?ps.OwnershipTransferDate:null,prValue:ps.DataSourceType==="Deed"?ps.OwnershipTransferDate:null,source:Te,hasConflict:!1,isVerified:!0},Ne[`saleHistory${fs}_OwnershipTransferTransactionType`]={value:ps.OwnershipTransferTransactionType,source:Te,hasConflict:!1,isVerified:!0},ps.OwnershipTransferTransactionAmount!=null?Ne[`saleHistory${fs}_OwnershipTransferTransactionAmount`]={value:String(ps.OwnershipTransferTransactionAmount),source:Te,hasConflict:!1,isVerified:!0}:ps.OwnershipTransferAmountNotAvailableReasonType&&(Ne[`saleHistory${fs}_OwnershipTransferAmountNotAvailableReasonType`]={value:ps.OwnershipTransferAmountNotAvailableReasonType,source:Te,hasConflict:!1,isVerified:!0}),Ne[`saleHistory${fs}_DataSourceType`]={value:ps.DataSourceType,source:Te,hasConflict:!1,isVerified:!0},ps.OwnershipTransferTransactionType==="Sale"&&typeof f.gla=="number"&&f.gla>0&&(Ne[`saleHistory${fs}_SaleType`]={value:"TypicallyMotivated",aiValue:"TypicallyMotivated",source:"AI",hasConflict:!1,isVerified:!1})}return Ne})(),dateOfSale:{...Xa,adjustment:u?.time},daysOnMarket:(()=>{const Ne=S("daysOnMarket",He??null,null,null);return{value:Ne.value,mlsValue:He,source:Ne.source,hasConflict:!1,isVerified:He!=null}})(),saleType:(()=>{const Ne=S("saleType",Tt||null,null,Le),Ue=je?String(je).trim():null;return{value:Ne.value,mlsValue:Tt??Ue,aiValue:Le,source:Ne.source,hasConflict:!1,isVerified:!!Tt}})(),financing:(()=>{const Ne=dx(Xt),Ue=dx(ua),ct=dx(Oa),xt=Te=>Te.hasData?Te.noFinancing?"Cash":Te.financing:null,Na=xt(Ne),qt=xt(Ue),la=xt(ct),fs=Na!=null&&qt!=null&&Na!==qt,ps=S("financing",Na,qt,la);return{value:ps.value,mlsValue:Na,prValue:qt,aiValue:la,source:ps.source,hasConflict:fs,isVerified:!fs&&(Ne.hasData||Ue.hasData||ct.hasData)}})(),concessions:(()=>{const Ne=st,Ue=Ne!=null?String(Ne).trim():"",ct=typeof f.price=="number"&&f.price>0?f.price:null,xt=Ue!==""&&(Ue.toLowerCase()==="none"||/^\$?0(\.0+)?$/.test(Ue));if(/^[1-9]$/.test(Ue)&&ct!=null){const fs=parseInt(Ue,10),ps=Math.round(fs/100*ct);return{value:String(ps),mlsValue:Ne,source:"MLS",hasConflict:!1,isVerified:!1,displaySuffix:`(${fs} pt — verify)`}}const qt=ib(Ne);if(qt!=null){const fs=S("concessions",String(qt),null,null);return{value:fs.value,mlsValue:Ne,source:fs.source,hasConflict:!1,isVerified:!0}}
39if(xt)return{value:"0",mlsValue:Ne,source:"MLS",hasConflict:!1,isVerified:!0};if(m)return{value:"0",mlsValue:null,source:"MLS",hasConflict:!1,isVerified:!1};const la=S("concessions",Ue||null,null,null);return{value:la.value,mlsValue:Ne??null,source:la.source,hasConflict:!1,isVerified:!1}})(),financingConcessions:(()=>{const Ne=Tt?cp(Tt):Le?cp(Le):"",Ue=(()=>{const Va=st!=null?String(st).trim():"",Mr=typeof f.price=="number"&&f.price>0?f.price:null;return/^[1-9]$/.test(Va)&&Mr!=null?Math.round(parseInt(Va,10)/100*Mr):ib(st)})(),ct=dx(Xt),xt=dx(ua),Na=dx(Oa),qt=Va=>Pv(Ne,Va.financing,Va.noFinancing,Ue),la=qt(ct),fs=qt(xt),ps=qt(Na),Te=Va=>Va.noFinancing?"Cash":Va.financing,at=ct.hasData&&xt.hasData&&Te(ct)!==Te(xt),yt=S("financingConcessions",ct.hasData?la:null,xt.hasData?fs:null,Na.hasData?ps:null),nt=!!Tt||!!Le||Ue!=null||ct.hasData,Wt=Le&&!ct.hasData&&!xt.hasData&&!Na.hasData?qt({financing:"",noFinancing:!1}):Na.hasData?ps:null,ts=yt.value??(nt?Le&&!Tt?Wt:la:null),gs=yt.value!=null?yt.source:Le&&!Tt&&!ct.hasData?"AI":"MLS";return{value:ts,mlsValue:ct.hasData?la:null,prValue:xt.hasData?fs:null,aiValue:Wt,source:gs,hasConflict:at,isVerified:!at&&(ct.hasData||xt.hasData||Na.hasData)}})(),location:Ze({...$e,adjustment:u?.location}),leaseholdFeeSimple:{value:"Fee Simple",source:"AI",hasConflict:!1,isVerified:!0},site:{...na,adjustment:u?.lotSize,lotSizeSf:Oe,lotSizeAcres:rt,autoSiteUnits:$t},view:Ze(Ot),design:ir,quality:(()=>{const Ne=u?.normalizedQuality||null,Ue=(()=>{const xt=u?.normalizedQualitySource?.toLowerCase();return xt==="mls"||xt==="remarks"?"MLS":xt==="user"?"PublicRecord":ne?"MLS":"AI"})(),ct=S("quality",ne||null,null,Ne);return{value:ct.source==="AI"?Ne:ct.value||Ne,mlsValue:ne,aiValue:Ne,source:n?.quality?ct.source:Ue,hasConflict:!1,isVerified:!!(u?.normalizedQuality||ne),adjustment:u?.quality}})(),yearBuilt:tt,qualityCondition:(()=>{const Ne=u?.normalizedQuality||ne||null,Ue=u?.normalizedCondition||Me||null;return{value:Ne||Ue?`${Ne??"–"} / ${Ue??"–"}`:null,source:"AI",hasConflict:!1,isVerified:!!(Ne&&Ue)}})(),condition:(()=>{const Ne=u?.normalizedCondition||null,Ue=(()=>{const xt=u?.normalizedConditionSource?.toLowerCase();return xt==="mls"||xt==="remarks"?"MLS":xt==="user"?"PublicRecord":Me?"MLS":"AI"})(),ct=S("condition",Me||null,null,Ne);return{value:ct.source==="AI"?Ne:ct.value||Ne,mlsValue:Me,aiValue:Ne,source:n?.condition?ct.source:Ue,hasConflict:!1,isVerified:!!(u?.normalizedCondition||Me),adjustment:u?.condition}})(),...a?{}:(()=>{const Ne={},Ue=u?.normalizedQuality||ne||null,ct=u?.normalizedCondition||Me||null;return Ue&&(Ne.interiorQuality={value:Ue,source:"AI",hasConflict:!1,isVerified:!0}),ct&&(Ne.interiorCondition={value:ct,source:"AI",hasConflict:!1,isVerified:!0}),Ne})(),...(()=>{const Ne={},Ue=yt=>{if(yt==null||yt==="")return null;const nt=typeof yt=="string"?parseFloat(yt):Number(yt);return Number.isFinite(nt)?nt:null},ct=(yt,nt)=>{if(yt==null&&nt==null)return null;const Wt=yt!=null&&nt!=null&&yt!==nt;return{value:String(yt??nt),mlsValue:yt!=null?String(yt):null,prValue:nt!=null?String(nt):null,source:yt!=null?"MLS":"PublicRecord",hasConflict:Wt,isVerified:!Wt}},xt=Ue(A),Na=Ue(oe),qt=ct(xt!=null?xt+(Ue(Je)??0):null,Na!=null?Na+(Ue(ht)??0):null);qt&&(Ne.catalog_BedroomCount_auto=qt);const la=Ue(D),fs=ct(la!=null?la+(Ue(V)??0):null,Ue($));fs&&(Ne.catalog_FullBathroomCount_auto=fs);const ps=Ue(_),Te=ct(ps!=null?ps+(Ue(le)??0):null,Ue(z));Te&&(Ne.catalog_HalfBathroomCount_auto=Te);const at=(()=>{const yt=String(me??"").toLowerCase();return!yt||yt.includes("carport")?null:yt.includes("built")?"BuiltIn":yt.includes("detach")?"Detached":yt.
39includes("attach")?"Attached":null})();return at&&(Ne.garageAttachment={value:at,mlsValue:at,source:"MLS",hasConflict:!1,isVerified:!0}),Ne})(),aboveGrade:{...it,adjustment:(u?.bedrooms??0)+(u?.bathrooms??0)},gla:{...sa,adjustment:u?.gla,...r==="ai"&&sa.aiValue!=null?{source:"AI",value:sa.aiValue}:r==="public-record"&&sa.prValue!=null?{source:"PublicRecord",value:sa.prValue}:{}},basement:{...Qt,adjustment:u?.basement},belowGrade:ea,functionalUtility:(()=>{const Ne=S("functionalUtility",lt||null,null,"None");return{value:Ne.value,mlsValue:lt,aiValue:"None",source:Ne.source,hasConflict:!1,isVerified:!!lt}})(),heatingCooling:zs,energyEfficient:{value:"None",source:"AI",hasConflict:!1,isVerified:!0},garageCarport:{...tr,adjustment:u?.garage},porchPatioDeck:pr,...(()=>{const Ne=u?(u.time??0)+(u.location??0)+(u.gla??0)+(u.condition??0)+(u.quality??0)+(u.bedrooms??0)+(u.bathrooms??0)+(u.basement??0)+(u.garage??0)+(u.lotSize??0):null,Ue=u?Math.abs(u.time??0)+Math.abs(u.location??0)+Math.abs(u.gla??0)+Math.abs(u.condition??0)+Math.abs(u.quality??0)+Math.abs(u.bedrooms??0)+Math.abs(u.bathrooms??0)+Math.abs(u.basement??0)+Math.abs(u.garage??0)+Math.abs(u.lotSize??0):null,ct=typeof f.price=="number"?f.price:null,xt=Ne!=null&&ct!=null?ct+Ne:null,Na=Ne!=null&&ct!=null&&ct>0?(Math.abs(Ne)/ct*100).toFixed(1):"0.0",qt=Ue!=null&&ct!=null&&ct>0?(Ue/ct*100).toFixed(1):"0.0";return{netAdjustment:{value:Ne,source:"AI",hasConflict:!1,isVerified:!!u,displaySuffix:`${Na}%`},grossAdjustment:{value:Ue,source:"AI",hasConflict:!1,isVerified:!!u,displaySuffix:`${qt}%`},adjustedSalePrice:{value:xt,source:"AI",hasConflict:!1,isVerified:!!u}}})()}};if(p){const Ne=v?.[0]??null,Ue=Te=>typeof Te=="string"||typeof Te=="number"?Te:null,ct=Te=>{const at=Ne?.[Te];if(at!=null){if(at&&typeof at=="object"&&"value"in at){const yt=at,nt=Ue(yt.value);return{value:nt,source:lM(yt.source),mlsValue:yt.source==="mls"?nt:null,prValue:yt.source==="public_record"||yt.source==="public_records"?nt:null,aiValue:yt.source==="ai"||yt.source==="ai_derived"?nt:null,hasConflict:!1,isVerified:nt!==null&&nt!==""}}return{value:Ue(at),source:"User",hasConflict:!1,isVerified:!0}}},xt={};for(const Te of["OwnershipTransferTransactionAmount","OwnershipTransferDate","SaleType","TotalSalesConcessionAmount","SalesConcessionIndicator","SalesConcessionAmountKnownIndicator","SalesConcessionsTypicalToMarketIndicator","SaleTypeOtherDescription"]){const at=ct(Te);at&&(xt[Te]=at)}const{salePrice:Na,saleType:qt,dateOfSale:la,concessions:fs,...ps}=It.fields;It.fields={...ps,...xt}}return It}function LS(t,a,s,r="MLS"){const n=t({compData:null,mlsData:a,prData:null});if(n.kind==="value"||n.kind==="confirmed-none"){const i=r==="PublicRecord"?{mlsValue:null,prValue:n.formatted}:{mlsValue:n.formatted,prValue:null};return{value:n.formatted,...i,aiValue:s,source:r,hasConflict:!1,isVerified:!0}}return{value:null,mlsValue:null,prValue:null,aiValue:s,source:r,hasConflict:!1,isVerified:!1}}function DS(t,a,s,r="MLS"){const n={basement:t?.basement??s?.basement?.value,basementSqft:t?.basementSqft??s?.basementSqft?.value,basementFinishedSqft:t?.basementFinishedSqft??s?.basementFinishedSqft?.value,garage:a?.garage??t?.garage??s?.garage?.value,garageType:a?.garage??t?.garage??s?.garage?.value,garageSpaces:t?.garageSpaces??s?.garageSpaces?.value,basementBedrooms:t?.basementBedrooms??s?.basementBedrooms?.value,basementFullBaths:t?.basementFullBaths??s?.basementFullBaths?.value,basementHalfBaths:t?.basementHalfBaths??s?.basementHalfBaths?.value,basementRecRooms:t?.basementRecRooms??s?.basementRecRooms?.value,patioFeatures:t?.patioFeatures??t?.features??s?.patioFeatures?.value};return{basement:LS(Tv,n,uy(0,0),r),belowGrade:LS(OI,n,sD(0,0,0,0),r),garageCarport:LS(dy,n,"None",r),porchPatioDeck:LS(PI,n,wI(null),r),attachedDetached:(()=>{const i=t?.propertyAttachedYN??t?.PropertyAttachedYN??s?.propertyAttachedYN?.value??void 0,l=Q0(t?.propertySubType??t?.propertyType??a?.propertyType??s?.propertyType?.value??null,i);return{value:l,mlsValue:r==="PublicRecord"?null:l,prValue:r==="PublicRecord"?l:null,aiValue:null,source:r,hasConflict:!1,isVerified:l!=null}})()}}function QP(t,a,s,r=0){return Array.isArray(t?.photos)&&t.photos.length>0?t.photos:Array.isArray(a?.photos)&&a.photos.length>0?a.photos:r>0?[]:s}function sW(t,a=0){return a<=0?t:Object.fromEntries(Object.entries(t).map(([s,r])=>r.source!=="MLS"&&r.source!=="PublicRecord"?[s,r]:[s,{...r,value:null,mlsValue:null,prValue:null,isVerified:!1}]))}function Kb(t,a,s="MLS"){if(!a)return t;const r={...t.fields},n=(p,u=s)=>({value:p??null,source:u,hasConflict:!1,isVerified:!0});if(a.lastSalePrice!=null&&t.fields.salePrice&&(r.salePrice=n(a.lastSalePrice,"MLS")),a.lastSaleDate&&t.fields.dateOfSale){const u=(typeof t.fields.dateOfSale?.value=="string"?t.fields.dateOfSale.value:"").match(/;?(c\d{2}\/\d{2})/),m=u?u[1]:null,h=Mm(a.lastSaleDate,null);r.dateOfSale=n(m?`${h};${m}`:h,"MLS")}if(a.lotSizeAcres!=null){const p=Math.round(a.lotSizeAcres*43560);r.site=n(p>43560?`${a.lotSizeAcres.toFixed(2)}
39 ac`:`${p.toLocaleString()} sf`)}if(a.view&&(r.view=n(a.view)),a.design&&(r.design=n(a.design)),a.yearBuilt!=null&&(r.yearBuilt=n(a.yearBuilt)),a.bedrooms!=null||a.bathrooms!=null){const p=a.bedrooms??0,u=a.bathrooms??0,m=p+Math.ceil(u)+2,h=Uh(null,null,u);r.aboveGrade=n(`${m}|${p}|${h}`)}if(a.gla!=null&&(r.gla=n(`${a.gla.toLocaleString()} sf`)),a.basementSqft!=null&&a.basementSqft>0||a.basementFinishedSqft!=null&&a.basementFinishedSqft>0){const p=a.basementSqft??0,u=a.basementFinishedSqft??0;r.basement=n(uy(p,u))}a.functionalUtility&&(r.functionalUtility=n(a.functionalUtility)),a.heatingCooling&&(r.heatingCooling=n(a.heatingCooling)),a.energyEfficient&&(r.energyEfficient=n(a.energyEfficient));const i=t.fields.garageCarport?.value;!(i!=null&&i!=="–"&&i!=="")&&a.garageSpaces!=null&&a.garageSpaces>0&&(r.garageCarport=n(`${a.garageSpaces} Garage`));const c=t.fields.porchPatioDeck?.value,d=c!=null&&c!=="–"&&c!=="";if(a.porchPatioDeck&&!d&&(r.porchPatioDeck=n(a.porchPatioDeck)),a.customFeatures)for(const[p,u]of Object.entries(a.customFeatures))u!=null&&String(u).trim()!==""&&(r[p]=n(u),p.startsWith("catalog_")||(r[`catalog_${p}_auto`]=n(u)));if(a.gridSubjectOverrides)for(const[p,u]of Object.entries(a.gridSubjectOverrides))u==null||u.value==null||String(u.value).trim()===""||(r[p]={...r[p]||{},value:u.value,source:u.source,hasConflict:!1,isVerified:!0});return{...t,fields:r}}function Qb(t){const a=t?.estateType,s=typeof a?.value=="string"&&a.value.trim()!==""?a.value.trim():"Fee Simple",r=String(a?.source||""),n=r==="Manual"||r==="User"||a?.isEdited?"User":r==="MLS"?"MLS":r==="PR"||r==="PublicRecord"?"PublicRecord":"AI";return{leaseholdFeeSimple:{value:s,source:n,hasConflict:!1,isVerified:a?.value!=null},location:{value:null,source:"AI",hasConflict:!1,isVerified:!1}}}const ZP=new Set(["gla","yearBuilt","aboveGrade","site","view","design","quality","condition","basement","garageCarport","porchPatioDeck","functionalUtility","heatingCooling","energyEfficient"]);function rW(t,a){if(!a)return a;const s=t?.gridSubjectOverrides;if(!s)return a;const r={};for(const[n,i]of Object.entries(s)){const l=cM(n);!ZP.has(n)&&!ZP.has(l)&&!(a.customFeatures&&(n in a.customFeatures||l in a.customFeatures))&&(r[n]=i)}return Object.keys(r).length>0?{...a,gridSubjectOverrides:r}:a}function cM(t){const a=t.match(/^catalog_(.+)_auto$/);if(a)return a[1];const s=t.match(/^catalog_(.+)_(\d{10,})$/);return s?s[1]:t}const nW={FunctionalIssueTypeOtherDescription:"functionalIssueOtherDescription",EfficiencyRatingName:"efficiencyRatingName",EfficiencyRatingScoreValue:"efficiencyRatingScore",GreenCertificationName:"greenCertificationName",GreenCertificationLevelName:"greenCertificationLevel",RenewableEnergyComponentType:"renewableEnergyType",BelowGradeExteriorAccessType:"basementAccess"},iW={EfficiencyRatingExistsIndicator:"efficiencyRatingExists",GreenCertificationExistsIndicator:"greenCertificationExists",RenewableEnergyComponentExistsIndicator:"renewableEnergyExists"};function XT(t,a){const s=cM(t),r=String(a).trim(),n=c=>{const d=parseFloat(c.replace(/[$,%]/g,"").replace(/,/g,""));return Number.isFinite(d)?d:null},i={},l={};switch(s){case"gla":{const c=n(r);c!=null&&c>0&&(i.gla=Math.round(c),l.gla=Math.round(c));break}case"yearBuilt":{const c=n(r);c!=null&&c>1600&&c<2200&&(i.yearBuilt=Math.round(c),l.yearBuilt=Math.round(c));break}case"site":{const c=n(r);if(c!=null&&c>0){const d=/ac/i.test(r)?c:c/43560;i.lotSizeAcres=d,l.lotSize=Math.round(d*43560)}break}case"view":{r&&(i.view=r,l.view=r);break}case"design":{const c=r.match(/^([A-Za-z]+)(\d+(?:\.\d+)?)?;?/);c&&(i.design=c[1],c[2]!=null&&(i.stories=parseFloat(c[2])),l.design=r);break}case"quality":{if(/^Q[1-6]$/i.test(r)){const c=r.toUpperCase();i.quality=c,l.quality=c}break}case"condition":{if(/^C[1-6]$/i.test(r)){const c=r.toUpperCase();i.condition=c,l.condition=c}break}case"aboveGrade":{const c=r.split("|");if(c.length===3){const d=n(c[1]),p=c[2].split("."),u=n(p[0]??""),m=p.length>1?n(p[1]??""):0;if(d!=null&&(i.bedrooms=Math.round(d),l.beds=Math.round(d)),u!=null){const h=u+(m!=null?m*.5:0);i.bathrooms=h,l.baths=h,l.bathsFull=Math.round(u),l.bathsHalf=m!=null?Math.round(m):0}}break}case"basement":{const c=r.match(/^([\d,]+)\s*\/\s*([\d,]+)/),d=r.match(/;\s*([\d,]+)\s*sfin/i),p=r.match(/^([\d,]+)/),u=c?n(c[1]):p?n(p[1]):null;if(u!=null){i.basementSqft=Math.round(u),l.basement=Math.round(u);const m=c?c[2]:d?d[1]:null,h=m!=null?n(m):null;h!=null&&(i.basementFinishedSqft=Math.round(h));const f=h!=null?Math.round(h):0;l.basementFinishedSqft=f,l.basementUnfinishedSqft=Math.max(0,Math.round(u)-f)}break}case"garageCarport":{let c=0,d=!1;for(const p of r.split(";")){const u=p.trim().match(/^(\d+)/);u&&(c+=parseInt(u[1],10),d=!0)}d&&(i.garageSpaces=c,l.garage=c),r&&(l.garageCarport=r);break}case"heatingCooling":{r&&(i.heatingCooling=r,l.heatingCooling=r);break}case"functionalUtility":{r&&(i.functionalUtility=r,l.functionalUtility=r.split(/\s*,\s*/).join("|"));break}case"energyEfficient":{r&&(i.energyEfficient=r);break}case"porchPatioDeck":{r&&(i.porchPatioDeck=r,l.porchPatioDeck=r);break}case"AmenityType_WaterFeatures":{r&&(l.pool=r,i.pool=r.split("|").some(c=>["IngroundPool","IngroundSpa"].includes(c.trim())));break}case"AmenityType_OutdoorLiving":{r&&(l.porchPatioDeck=r);break}case"salePrice":{const c=n(r);c!=null&&c>0&&(i.lastSalePrice=c);break}case"BedroomCount":{const c=n(r);c!=null&&c>=0&&(i.bedrooms=Math.round(c),l.beds=Math.round(c));break}case"FullBathroomCount":{const c=n(r);c!=null&&c>=0&&(l.bathsFull=Math.round(c));break}case"HalfBathroomCount":{const c=n(r);c!=null&&c>=0&&(l.bathsHalf=Math.round(c));break}case"FunctionalIssueType":{r&&(i.functionalUtility=r,l.functionalUtility=r);break}default:{const c=nW[s];if(c){r&&(l[c]=r);break}const d=iW[s];if(d){(r==="true"||r==="false")&&(l[d]=r==="true"?"Yes":"No");break}!["dateOfSale","financingConcessions","leaseholdFeeSimple"].includes(s)&&r&&(l[s]=r);break}}return{vsPatch:i,verifySelections:l}}function oW(t,a,s,r){const n=s?new Date(String(s).slice(0,10)).getTime():null,i=3*365.25*24*60*60*1e3,l=Number.isFinite(n)?n-i:Date.now()-i,c=(u,m)=>n==null||!Number.isFinite(n)||Math.abs(u-n)/864e5>30?!1:r!=null&&r>0&&m!=null?Math.abs(m-r)/r<=.05:!0,d=[];if(Array.isArray(t)&&t.length>0)for(const u of t){if(!u||typeof u!="object")continue;const m=String(u.status??u.Status??"").toLowerCase(),h=!!(u.closeDate??u.CloseDate??u.closedDate??u.ClosedDate);if(!(m==="sold"||m==="closed"||m==="clsd"||h))continue;const v=u.closeDate??u.CloseDate??u.closedDate??u.ClosedDate??u.soldDate??u.SoldDate??u.saleDate??u.SaleDate,S=v!=null?String(v).slice(0,10):null;if(!S||!/^\d{4}-\d{2}-\d{2}$/.test(S))continue;const N=new Date(S+"T00:00:00Z").getTime();if(!Number.isFinite(N))continue;const x=u.closePrice??u.ClosePrice??u.closedPrice??u.ClosedPrice??u.soldPrice??u.SoldPrice,y=x!=null&&x!==""?Number(String(x).replace(/,/g,"")):NaN,b=Number.isFinite(y)&&y>0?y:null;c(N,b)||N<l||d.push({OwnershipTransferDate:S,OwnershipTransferTransactionType:"Sale",OwnershipTransferTransactionAmount:b,OwnershipTransferAmountNotAvailableReasonType:b==null?"NotDisclosed":"",DataSourceType:"MLS"})}if(d.length>0)return d.sort((u,m)=>m.OwnershipTransferDate.localeCompare(u.OwnershipTransferDate)),d.slice(0,Vm);const p=[];if(Array.isArray(a)&&a.length>0)for(const u of a){if(!u||typeof u!="object")continue;const m=u.recordingDate??u.closeDate??u.contractDate??u.SaleDate??u.LastSaleDate??u.RecordingDate??u.LastSaleRecordingDate??u.TransferDate??u.date??u.Date??u.CloseDate??null,h=m!=null?String(m).trim().slice(0,10):null;if(!h||!/^\d{4}-\d{2}-\d{2}$/.test(h))continue;const f=new Date(h+"T00:00:00Z").getTime();if(!Number.isFinite(f))continue;const v=u.salePrice??u.closePrice??u.SalePrice??u.LastSalePrice??u.ClosePrice??u.Amount??u.price??u.Price??null,S=v!=null&&v!==""?Number(String(v).replace(/,/g,"")):NaN,N=Number.isFinite(S)&&S>0?S:null;if(c(f,N)||f<l)continue;const x=N!=null?"Sale":"DeedTransferOnly";p.push({OwnershipTransferDate:h,OwnershipTransferTransactionType:x,OwnershipTransferTransactionAmount:N,OwnershipTransferAmountNotAvailableReasonType:N==null?"NotDisclosed":"",DataSourceType:"Deed"})}return p.sort((u,m)=>m.OwnershipTransferDate.localeCompare(u.OwnershipTransferDate)),p.slice(0,Vm)}function lW(t,a,s){if(!t||!Array.isArray(t)||t.length===0)return{priorSaleDate:null,priorSalePrice:null,confirmedEmpty:!1};const r=[];for(const d of t){if(!d||typeof d!="object")continue;const p=d.recordingDate??d.closeDate??d.contractDate??d.SaleDate??d.LastSaleDate??d.RecordingDate??d.LastSaleRecordingDate??d.TransferDate??d.date??d.Date??d.CloseDate??null,u=p!=null?String(p).trim():null;if(!u)continue;const m=d.salePrice??d.closePrice??d.SalePrice??d.LastSalePrice??d.ClosePrice??d.Amount??d.price??d.Price??null,h=m!=null&&m!==""?Number(m):NaN;r.push({date:u,price:Number.isFinite(h)&&h>0?h:null})}if(r.length===0)return{priorSaleDate:null,priorSalePrice:null,confirmedEmpty:!1};r.sort((d,p)=>p.date.localeCompare(d.date));const n=a?new Date(String(a).slice(0,10)).getTime():null,i=d=>
39{if(n==null)return!1;const p=new Date(d.date.slice(0,10)).getTime();return!Number.isFinite(p)||Math.abs(p-n)/864e5>30?!1:s!=null&&s>0&&d.price!=null?Math.abs(d.price-s)/s<=.05:!0},l=r.filter(d=>!i(d));if(l.length===0)return{priorSaleDate:null,priorSalePrice:null,confirmedEmpty:!0};const c=l[0];return{priorSaleDate:c.date,priorSalePrice:c.price,confirmedEmpty:!1}}const cW=lb,dW=[{id:"adjustedPricePerUnit",label:"Adjusted Price / Unit",gateId:"summaryMultiUnit"},{id:"adjustedPricePerBedroom",label:"Adjusted Price / Bedroom",gateId:"summaryMultiUnit"},{id:"pricePerGrossBuildingFinishedArea",label:"Price / Gross Bldg. Finished Area",gateId:"summaryMultiUnitSubject",perUnitLabel:"sf"},{id:"pricePerAboveGradeFinishedArea",label:"Price / Above-Grade Finished Area",gateId:"summarySingleUnitAboveGrade",perUnitLabel:"sf"},{id:"adjustedPrice",label:"Adjusted Price"}];function Cj(t){if(t==null||t==="")return null;const a=typeof t=="number"?t:Number(String(t).replace(/[^0-9.-]/g,""));return Number.isFinite(a)?a:null}function uW(t,a){return{salePrice:t("SalePrice"),contractPrice:t("SalesContractAmount"),listPrice:t("FinalListPriceAmount"),netAdjustment:a,listingStatusType:t("ListingStatusType"),livingUnitCount:t("LivingUnitExcludingADUCount"),bedroomCount:t("BedroomCount"),totalFinishedArea:t("TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure"),aboveGradeStandardArea:t("UnitStandardAboveGradeFinishedAreaMeasure"),aboveGradeNonStandardArea:t("UnitNonStandardAboveGradeFinishedAreaMeasure")}}function JP(t,a){const s=uW(t,a),r=Cj(s.livingUnitCount),n=(Cj(s.aboveGradeStandardArea)??0)+(Cj(s.aboveGradeNonStandardArea)??0);return{multiUnit:X7(s.livingUnitCount),livingUnitCount:r,aboveGradeArea:n,result:eH(s)}}function pW(t,a,s){switch(t.gateId){case void 0:return!0;case"summaryMultiUnit":return a.multiUnit||s.some(r=>r.multiUnit);case"summaryMultiUnitSubject":return a.multiUnit;case"summarySingleUnitAboveGrade":{const r=n=>n.livingUnitCount===1&&n.aboveGradeArea>0;return r(a)||s.some(r)}default:return!0}}function XP(t,a){const{result:s}=a;switch(t.id){case"adjustedPricePerUnit":return a.livingUnitCount===1?{kind:"em-dash"}:Zb(s.adjustedPricePerUnit);case"adjustedPricePerBedroom":return a.livingUnitCount===1?{kind:"em-dash"}:Zb(s.adjustedPricePerBedroom);case"pricePerAboveGradeFinishedArea":return a.livingUnitCount===1&&a.aboveGradeArea>0?Zb(s.pricePerAboveGradeFinishedArea):{kind:"em-dash"};case"pricePerGrossBuildingFinishedArea":return Zb(s.pricePerGrossBuildingFinishedArea);case"adjustedPrice":return Zb(s.adjustedPrice);default:return{kind:"blank"}}}function Zb(t){return t===null?{kind:"blank"}:{kind:"value",amount:t}}function e1(t,a){return t===null||!Number.isFinite(t)?"":t<0?`(${a(Math.abs(t)).replace(/^[-+]/,"")})`:a(t)}const Zv="__clear__";function mW(t){return t.improvementType==="Dwelling"||t.improvementType==="Outbuilding"&&t.outbuildingRealPropertyIndicator===!0}function hW(){return{id:`unit_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,isAdu:!1}}function fW(t){const a=`structure_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;return t==="Dwelling"?{id:a,order:0,improvementType:t,label:null,outbuildingType:null,outbuildingTypeOtherDescription:null,outbuildingRealPropertyIndicator:null,attachmentType:null,structuralDesignType:null,constructionMethods:[],manufacturedHomeWidthType:null,units:[]}:{id:a,order:0,improvementType:t,label:null,attachmentType:null,structuralDesignType:null,constructionMethods:[],manufacturedHomeWidthType:null,outbuildingType:null,outbuildingTypeOtherDescription:null,outbuildingRealPropertyIndicator:null,units:[]}}function gW(t,a,s){if(a<0||s<0||a>=t.length||s>=t.length||a===s)return t;const r=t.slice(),[n]=r.splice(a,1);return r.splice(s,0,n),r}function N0({field:t,value:a,onChange:s,placeholder:r,disabled:n,testId:i,className:l}){const c=Pr(t)??[];return e.jsxs(sr,{value:a==null||a===""?void 0:a,onValueChange:d=>s(d===Zv?null:d),disabled:n,children:[e.jsx(rr,{className:Q("h-7 text-xs placeholder-hint",l),"data-testid":i,children:e.jsx(or,{placeholder:r??"Select…"})}),e.jsxs(nr,{children:[e.jsx(vs,{value:Zv,children:e.jsx("span",{className:"text-muted-foreground",children:"— Clear —"})}),c.map(d=>e.jsx(vs,{value:d,children:Dc(t,d)},d))]})]})}function cv({value:t,onChange:a,disabled:s,testId:r,className:n}){const i=t===!0?"true":t===!1?"false":void 0;return e.jsxs(sr,{value:i,onValueChange:l=>a(l===Zv?null:l==="true"),disabled:s,children:[e.jsx(rr,{className:Q("h-7 text-xs placeholder-hint",n),"data-testid":r,children:e.jsx(or,{placeholder:"—"})}),e.jsxs(nr,{children:[e.jsx(vs,{value:Zv,children:e.jsx("span",{className:"text-muted-foreground",children:"— Clear —"})}),e.jsx(vs,{value:"true",children:"Yes"}),e.jsx(vs,{value:"false",children:"No"})]})]})}function xW({unit:t,onChange:a,onRemove:s,disabled:r,testId:n,inspectPrefix:i}){return e.jsxs("div",{className:"flex items-center gap-2 rounded border bg-slate-50 px-2 py-1",children:[e.jsxs("label",{className:"flex items-center gap-1 text-xs",children:[e.jsx("input",{type:"checkbox",checked:t.isAdu,onChange:l=>a({...t,isAdu:l.target.checked}),disabled:r,"data-testid":`${n}-adu`}),"ADU",e.jsx(Fs,{section:"salesComparison",fieldName:`${i}.AccessoryDwellingUnitIndicator`})]}),e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"ml-auto h-6 w-6 p-0 text-muted-foreground hover:text-red-600",onClick:s,disabled:r,"data-testid":`${n}-remove`,title:"Remove unit",children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})]})}function bW({structure:t,index:a,total:s,onChange:r,onRemove:n,onMove:i,disabled:l,compNumber:c,inspectPrefix:d}){const p=t.improvementType==="Dwelling",u=mW(t),m=t.constructionMethods.includes("Manufactured"),h=`comp${c}-structure${a}`,f=Pr("ConstructionMethodType")??[],v=x=>{const b=t.constructionMethods.includes(x)?t.constructionMethods.filter(j=>j!==x):[...t.constructionMethods,x];r({...t,constructionMethods:b})},S=(x,y)=>r({...t,units:t.units.map(b=>b.id===x?y:b)}),N=p?`Dwelling ${a+1}`:`Outbuilding ${a+1}`;return e.jsxs("div",{className:"rounded border p-2 space-y-2","data-testid":h,children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("input",{type:"text",className:"h-6 min-w-0 flex-1 rounded border border-transparent bg-transparent px-1 text-xs font-semibold text-slate-700 placeholder-hint hover:border-slate-200 focus:border-blue-400 focus:outline-none",value:t.label??"",placeholder:N,disabled:l,"data-testid":`${h}-label`,onChange:x=>r({...t,label:x.target.value||null}),title:"Building label shown in Structure ID rows"}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:()=>i(a-1),disabled:l||a===0,"data-testid":`${h}-up`,title:"Move up",children:e.jsx(Du,{className:"h-3.5 w-3.5"})}),e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:()=>i(a+1),disabled:l||a===s-1,"data-testid":`${h}-down`,title:"Move down",children:e.jsx(Rr,{className:"h-3.5 w-3.5"})}),e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-muted-foreground hover:text-red-600",onClick:n,disabled:l,"data-testid":`${h}-remove`,title:"Remove structure",children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})]})]}),p?e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Attachment"}),e.jsx(Fs,{section:"salesComparison",fieldName:`${d}.AttachmentType`}
39),e.jsx(N0,{field:"AttachmentType",value:t.attachmentType,onChange:x=>r({...t,attachmentType:x}),disabled:l,testId:`${h}-attachment`})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Structural Design"}),e.jsx(Fs,{section:"salesComparison",fieldName:`${d}.StructuralDesignType`}),e.jsx(N0,{field:"StructuralDesignType",value:t.structuralDesignType,onChange:x=>r({...t,structuralDesignType:x}),disabled:l,testId:`${h}-design`})]}),e.jsxs("div",{className:"col-span-2 space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Construction Method(s)"}),e.jsx(Fs,{section:"salesComparison",fieldName:`${d}.ConstructionMethodType`}),e.jsx("div",{className:"flex flex-wrap gap-1",children:f.map(x=>{const y=t.constructionMethods.includes(x);return e.jsx("button",{type:"button",className:Q("rounded border px-1.5 py-0.5 text-[10px]",y?"border-blue-500 bg-blue-50 text-blue-700":"border-slate-200 text-slate-600 hover:bg-slate-50"),onClick:()=>v(x),disabled:l,"data-testid":`${h}-cm-${x}`,children:Dc("ConstructionMethodType",x)},x)})})]}),m&&e.jsxs("div",{className:"col-span-2 space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Manufactured Home Width"}),e.jsx(Fs,{section:"salesComparison",fieldName:`${d}.ManufacturedHomeWidthType`}),e.jsx(N0,{field:"ManufacturedHomeWidthType",value:t.manufacturedHomeWidthType,onCh
39ange:x=>r({...t,manufacturedHomeWidthType:x}),disabled:l,testId:`${h}-mhwidth`,className:"w-40"})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Outbuilding Type"}),e.jsx(Fs,{section:"salesComparison",fieldName:`${d}.OutbuildingType`}),e.jsx(N0,{field:"OutbuildingType",value:t.outbuildingType,onChange:x=>r({...t,outbuildingType:x}),disabled:l,testId:`${h}-obtype`})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Real Property?"}),e.jsx(Fs,{section:"salesComparison",fieldName:`${d}.OutbuildingRealPropertyIndicator`}),e.jsx(cv,{value:t.outbuildingRealPropertyIndicator,onChange:x=>r({...t,outbuildingRealPropertyIndicator:x}),disabled:l,testId:`${h}-realprop`})]}),t.outbuildingType==="Other"&&e.jsxs("div",{className:"col-span-2 space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Other Description"}),e.jsx(Fs,{section:"salesComparison",fieldName:`${d}.OutbuildingTypeOtherDescription`}),e.jsx(ze,{type:"text",className:"h-7 text-xs",value:t.outbuildingTypeOtherDescription??"",onChange:x=>r({...t,outbuildingTypeOtherDescription:x.target.value===""?null:x.target.value}),disabled:l,"data-testid":`${h}-obother`})]})]}),u&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Units"}),e.jsxs(De,{type:"button",size:"sm",variant:"ghost",className:"ml-auto h-6 px-1 text-[10px] text-blue-600",onClick:()=>r({...t,units:[...t.units,hW()]}),disabled:l,"data-testid":`${h}-add-unit`,children:[e.jsx(un,{className:"mr-0.5 h-3 w-3"})," Add unit"]})]}),t.units.map((x,y)=>e.jsx(xW,{unit:x,onChange:b=>S(x.id,b),onRemove:()=>r({...t,units:t.units.filter(b=>b.id!==x.id)}),disabled:l,testId:`${h}-unit${y}`,inspectPrefix:`${d}.units.${tb(x.id)}`},x.id))]})]})}function yW({itemId:t,compNumber:a,fields:s,structures:r,onFieldChange:n,onStructuresChange:i,onProjectClassificationChange:l,disabled:c,showPropertyRights:d}){const p=T=>i(T),u=T=>p([...r,fW(T)]),m=(T,O)=>p(r.map(E=>E.id===T?O:E)),h=T=>p(r.filter(O=>O.id!==T)),f=(T,O)=>p(gW(r,T,O)),v=o.useMemo(()=>{const T=String(s.ProjectClassificationType?.value??"");if(T)return T;const O=String(s.ProjectLegalStructureType?.value??"");if(O==="Condominium"||O==="Condop"||O==="Cooperative")return O;const E=s.PUDIndicator?.value;return E===!0||E==="true"?"PUD":""},[s]),S=T=>{if(l){l(T);return}},N=T=>{const O=s[T]?.value;return O===!0||O==="true"?!0:O===!1||O==="false"?!1:null},x=(T,O)=>n(T,O),y=r.filter(T=>T.improvementType==="Dwelling").length,b=r.length-y,j=T=>Zi(t,`fields.${T}`);return e.jsxs(xn,{children:[e.jsx(bn,{asChild:!0,children:e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-muted-foreground hover:text-blue-600","data-testid":`button-comp${a}-structures`,title:`Comp ${a} facts & structures`,"aria-label":`Comp ${a} facts & structures`,children:e.jsx(w5,{className:"h-3.5 w-3.5"})})}),e.jsxs(yn,{align:"end",className:"w-96 p-0","data-testid":`popover-comp${a}-structures`,children:[e.jsxs("div",{className:"border-b px-3 py-2 text-sm font-semibold",children:["Comp ",a," facts & structures"]}),e.jsx(Qd,{className:"max-h-[70vh]",children:e.jsxs("div",{className:"space-y-3 p-3 text-left",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-slate-500",children:"Structures"}),e.jsx(Fs,{section:"salesComparison",fieldName:j("Dwellings"),displayLabel:"Dwellings"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[y," dwelling",y===1?"":"s",b>0?`, ${b} outbuilding${b===1?"":"s"}`:""]})]}),r.map((T,O)=>e.jsx(bW,{structure:T,index:O,total:r.length,onChange:E=>m(T.id,E),onRemove:()=>h(T.id),onMove:E=>f(O,E),disabled:c,compNumber:a,inspectPrefix:`${j(T.improvementType==="Dwelling"?"Dwellings":"Outbuildings")}.${tb(T.id)}`},T.id)),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-7 flex-1 text-xs",onClick:()=>u("Dwelling"),disabled:c,"data-testid":`button-comp${a}-add-dwelling`,children:[e.jsx(un,{className:"mr-1 h-3.5 w-3.5"})," Add Dwelling"]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-7 flex-1 text-xs",onClick:()=>u("Outbuilding"),disabled:c,"data-testid":`button-comp${a}-add-outbuilding`,children:[e.jsx(un,{className:"mr-1 h-3.5 w-3.5"})," Add Outbuilding"]})]})]}),e.jsx(Rv,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-slate-500",children:"Facts (not shown as grid rows)"}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Project Legal Structure"}),e.jsx(Fs,{section:"salesComparison",fieldName:j("ProjectLegalStructureType")}),e.jsx(Fs,{section:"salesComparison",fieldName:j("PropertyInProjectIndicator"),displayLabel:"In project"}),e.jsx(Fs,{section:"salesComparison",fieldName:j("PUDIndicator"),displayLabel:"PUD"}
39),e.jsx(Kd,{value:v,onChange:S,suggestions:oU,placeholder:"Unknown",compact:!0,ariaLabel:"Project Legal Structure",inputClassName:"h-7 text-xs placeholder-hint",testId:`comp${a}-legal-structure`,disabled:c})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Homeowner Resp. Ext. Maint."}),e.jsx(Fs,{section:"salesComparison",fieldName:j("HomeownerResponsibleForExteriorMaintenanceIndicator")}),e.jsx(cv,{value:N("HomeownerResponsibleForExteriorMaintenanceIndicator"),onChange:T=>x("HomeownerResponsibleForExteriorMaintenanceIndicator",T),disabled:c,testId:`comp${a}-homeowner-ext`})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Land Owned in Common"}),e.jsx(Fs,{section:"salesComparison",fieldName:j("LandOwnedInCommonIndicator")}),e.jsx(cv,{value:N("LandOwnedInCommonIndicator"),onChange:T=>x("LandOwnedInCommonIndicator",T),disabled:c,testId:`comp${a}-land-common`})]})]}),d&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 rounded border border-amber-200 bg-amber-50 p-2",children:[e.jsx("div",{className:"col-span-2 text-[10px] text-amber-700",children:"Property Rights inputs (a dependent row is shown while the Property Rights row itself is hidden)."}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"Property Estate Type"}),e.jsx(N0,{field:"PropertyEstateType",value:String(s.PropertyEstateType?.value??"")||null,onChange:T=>n("PropertyEstateType",T===null?null:T),disabled:c,testId:`comp${a}-estate-type`})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Ja,{className:"text-[10px] uppercase text-muted-foreground",children:"All Rights Appraised"}),e.jsx(cv,{value:N("AllPropertyRightsAppraisedIndicator"),onChange:T=>x("AllPropertyRightsAppraisedIndicator",T),disabled:c,testId:`comp${a}-all-rights`})]})]})]})]})})]})]})}function SW(t,a){return!t.includes("Other")||!a?t:t.split("|").map(s=>s.trim()==="Other"?a:s).join("|")}function vW(t,a,s){if(!s)return t.transferHistory;const r=[];let n=!1;for(let i=0;i<=Vm;i+=1){const l={};for(const c of mg){const d=s(Ag(a,i,c));d!==void 0&&(n=!0,l[c]=d)}r.push(l)}return n?r:t.transferHistory}function Jb(t){return qL(t)}const Vp=new Set(["netAdjustment","grossAdjustment","adjustedSalePrice"]);function lc(t){if(t==null)return NaN;if(typeof t=="number")return t;const a=t.replace(/,/g,"").match(/-?\d+(\.\d+)?/);return a?parseFloat(a[0]):NaN}function NW(t){if(t==null)return null;const a=String(t).match(/(\d{1,2})\/(\d{2,4})/);if(!a)return null;const s=Number(a[1]),r=a[2],n=r.length===2?2e3+Number(r):Number(r);return!s||s<1||s>12||!n?null:{mo:s,yr:n}}function Rj(t){if(t==null)return{bedrooms:NaN,bathrooms:NaN};const a=String(t).split("|");if(a.length<3)return{bedrooms:NaN,bathrooms:NaN};const s=parseFloat(a[1].replace(/[^0-9.]/g,"")),r=a[2].trim(),n=r.indexOf(".");let i;if(n===-1)i=parseFloat(r.replace(/[^0-9.]/g,""));else{const l=parseFloat(r.slice(0,n).replace(/[^0-9]/g,"")),c=parseFloat(r.slice(n+1).replace(/[^0-9]/g,""));i=(Number.isFinite(l)?l:0)+(Number.isFinite(c)?c*.5:0)}return{bedrooms:s,bathrooms:i}}function t1(t){if(t==null)return{bedrooms:NaN,fullBaths:NaN,halfBaths:NaN};const a=String(t).split("|");if(a.length<3)return{bedrooms:NaN,fullBaths:NaN,halfBaths:NaN};const s=parseFloat(a[1].replace(/[^0-9.]/g,"")),r=a[2].trim(),n=r.indexOf(".");let i,l;return n===-1?(i=parseFloat(r.replace(/[^0-9.]/g,"")),l=0):(i=parseFloat(r.slice(0,n).replace(/[^0-9]/g,"")),l=parseFloat(r.slice(n+1).replace(/[^0-9]/g,"")),Number.isFinite(i)||(i=NaN),Number.isFinite(l)||(l=NaN)),{bedrooms:s,fullBaths:i,halfBaths:l}}function eI(t){if(t==null)return{finished:NaN,unfinished:NaN};const a=String(t).trim();if(a==="0"||!a.includes("/"))return{finished:0,unfinished:0};const s=a.split("/"),r=parseFloat(s[0].replace(/[^0-9.]/g,"")),n=parseFloat((s[1]??"").split(" ")[0].replace(/[^0-9.]/g,""));return!Number.isFinite(r)||!Number.isFinite(n)?{finished:NaN,unfinished:NaN}:{finished:n,unfinished:Math.max(0,r-n)}}function a1(t){const a=cC(t);return a.cleared||a.sf==null?NaN:a.sf}function s1(t){return $H(t)}function r1(t){if(t==null)return{bedrooms:NaN,bathrooms:NaN};const a=String(t).trim();if(a==="0")return{bedrooms:0,bathrooms:0};const s=a.match(/(\d+)\s*br\b/i),r=a.match(/(\d+(?:\.\d+)?)\s*ba\b/i);let n=NaN;if(r){const i=r[1],l=i.indexOf(".");if(l===-1)n=parseFloat(i);else{const c=parseInt(i.slice(0,l),10),d=parseInt(i.slice(l+1),10);n=(Number.isFinite(c)?c:0)+(Number.isFinite(d)?d*.5:0)}}return{bedrooms:s?parseInt(s[1],10):NaN,bathrooms:n}}function AW(t,a,s){if(t.lat==null||t.lng==null)return null;const r=a.filter(y=>y.lat!=null&&y.lng!=null);if(r.length===0)return null;const n=[t.lat,...r.map(y=>y.lat)],i=[t.lng,...r.map(y=>y.lng)],l=Math.max(...n),c=Math.min(...n),d=Math.max(...i),p=Math.min(...i),u=(l+c)/2,m=(d+p)/2,h=l-c,f=d-p,v=Math.max(h,f),S=v<.01?15:v<.05?13:v<.1?12:v<.5?10:8,N=y=>{const b=y.fields.salePrice?.value;if(b==null)return null;const j=typeof b=="number"?b:parseFloat(String(b).replace(/[^0-9.
39-]/g,""));return isNaN(j)?null:j},x=(y,b)=>{const j=N(y);if(j==null||!b)return j;const T=new Set;Object.keys(b).forEach(E=>{const R=$k[E];R&&R.forEach(G=>T.add(G))});const O=Object.entries(b).filter(([E])=>!Vp.has(E)&&!T.has(E)).reduce((E,[,R])=>E+R,0);return j+O};return{viewport:{center:{lat:u,lng:m},zoom:S,bounds:{north:l,south:c,east:d,west:p}},subject:{lat:t.lat,lng:t.lng,address:t.address},comps:r.map(y=>{const b=a.indexOf(y);return{id:y.id,lat:y.lat,lng:y.lng,address:y.address,index:b>=0?b:0,distance:y.distance??lb(t.lat,t.lng,y.lat,y.lng),salePrice:N(y),adjustedPrice:x(y,s[y.id])}})}}const jW=/^[\s\-‐‑‒–—―−]+$/,TW=new Set(["salePrice","listPrice","concessions","TotalSalesConcessionAmount","contractPrice","ContractPrice","salesContractAmount","SalesContractAmount"]),dM=new Set(["dateOfSale","salesContractDate","SalesContractDate"]),uM=new Set(["daysOnMarket","DaysOnMarket","proximity","gla","lotSize","site"]);function Cm(t){const a=t.replace(/[$,\s]/g,"").trim();if(!a)return null;const s=Number(a);return Number.isFinite(s)?s:null}function qf(t,a){if(a==null||a==="")return"";if(dM.has(t)){const s=String(a);return/^\d{4}-\d{2}-\d{2}/.test(s)?hL(s):s}if(TW.has(t)){const s=cf(a);return s==="—"?String(a):s}if(uM.has(t)){const s=Cm(String(a));return s===null?String(a):s.toLocaleString("en-US")}return String(a)}function Yh(t,a,s="1004",r=!1,n){if(r&&a==="attachedDetached")return dC(t);if(n&&t!==null&&t!==void 0&&t!==""){if(a==="saleType"&&cp(String(t))==="Other"){const i=n.saleTypeOtherDescription?.trim();if(i)return i}if(a==="financing"&&String(t).trim()==="Other"){const i=n.financingOtherDescription?.trim();if(i)return i}if(a==="design"&&gg(String(t))==="Other"){const i=n.designOtherDescription?.trim();if(i)return i}}if(a==="financingConcessions")return uB(t);if(a==="concessions"&&t!==null&&t!==void 0&&t!=="")return mB(t);if(a==="saleType"&&t!==null&&t!==void 0&&t!=="")return hB(t);if(a==="financing"&&t!==null&&t!==void 0&&t!=="")return pB(t);if(a==="porchPatioDeck"&&t!==null&&t!==void 0&&t!=="")return SB(t);if(t==null||t==="")return a==="saleType"||r?"":s==="str"?"Unknown":"–";if(r&&(a==="basement"||/^basementUnit\d+$/.test(a))&&typeof t=="string")if(t.includes("/")){const i=eI(t);if(Number.isFinite(i.finished)&&Number.isFinite(i.unfinished)){const l=i.finished+i.unfinished;return l===0?"No Below Grade":`${l.toLocaleString()} sf (${i.finished.toLocaleString()} fin / ${i.unfinished.toLocaleString()} unfin)`}}else{if(t.trim()==="0")return"No Below Grade";if(!/\d/.test(t))return r?"":s==="str"?"Unknown":"–"}if(r&&s!=="str"&&a==="dateOfSale"&&typeof t=="string"){const i=t.split(";").map(c=>c.trim()).filter(Boolean),l=i.find(c=>/^s/i.test(c))??i.find(c=>!/^c/i.test(c));if(l){const d=l.replace(/^s/i,"").trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);return d?`${d[2]}/${d[3]}/${d[1]}`:""}return""}{const i=zH(a,t);if(i!==null)return i!==""?i:r?"":s==="str"?"Unknown":"–"}return typeof t=="string"&&(t.includes(";")||t.includes("sf")||/^[QC][1-6]$/.test(t)||/^[NBA];/.test(t)||/^\d+[a-z]{2,3}$/.test(t)||t==="None")?t:a==="listPrice"&&(typeof t=="number"||typeof t=="string"&&t.trim()!==""&&Number.isFinite(Number(t)))?`$${Math.round(Number(t)).toLocaleString("en-US")}`:a==="salePrice"&&(typeof t=="number"||typeof t=="string"&&t.trim()!==""&&Number.isFinite(Number(t)))?ng(Number(t)):a==="adjustedSalePrice"&&typeof t=="number"?ng(t):a==="netAdjustment"&&typeof t=="number"?`${t>=0?"+":"-"}${ng(Math.abs(t))}`:a==="grossAdjustment"&&typeof t=="number"?ng(t):a==="gla"&&typeof t=="number"?Iv(t):(a==="site"||a==="lotSize")&&typeof t=="number"?sb(t,"sqft"):a==="yearBuilt"?String(t):a==="listingStatus"?{Active:"Active",OffMarket:"Off Market",Pending:"Pending",SettledSale:"Settled Sale"}[String(t)]??String(t):String(t)}function IW(t,a,s,r=!1){if(!s)return a;const n=l=>l?` | ${l}`:"",i=l=>{const c=s[l]?.value;return c==null?"":String(c).trim()};if(t==="interiorQuality"||t==="exteriorQuality"){const l=i(t==="interiorQuality"?"interiorCondition":"exteriorCondition").toUpperCase();return l?`${a} / ${l}`:a}if(!a||a==="Unknown")return a;switch(t){case"dataSource":{const l=i("dataSourceIdentifier");return l?`${a} | ${l}`:a}case"location":{const l=i("locationBodyOfWater");return l?`${a} | ${l}`:a}case"view":return a.split(", ").map((l,c)=>{const d=i(`viewRange${c===0?"":String(c+1)}`);return`${l}${n(d?Hs("ViewRangeType",d)||d:"")}`}).join(", ");case"heatingCooling":{const l=i("heatingFuel");return!l&&/^none\b/i.test(a)?a:`${a}${n(l?Hs("HeatingFuelType",l)||l:"")}`}case"garageCarport":return a.split("; ").map((c,d)=>{const p=d===0?"":String(d+1),u=[],m=i(`garageAttachment${p}`);m&&u.push(Hs("CarStorageAttachmentType",m)||m);const h=i(`garageArea${p}`);
39h&&u.push(`${Number(h).toLocaleString()} sf`);const f=i(`garageSurface${p}`);return f&&u.push(Hs("ImprovedSurfaceMaterialType",f)||f),i(`garageTenOrMore${p}`)==="true"&&u.push("10+ spaces"),u.length?`${c} | ${u.join(" · ")}`:c}).join("; ");default:return a}}function wm(t,a,s=!1){const r=t.fields??{};if(ZD(a)||t.isSubject&&Qp.has(a)&&NN(r.ListedWithinPreviousYearIndicator?.value)!=="values"||t.isSubject&&s&&a==="proximity"||a==="financing")return!1;if(s){const d=Lx(t,a);if(d!==void 0)return!Vh(d.value);const p=hM[a];if(p){const u=p.map(m=>r[m]).filter(m=>m!==void 0);if(u.length>0)return u.some(m=>!Vh(m.value))}}if(s&&!t.isSubject&&a==="salePrice"&&j0(t)!=="Sale")return!1;const i={address:["AddressLineText","CityName","StateCode","PostalCode"],proximity:["ProximityToSubjectDistanceLinearMeasure","ProximityToSubjectDistanceUnitType","ProximityToSubjectDirectionType"]}[a];if(i&&i.some(d=>r[d]!==void 0))return i.some(d=>!Vh(r[d]?.value));const l=r[a];if(!l)return!0;const c=l.value;return a==="attachedDetached"&&dC(c)===""?!0:!Vh(c)}const pM=new Set(vL.filter(t=>t.required).map(t=>t.rowId)),mM=new Set(["OverallConditionRatingCode","OverallQualityRatingCode","SiteInfluenceType","ViewType"]),hM={salePrice:["SalePrice"],dateOfSale:["SaleDate"],proximity:["Proximity"],gla:["TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure"],location:["SiteInfluenceType"],qualityCondition:["OverallConditionRatingCode","OverallQualityRatingCode"],aboveGrade:["BedroomCount","FullBathroomCount","HalfBathroomCount"],view:["ViewType"]},A0=new Set(["BedroomCount","FullBathroomCount","HalfBathroomCount"].filter(t=>pM.has(t))),dg=new Set(["attachedDetached",...Array.from(A0),...Array.from(mM),...Object.entries(hM).filter(([,t])=>t.some(a=>pM.has(a))).map(([t])=>t)]),CW=new Set(["qualityCondition","aboveGrade","belowGrade","gla","location","site","view","energyEfficient"]),Qp=new Set(["listPrice","listingStatus","daysOnMarket"]),Pm={listPrice:"FinalListPriceAmount",listingStatus:"ListingStatusType",daysOnMarket:"DaysOnMarketCount"};function tI(t){if(t.isMissing)return wL(PL({semanticState:"blank",required:t.isRequired??!1,hasValue:!1}));t.isVerified&&t.hasHighlightedConflict}function Gl(t){return wL(PL({semanticState:t.semanticState??(t.isMissing?"blank":"value"),required:t.isRequired??dg.has(t.fieldName),hasValue:!t.isMissing}))}function Kx(t,a){const s=t==="salePrice"?"SalePrice":t==="ContractPrice"?"SalesContractAmount":Pm[t]??t,n=dT(s,s)?.[a==="subject"?"subjectText":"compText"]?.trim();if(!n)throw new Error(`Sales Grid em-dash rendered without a governing UAD 3.6 rule: ${s} (${a})`);return TU(n)}function RW(t,a){if(t==="Unknown"&&!a)return{label:"Unknown",bg:"bg-slate-100",text:"text-slate-600"};if(t==="Rental")return{label:"Rental",bg:"bg-purple-100",text:"text-purple-700"};const s=a||t;if(TN(s)==="SettledSale")return{label:"Sold",bg:"bg-red-100",text:"text-red-700"};const r=jN(s),n=r==="underContract"?{label:"Active Under Contract",bg:"bg-blue-100",text:"text-blue-700"}:r==="contingent"?{label:"Contingent",bg:"bg-teal-100",text:"text-teal-700"}:r==="active"?{label:"Active",bg:"bg-green-100",text:"text-green-700"}:{label:"Pending",bg:"bg-amber-100",text:"text-amber-700"};return UI(s)?{...n,label:`${n.label} (Private)`}:n}const EW={N:"North",NE:"NorthEast",E:"East",SE:"SouthEast",S:"South",SW:"SouthWest",W:"West",NW:"NorthWest"};function kS(t){const a=String(t).trim().split(/\s+/).filter(Boolean),s=Number(a[0]);if(!Number.isFinite(s)||s<0)return null;const r=a[1]??"",n=/^(?:Miles?|Km\.?|Kilometers?)$/i.test(r),i=n?/^Km|Kilometer/i.test(r)?"Kilometers":"Miles":"",l=(n?a[2]??"":r).toUpperCase();return{distance:String(s),unit:i,direction:EW[l]??""}}function wW({dateField:t,unknownField:a,allowUnknown:s=!0,onSelect:r,onSetPreference:n,preferredSource:i,onCopyToAllComps:l,children:c,fieldKey:d,entityLabel:p}){const[u,m]=o.useState(!1),[h,f]=o.useState(null),[v,S]=o.useState(""),[N,x]=o.useState(!1),y=[{key:"mls",label:"MLS",source:"MLS",dot:"bg-sky-500"},{key:"pr",label:"PR",source:"PublicRecord",dot:"bg-amber-500"},{key:"ai",label:"AI",source:"AI",dot:"bg-emerald-500"}],b=(A,M)=>{const B=M==="MLS"?"mls":M==="PublicRecord"?"public_records":M==="AI"?"ai_derived":"user";
39return A?.sourceCandidates&&B in A.sourceCandidates?A.sourceCandidates[B]:M==="MLS"?A?.mlsValue:M==="PublicRecord"?A?.prValue:M==="AI"?A?.aiValue:A?.userValue??(A?.source==="User"?A.value:null)},j=A=>{const M=b(t,A);return M==null||M===""?null:String(M)},T=A=>{const M=b(a,A);if(M===!0||M==="true")return!0;if(M===!1||M==="false")return!1},O=A=>{if(s&&T(A)===!0)return"Unknown";const M=j(A);if(!M)return"";const B=/^(\d{4})-(\d{2})-(\d{2})$/.exec(M);return B?`${B[2]}/${B[3]}/${B[1]}`:M},E=h??(t.source==="User"||a?.source==="User"?"User":t.source==="PublicRecord"||a?.source==="PublicRecord"?"PublicRecord":t.source==="AI"||a?.source==="AI"?"AI":"MLS"),R=`${p?`${p} `:""}Contract Date`,G=A=>j(A)!==null||s&&T(A)===!0,U=A=>{G(A)&&(f(A),r("SalesContractDate",j(A)??"",`Select:${A}`),s&&r("ContractDateUnknownIndicator",T(A)===!0,`Select:${A}`))},C=()=>{f("User"),r("SalesContractDate",N?"":v,"Select:User"),s&&r("ContractDateUnknownIndicator",N,"Select:User")},F=()=>{const A=y.find(B=>G(B.source))?.source,M=A?`ClearUser:${A}`:"ClearUser";S(""),x(!1),f(A??"User"),r("SalesContractDate","",M),s&&r("ContractDateUnknownIndicator",!1,M)};return e.jsxs(xn,{open:u,onOpenChange:A=>{A&&(S(j("User")??""),x(T("User")===!0)),m(A)},children:[e.jsx(bn,{asChild:!0,children:c}),u&&Wp.createPortal(e.jsx("button",{type:"button","aria-label":"Close contract date editor",className:"fixed inset-0 z-40 cursor-default bg-slate-950/35 backdrop-blur-[1px]","data-testid":"contract-date-editor-backdrop",onClick:()=>m(!1)}),document.body),e.jsxs(yn,{align:"start",className:"z-50 w-[28rem] border-slate-300 p-0 shadow-2xl","data-testid":`contract-date-editor-${d}`,children:[e.jsx("div",{className:Xv,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:Jv,children:R}),e.jsx("p",{className:eN,children:"Select a source candidate for this comparable."})]}),e.jsx("button",{type:"button","aria-label":"Close",className:"rounded p-0.5 text-slate-400 hover:bg-slate-100",onClick:()=>m(!1),children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]})}),e.jsxs("div",{className:"space-y-0.5 p-1",role:"radiogroup","aria-label":`${R} source`,children:[y.map(A=>{const M=G(A.source),B=E===A.source;return e.jsxs("div",{className:Q("grid min-h-8 grid-cols-[20px_38px_1fr_auto] items-center gap-1.5 rounded px-2 py-0.5",M?"hover:bg-slate-50":"opacity-50"),"data-testid":`source-${A.key}-contractDate`,children:[e.jsx("button",{type:"button",role:"radio","aria-checked":B,"aria-label":`Use ${A.label}: ${R}`,disabled:!M,onClick:()=>U(A.source),className:Q("flex h-4 w-4 items-center justify-center rounded border",B?"border-sky-600 bg-sky-600 text-white":"border-slate-300 bg-white"),children:B&&e.jsx(Bs,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:Q("h-2 w-2 rounded-full",A.dot)}),e.jsx("span",{className:Gh,children:A.label})]}),e.jsx("span",{className:tN,children:O(A.source)}),e.jsxs("div",{className:"grid w-[5.75rem] grid-cols-3 justify-items-center gap-1",children:[n&&e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0","aria-label":`Set ${A.label} as default contract date source`,onClick:()=>n("SalesContractDate",A.source),children:e.jsx(Lo,{className:"h-3.5 w-3.5"})}),l&&e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",disabled:!M,"aria-label":`Copy ${A.label} contract date to all comps`,onClick:()=>l(T(A.source)===!0?null:j(A.source),T(A.source)===!0),children:e.jsx(jr,{className:"h-3.5 w-3.5"})})]})]},A.key)}),e.jsxs("div",{className:"grid min-h-9 grid-cols-[20px_38px_1fr_auto] items-center gap-1.5 rounded px-2 py-0.5 hover:bg-slate-50","data-testid":"source-user-contractDate",children:[e.jsx("button",{type:"button",role:"radio","aria-checked":E==="User","aria-label":`Use User: ${R}`,onClick:C,className:Q("flex h-4 w-4 items-center justify-center rounded border",E==="User"?"border-violet-600 bg-violet-600 text-white":"border-slate-300 bg-white"),children:E==="User"&&e.jsx(Bs,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-violet-500"}),e.jsx("span",{className:Gh,children:"User"})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(vN,{value:v,onCh
39ange:A=>{S(A),x(!1),r("SalesContractDate",A,"User"),s&&r("ContractDateUnknownIndicator",!1,"User")},disabled:N,testId:`input-user-contract-date-${d}`,inputClassName:Q(rp,"h-7 min-w-0 placeholder-hint"),pickerButtonClassName:"h-7 w-7 p-0"}),s&&e.jsxs("label",{className:Q("flex shrink-0 items-center gap-1",rp,"text-slate-500"),children:[e.jsx("input",{type:"checkbox","aria-label":"User contract date Unknown",checked:N,onChange:A=>{const M=A.target.checked;x(M),r("SalesContractDate",M?"":v,"User"),r("ContractDateUnknownIndicator",M,"User")}}),"Unknown"]}),j("User")!==null&&e.jsx("button",{type:"button","aria-label":"Clear User contract date",className:"rounded p-1 text-slate-400 hover:text-slate-700",onClick:F,children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})]})]})]})]})]})}function PW({amountField:t,unknownField:a,allowUnknown:s=!0,onSelect:r,children:n,fieldKey:i,entityLabel:l}){const[c,d]=o.useState(!1),[p,u]=o.useState(null),[m,h]=o.useState(""),[f,v]=o.useState(!1),[S,N]=o.useState(!1),x=[{key:"mls",label:"MLS",source:"MLS",dot:"bg-sky-500"},{key:"pr",label:"PR",source:"PublicRecord",dot:"bg-amber-500"},{key:"ai",label:"AI",source:"AI",dot:"bg-emerald-500"}],y=(A,M)=>{const B=M==="MLS"?"mls":M==="PublicRecord"?"public_records":M==="AI"?"ai_derived":"user";return A?.sourceCandidates&&B in A.sourceCandidates?A.sourceCandidates[B]:M==="MLS"?A?.mlsValue:M==="PublicRecord"?A?.prValue:M==="AI"?A?.aiValue:A?.userValue??(A?.source==="User"?A.value:null)},b=A=>{const M=y(t,A);return M==null||M===""?null:M},j=A=>{const M=y(a,A);if(M===!0||M==="true")return!0;if(M===!1||M==="false")return!1},T=A=>{if(s&&j(A)===!0)return"Unknown";const M=b(A);if(M==null)return"—";const B=Number(String(M).replace(/[$,\s]/g,""));return Number.isFinite(B)?cf(B):String(M)},O=p??(t.source==="User"||a?.source==="User"?"User":t.source==="PublicRecord"||a?.source==="PublicRecord"?"PublicRecord":t.source==="AI"||a?.source==="AI"?"AI":"MLS"),E=`${l?`${l} `:""}Contract Price`,R=A=>b(A)!==null||s&&j(A)===!0,G=(A,M)=>{u(A),r("SalesContractAmount",j(A)===!0?"":b(A)??"",M),s&&r("ContractAmountUnknownIndicator",j(A)===!0,M)},U=A=>{R(A)&&G(A,`Select:${A}`)},C=()=>{u("User");const A=m.replace(/[$,\s]/g,"").trim();r("SalesContractAmount",f||A===""?"":Number(A),"Select:User"),s&&r("ContractAmountUnknownIndicator",f,"Select:User")},F=()=>{const A=x.find(B=>R(B.source))?.source,M=A?`ClearUser:${A}`:"ClearUser";h(""),v(!1),u(A??"User"),r("SalesContractAmount","",M),s&&r("ContractAmountUnknownIndicator",!1,M)};return e.jsxs(xn,{open:c,onOpenChange:A=>{if(A){const M=b("User");h(M==null?"":String(M)),v(j("User")===!0),N(!1)}d(A)},children:[e.jsx(bn,{asChild:!0,children:n}),c&&Wp.createPortal(e.jsx("button",{type:"button","aria-label":"Close contract amount editor",className:"fixed inset-0 z-40 cursor-default bg-slate-950/35 backdrop-blur-[1px]","data-testid":"contract-amount-editor-backdrop",onClick:()=>d(!1)}),document.body),e.jsxs(yn,{align:"start",className:"z-50 w-[28rem] border-slate-300 p-0 shadow-2xl","data-testid":`contract-amount-editor-${i}`,children:[e.jsx("div",{className:Xv,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:Jv,children:E}),e.jsx("p",{className:eN,children:"Select a source candidate for this comparable."})]}),e.jsx("button",{type:"button","aria-label":"Close",className:"rounded p-0.5 text-slate-400 hover:bg-slate-100",onClick:()=>d(!1),children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]})}),e.jsxs("div",{className:"space-y-0.5 p-1",role:"radiogroup","aria-label":`${E} source`,children:[x.map(A=>{const M=R(A.source),B=O===A.source;return e.jsxs("div",{className:Q("grid min-h-8 grid-cols-[20px_38px_1fr_auto] items-center gap-1.5 rounded px-2 py-0.5",M?"hover:bg-slate-50":"opacity-50"),"data-testid":`source-${A.key}-contractAmount`,children:[e.jsx("button",{type:"button",role:"radio","aria-checked":B,"aria-label":`Use ${A.label}: ${E}`,disabled:!M,onClick:()=>U(A.source),className:Q("flex h-4 w-4 items-center justify-center rounded border",B?"border-sky-600 bg-sky-600 text-white":"border-slate-300 bg-white"),children:B&&e.jsx(Bs,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:Q("h-2 w-2 rounded-full",A.dot)}),e.jsx("span",{className:Gh,children:A.label})]}),e.jsx("span",{className:Q(tN,M?"text-slate-900":"text-slate-400"),children:M?T(A.source):"No data"})]},A.key)}),e.jsxs("div",{className:"grid min-h-9 grid-cols-[20px_38px_1fr_auto] items-center gap-1.5 rounded px-2 py-0.5 hover:bg-slate-50","data-testid":"source-user-contractAmou
39nt",children:[e.jsx("button",{type:"button",role:"radio","aria-checked":O==="User","aria-label":`Use User: ${E}`,onClick:C,className:Q("flex h-4 w-4 items-center justify-center rounded border",O==="User"?"border-violet-600 bg-violet-600 text-white":"border-slate-300 bg-white"),children:O==="User"&&e.jsx(Bs,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-violet-500"}),e.jsx("span",{className:Gh,children:"User"})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(ze,{type:"text",inputMode:"decimal",value:S||T("User")==="—"||T("User")==="Unknown"?m:T("User"),onFocus:()=>{N(!0),h(b("User")?.toString()??m)},onChange:A=>{const M=A.target.value;h(M);const B=M.replace(/[$,\s]/g,"").trim(),oe=Number(B);r("SalesContractAmount",B===""?"":Number.isFinite(oe)?oe:M,"User"),s&&B!==""&&(v(!1),r("ContractAmountUnknownIndicator",!1,"User"))},onBlur:()=>N(!1),disabled:f,placeholder:"$ amount","aria-label":"User contract amount",className:Q(rp,"h-7 min-w-0 placeholder-hint"),"data-testid":`input-user-contract-amount-${i}`}),s&&e.jsxs("label",{className:Q("flex shrink-0 items-center gap-1",rp,"text-slate-500"),children:[e.jsx("input",{type:"checkbox","aria-label":"User contract amount Unknown",checked:f,onChange:A=>{const M=A.target.checked;v(M),r("SalesContractAmount",M?"":m,"User"),r("ContractAmountUnknownIndicator",M,"User")}}),"Unknown"]}),b("User")!==null&&e.jsx("button",{type:"button","aria-label":"Clear User contract amount",className:"rounded p-1 text-slate-400 hover:text-slate-700",onClick:F,children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})]})]})]})]})]})}const Jv="text-sm font-semibold text-slate-800",Xv="shrink-0 border-b border-slate-200 px-3 py-3",eN="mt-1 text-[11px] text-slate-500",Gh="text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",tN="text-[11px] font-medium tabular-nums text-slate-900",rp="text-[11px] text-slate-900";function OW(t){return[t.mlsValue,t.prValue,t.aiValue].filter(a=>a!=null).map(a=>cp(String(a)))}function fM({fieldName:t,fieldData:a,onSelect:s,onCopyToAllComps:r,onCopyCompanionToAllComps:n,onSetPreference:i,preferredSource:l,otherDescriptions:c,onOtherDescriptionChange:d,companionFields:p,onSelectCompanion:u,onConcessionTransactionUpdate:m,uad36:h,gridMode:f,basementHint:v,children:S,compactListingFields:N,onSelectCompactListing:x,onCopyCompactListing:y,comparableSequence:b,entityLabel:j,editableText:T=!1}){const[O,E]=o.useState(!1),R=t.split("-").pop()||t,G=j??(b!=null?`Comp ${b}`:""),U=G?`${G} `:"",[C,F]=o.useState(""),[A,M]=o.useState({}),[B,oe]=o.useState(null),[ae,D]=o.useState(!1),[_,$]=o.useState(null),[z,V]=o.useState(()=>a.value==null?"":"Amount"),[le,W]=o.useState(()=>qf("concessions",a.value)),[me,Z]=o.useState(()=>{const tt=a.userValue??(a.source==="User"?a.value:null);return tt==null?"":Yh(tt,"saleType",f??"1004",h,c)}),[pe,se]=o.useState(()=>{const tt=a.userValue??(a.source==="User"?a.value:null);return tt==null?"":String(tt)});o.useEffect(()=>{$(a.source??null)},[t,a.source]),o.useEffect(()=>{if(R!=="saleType")return;const tt=a.userValue??(a.source==="User"?a.value:null);Z(tt==null?"":Yh(tt,"saleType",f??"1004",h,c))},[R,a.userValue,a.value,a.source,f,c,h]),o.useEffect(()=>{if(R!=="dateOfSale")return;const tt=a.userValue??(a.source==="User"?a.value:null);se(tt==null?"":String(tt))},[R,a.userValue,a.value,a.source]);const fe=new Set(["salePrice","saleType","financing","concessions","financingConcessions","dateOfSale","salesContractDate"]),ue=o.useRef(null),be=R==="proximity"?kS(a.userValue??(a.source==="User"?a.value:"")??""):null,[H,ye]=o.useState(qf("proximity",be?.distance??"")),[de,ge]=o.useState(be?.unit||"Miles"),[Be,He]=o.useState(be?.direction??""),Ie=r?(tt,it)=>{if(R!=="proximity"||!n){r(tt,it);return}const Je=kS(tt);Je&&(n("ProximityToSubjectDistanceLinearMeasure",Je.distance,"User"),n("LinearUnitOfMeasureType",Je.unit,"User"),n("ComparableToSubjectDirectionType",Je.direction,"User"))}:void 0,ce=tt=>{tt&&N&&(oe(sI(N)??null),M(Object.fromEntries(["listingStatus","listPrice","daysOnMarket"].map(it=>{const Je=N[it],ht=_m(Je?.userValue),Kt=_m(Je?.value);return[it,ht??(Je?.source==="User"?Kt:"")??""]})))),E(tt)};o.useEffect(()=>{if(!O||R!=="proximity")return;const tt=a?.userValue??(a?.source==="User"?a.value:""),it=tt==null?null:kS(tt);ye(it?.distance??""),ge(it?.unit||"Miles"),He(it?.direction??"")},[O]),o.useEffect(()=>{if(!fe.has(R)||a.source==="User")return;const tt=a.value;if(tt!=null&&tt!=="")return;const Je=[["MLS",a.mlsValue],["PublicRecord",a.prValue],["AI",a.aiValue],["User",a.userValue]].filter(([,Qt])=>Qt!=null&&Qt!=="");if(Je.length!==1)return;const[ht,Kt]=Je[0],Sa=`${R}:${ht}:${String(Kt)}`;ue.current!==Sa&&(ue.current=Sa,$(ht),s(Kt,`SelectOnly:${ht}`))},[R,fe,a.value,a.mlsValue,a.prValue,a.aiValue,a.userValue,s]);const Pe=h?R:t,We=tt=>{const it=Yh(tt,Pe,f??"1004",h,c);if(dM.has(R)&&/^\d{4}-\d{2}-\d{2}$/.test(it))return hL(it);if(uM.has(R)&&tt!==null&&tt!==void 0&&tt!==""&&!it.includes(",")){const Je=Cm(String(tt));
39if(Je!==null)return Je.toLocaleString("en-US")}return it},Re=Ov(R),ne=Re!==null,Me=Re==="location"||Re==="view",lt=tt=>tt==null,Tt=lt(a.mlsValue)||lt(a.prValue)||lt(a.aiValue),je=(tt,it,Je)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded opacity-50","data-testid":`source-empty-${Je}-${t}`,children:[e.jsx("span",{className:Q("w-2 h-2 rounded-full",it)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-400 font-medium",children:tt}),e.jsx("p",{className:"text-[12px] text-slate-400",children:"No data"})]})]}),Le=(tt,it)=>{if(tt)return it==="MLS"?tt.mlsValue:it==="PublicRecord"?tt.prValue:it==="AI"?tt.aiValue:tt.userValue??(tt.source==="User"?tt.value:void 0)},ut=tt=>{if(R!=="concessions")return null;const it=Le(p?.SalesConcessionIndicator,tt),Je=Le(p?.SalesConcessionAmountKnownIndicator,tt),ht=Le(p?.TotalSalesConcessionAmount,tt);return it===!1||it==="false"?"":(it===!0||it==="true")&&(Je===!0||Je==="true")?ht??"":""},st=tt=>R==="concessions"&&[Le(a,tt),Le(p?.SalesConcessionIndicator,tt),Le(p?.SalesConcessionAmountKnownIndicator,tt),Le(p?.TotalSalesConcessionAmount,tt)].some(it=>it!=null),Xt=(tt,it)=>{if(R!=="concessions"||!p)return We(it);const Je=Le(p.SalesConcessionIndicator,tt),ht=Le(p.SalesConcessionAmountKnownIndicator,tt),Kt=ut(tt);return Je===!1||Je==="false"?"None":Je===!0||Je==="true"?ht===!0||ht==="true"?We(Kt):"Unknown":We(it)},ua=(tt,it)=>{if(tt!==null){if($(it),a.value===tt&&a.source===it){R!=="proximity"&&E(!1);return}if(R==="financingConcessions"&&d){const{saleType:ht,financing:Kt,concessions:Sa}=WD(tt);d("saleType",ht),d("financing",Kt),d("concessions",Sa)}if(R==="proximity"&&d){const ht=kS(tt);ht&&(d("ProximityToSubjectDistanceLinearMeasure",Number(ht.distance).toFixed(2),it),d("LinearUnitOfMeasureType",ht.unit,it),d("ComparableToSubjectDirectionType",ht.direction,it))}const Je=fe.has(R)?`SelectOnly:${it}`:it;if(R==="concessions"&&u){const ht=Le(p?.SalesConcessionIndicator,it),Kt=Le(p?.SalesConcessionAmountKnownIndicator,it);if(u("SalesConcessionIndicator",ht==null?"":ht===!1||ht==="false"?"false":"true",Je),u("SalesConcessionAmountKnownIndicator",Kt==null?"":Kt===!0||Kt==="true"?"true":"false",Je),p?.SalesConcessionsTypicalToMarketIndicator){const Sa=Le(p.SalesConcessionsTypicalToMarketIndicator,it);u("SalesConcessionsTypicalToMarketIndicator",Sa==null?"":Sa===!0||Sa==="true"?"true":"false",Je)}}if(R==="saleType"&&d){const ht=Le(p?.SaleTypeOtherDescription,it);d("saleTypeOtherDescription",ht==null?"":String(ht),Je)}R!=="proximity"&&s(tt,Je),R!=="proximity"&&!fe.has(R)&&E(!1)}},Oa=[{value:"North",label:"N"},{value:"NorthEast",label:"NE"},{value:"East",label:"E"},{value:"SouthEast",label:"SE"},{value:"South",label:"S"},{value:"SouthWest",label:"SW"},{value:"West",label:"W"},{value:"NorthWest",label:"NW"}],Xa=(tt=H,it=de,Je=Be)=>{const ht=Cm(tt);if(ht===null||ht<0||tt.trim()==="")return;ye(qf("proximity",ht));const Kt=ht===0?"Miles":it||"Miles";d&&(d("ProximityToSubjectDistanceLinearMeasure",String(ht.toFixed(2)),"User"),d("LinearUnitOfMeasureType",Kt,"User"),d("ComparableToSubjectDirectionType",ht>0?Je:"","User"))},qa=()=>Xa(),os=Cm(H)??NaN,ya=H.trim()!==""&&!isNaN(os),At=ya&&os===0,Fe=ya&&os>0,Oe=o.useRef(""),rt=o.useRef(!1),$t=tt=>{rt.current=!0,Oe.current=tt,F(tt)},na=tt=>{const it=Oe.current.trim();if(T?!rt.current:!it)return!1;const Je=Number(it),ht=T||isNaN(Je)?it:Je;return $t(""),rt.current=!1,s(ht,"User"),tt&&E(!1),!0},zt=()=>{na(!0)},Ua=["attachedDetached","listPrice","listingStatus","daysOnMarket","proximity"].includes(R),Ce=["salePrice","saleType","dateOfSale"].includes(R),St=R==="saleType"?Pr("SaleType")??[]:[],vt=new Set(St),Ve=new Map(St.map(tt=>[Hs("SaleType",tt).trim().toLocaleLowerCase(),tt])),sa=Array.from(new Set([...St,...OW(a)])).filter(tt=>tt&&tt!=="Other");if(Ua||Ce){const tt=R==="listPrice"?N:void 0,it=["listingStatus","listPrice","daysOnMarket"],Je=qe=>{const Ze=A[qe];return Ze===""?null:Ze??null},ht=[{key:"mls",label:"MLS",source:"MLS",dotClass:"bg-sky-500"},{key:"pr",label:"PR",source:"PublicRecord",dotClass:"bg-amber-500"},{key:"ai",label:"AI",source:"AI",dotClass:"bg-emerald-500"}],Kt=sI(tt??{}),Sa=B??Kt,Qt=(qe,Ze)=>{const It=_m(Ze);if(It==null)return"—";const Ne=Yh(It,qe,f??"1004",h,c);if(qe==="daysOnMarket"&&!Ne.includes(",")){const Ue=Cm(String(It));
39if(Ue!==null)return Ue.toLocaleString("en-US")}return Ne},ea=qe=>it.map(Ze=>Qt(Ze,qe[Ze])).map((Ze,It)=>e.jsxs(Mn.Fragment,{children:[It>0&&e.jsx("span",{className:"mx-1 text-slate-700",children:"|"}),e.jsx("span",{className:"truncate",children:Ze})]},it[It]));if(tt){const qe=(It,Ne,Ue=!1)=>{const ct={...A,...It?{[It]:Ne??""}:{}};oe("User"),M(ct),it.forEach(xt=>x?.(xt,ct[xt]??"",Ue?"SelectOnly:User":"User"))},Ze=()=>{const It=ht.find(Ne=>{const Ue=Ne.key==="pr"?"prValue":Ne.key==="ai"?"aiValue":"mlsValue";return it.some(ct=>{const xt=tt[ct]?.[Ue];return xt!=null&&xt!==""})})?.source;M({listingStatus:"",listPrice:"",daysOnMarket:""}),oe(It??"User"),it.forEach(Ne=>x?.(Ne,"",It?`ClearUser:${It}`:"ClearUser"))};return e.jsxs(xn,{open:O,onOpenChange:ce,children:[e.jsx(bn,{asChild:!0,children:S}),O&&Wp.createPortal(e.jsx("button",{type:"button","aria-label":"Close listing details editor",className:"fixed inset-0 z-40 cursor-default bg-slate-950/35 backdrop-blur-[1px]","data-testid":"listing-editor-backdrop",onClick:()=>ce(!1)}),document.body),e.jsxs(yn,{align:"start",collisionPadding:8,"data-editor-layout":"compact-existing",className:"z-50 w-[28rem] border-slate-300 p-0 shadow-2xl ring-1 ring-slate-900/10",sideOffset:4,children:[e.jsx("div",{className:Xv,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:Jv,"data-testid":"source-editor-title",children:[U,"Listing Status ",e.jsx("span",{className:"mx-1 text-slate-700",children:"|"})," Price ",e.jsx("span",{className:"mx-1 text-slate-700",children:"|"})," DOM"]}),e.jsx("p",{className:eN,children:"Select a source candidate for these listing details."})]}),e.jsx("button",{type:"button",onClick:()=>ce(!1),className:"rounded p-0.5 text-slate-400 hover:bg-slate-100","aria-label":"Close",children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]})}),e.jsxs("div",{className:"space-y-0.5 p-1",role:"radiogroup","aria-label":`${U}Listing details source`,children:[ht.map(It=>{const Ne=Object.fromEntries(it.map(xt=>{const Na=tt[xt],qt=It.key==="pr"?"prValue":It.key==="ai"?"aiValue":"mlsValue";return[xt,_m(Na?.[qt])]})),Ue=it.some(xt=>Ne[xt]!=null),ct=Sa===It.source;return e.jsxs("div",{className:Q("grid min-h-8 grid-cols-[20px_38px_1fr_auto] items-center gap-1.5 rounded px-2 py-0.5",Ue?"hover:bg-slate-50":"opacity-50"),"data-testid":`source-${It.key}-listingDetails`,children:[e.jsx("button",{type:"button",role:"radio","aria-checked":ct,"aria-label":`Use ${It.label}: Listing Status | Price | DOM`,disabled:!Ue,onClick:()=>{!Ue||!x||(oe(It.source),it.forEach(xt=>{const Na=Ne[xt];x(xt,Na??"",`SelectOnly:${It.source}`)}))},className:Q("flex h-4 w-4 items-center justify-center rounded border",ct?"border-sky-600 bg-sky-600 text-white":"border-slate-300 bg-white"),children:ct&&e.jsx(Bs,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:Q("h-2 w-2 rounded-full",It.dotClass)}),e.jsx("span",{className:Gh,children:It.label})]}),e.jsx("div",{className:Q("flex min-w-0 items-center",tN),children:ea(Ne)}),e.jsxs("div",{className:"grid w-[5.75rem] grid-cols-3 justify-items-center gap-1",children:[i&&e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:Q("h-7 w-7 p-0",l===It.source?"text-amber-500":"text-slate-300 hover:text-amber-500"),title:`Set ${It.label} as default`,"aria-label":`Set ${It.label} as default listing source`,onClick:()=>it.forEach(xt=>i(xt,It.source)),children:e.jsx(Lo,{className:Q("h-3.5 w-3.5",l===It.source&&"fill-amber-500")})}),y&&e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-slate-400 hover:text-slate-700 disabled:text-slate-200",title:`Copy ${It.label} to all comps`,"aria-label":`Copy ${It.label} listing details to all comps`,disabled:!Ue,onClick:()=>it.forEach(xt=>{const Na=Ne[xt];Na!=null&&y(xt,Na)}),children:e.jsx(jr,{className:"h-3.5 w-3.5"})})]})]},It.key)}),e.jsxs("div",{className:"grid min-h-9 grid-cols-[20px_38px_1fr_auto] items-center gap-1.5 rounded px-2 py-0.5 hover:bg-slate-50","data-testid":"source-user-listingDetails",children:[e.jsx("button",{type:"button",role:"radio","aria-label":"Use User: Listing Status | Price | DOM","aria-checked":Sa==="User",onClick:()=>qe(void 0,void 0,!0),className:Q("flex h-4 w-4 items-center justify-center rounded border",Sa==="User"?"border-violet-600 bg-violet-600 text-white":"border-slate-300 bg-white"),children:Sa==="User"&&e.jsx(Bs,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-violet-500"}),e.jsx("span",{className:Gh,children:"User"})]}),e.jsxs("div",{className:"grid min-w-0 grid-cols-[1.1fr_1fr_0.8fr] items-center gap-1",children:[e.jsx(rI,{value:Je("listingStatus")==null?"":String(Je("listingStatus")),onChange:It=>qe("listingStatus",It),ariaLabel:"User listing status",testId:"select-user-listingStatus"}),e.jsx("input",{type:"text",inputMode:"decimal","aria-label":"User price",value:typeof A.listPrice=="number"?qf("listPrice",A.listPrice):A.listPrice??"",onChange:It=>M(Ne=>({...Ne,listPrice:It.target.value})),onBlur:It=>{const Ne=Cm(It.currentTarget.value);qe("listPrice",Ne??"")},className:"h-7 min-w-0 rounded border border-slate-200 px-1.5 text-[11px]","data-testid":"input-user-listing-listPrice"}),e.jsx("input",{type:"text",inputMode:"numeric","aria-label":"User DOM",value:typeof A.daysOnMarket=="number"?qf("daysOnMarket",A.daysOnMarket):A.daysOnMarket??"",onChange:It=>M(Ne=>({...Ne,daysOnMarket:It.target.value})),onBlur:It=>{const Ne=Cm(It.currentTarget.value);qe("daysOnMarket",Ne??"")},className:"h-7 min-w-0 rounded border border-slate-200 px-1.5 text-[11px]","data-testid":"input-user-listing-daysOnMarket"})]}),e.jsxs("div",{className:"grid w-[5.75rem] grid-cols-3 justify-items-center gap-1",children:[i&&e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:Q("h-7 w-7 p-0",l==="User"?"text-amber-500":"text-slate-300 hover:text-amber-500"),title:"Set User as default","aria-label":"Set User as default listing source",onClick:()=>it.forEach(It=>i?.(It,"User")),children:e.jsx(Lo,{className:Q("h-3.5 w-3.5",l==="User"&&"fill-amber-500")})}),y&&e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-slate-400 hover:text-slate-700 disabled:text-slate-200",title:"Copy User listing details to all comps","aria-label":"Copy User listing details to all comps",disabled:!it.some(It=>Je(It)!=null),onClick:()=>it.forEach(It=>{const Ne=Je(It);Ne!=null&&y(It,Ne)}),children:e.jsx(jr,{className:"h-3.5 w-3.5"})}),e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-slate-400 hover:text-red-600",title:"Clear User listing values","aria-label":"Clear User listing details",onClick:Ze,children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})]})]})]})]})]})}const tr=R==="proximity"?[{key:"ai",label:"AI",source:"AI",value:a.aiValue??(a.source!=="User"?a.value:null),dotClass:"bg-emerald-500"}]:[{key:"mls",label:"MLS",source:"MLS",value:R==="concessions"?st("MLS")?ut("MLS"):null:a.mlsValue,dotClass:"bg-sky-500"},{key:"pr",label:"PR",source:"PublicRecord",value:R==="concessions"?st("PublicRecord")?ut("PublicRecord"):null:a.prValue,dotClass:"bg-amber-500"},{key:"ai",label:"AI",source:"AI",value:R==="concessions"?st("AI")?ut("AI"):null:a.aiValue,dotClass:"bg-emerald-500"}],ir=a.userValue??(a.source==="User"?a.value:null),zs=ir==null||ir===""?null:ir,pr=zs!==null,$e=new Set(["salePrice","saleType","financing","concessions","financingConcessions","dateOfSale","salesContractDate","listPrice","listingStatus","daysOnMarket"]).has(R),_e={attachedDetached:"Attached / Detached",listPrice:"List Price",listingStatus:"Listing Status",daysOnMarket:"Days on Market",proximity:"Proximity to Subject",salePrice:"Sale Price",saleType:"Transfer Terms",dateOfSale:"Sale Date",concessions:"Sales Concessions",financing:"Financing Type",financingConcessions:"Sale or Financing Concessions",salesContractDate:"Contract Date"}[R],ma=_e&&`${U}${_e}`,pt={attachedDetached:"attached or detached",listPrice:"list price",listingStatus:"listing status",daysOnMarket:"days on market",proximity:"proximity",salePrice:"sale price",saleType:"transfer terms",dateOfSale:"sale date",concessions:"sales concessions",financing:"financing type",financingConcessions:"sale or financing concessions",salesContractDate:"contract date"},re=(qe,Ze,It)=>R==="proximity"?null:e.jsxs("div",{className:"flex shrink-0 items-center",children:[i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:Q("h-7 w-7 p-0",l===qe?"text-amber-500":"text-slate-300 hover:text-amber-500"),onClick:()=>i(R,qe),"data-testid":`button-fav-${It}-${t}`,children:e.jsx(Lo,{className:Q("h-3.5 w-3.5",l===qe&&"fill-amber-500")})})}),e.jsx(Wa,{side:"right",className:"text-xs",children:l===qe?"Default source":"Set as default"})]}),r&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{type:"button",size:"sm",variant:"ghost",disabled:Ze==null,className:"h-7 w-7 p-0 text-slate-400 hover:text-slate-700 disabled:text-slate-200",onClick:()=>{Ze!=null&&(R==="proximity"?Ie?.(Ze,"User"):r(Ze,"User"))},"data-testid":`button-copy-${It}-${t}`,children:e.jsx(jr,{className:"h-3.5 w-3.5"})})}),e.jsx(Wa,{side:"right",className:"text-xs",children:Ze==null?"No value to copy":`Copy ${It==="pr"?"PR":qe} to all comps`})]})]});return e.jsxs(xn,{open:O,onOpenChange:R==="proximity"?ce:E,children:[e.jsx(bn,{asChild:!0,children:S}),R==="proximity"&&O&&Wp.createPortal(e.jsx("button",{type:"button","aria-label":"Close proximity editor",className:"fixed inset-0 z-40 cursor-default bg-slate-950/35 backdrop-blur-[1px]","data-testid":"proximity-editor-backdrop",onClick:()=>ce(!1)}),document.body),O&&fe.has(R)&&Wp.createPortal(e.jsx("button",{type:"button","aria-label":"Close transaction editor",className:"fixed inset-0 z-40 cursor-default bg-slate-950/35 backdrop-blur-[1px]","data-testid":R==="concessions"?`sales-concessions-editor-overlay-${t}`:"transaction-editor-backdrop",onClick:()=>E(!1)}),document.body),e.jsxs(yn,{align:"start",collisionPadding:8,"data-editor-layout":Ce?"compact-transaction":Ua?"compact-existing":void 0,className:Q("z-50 p-0",R==="proximity"?"w-[28rem] border-slate-300 shadow-2xl ring-1 ring-slate-900/10":R==="dateOfSale"?"w-[24rem]":"w-80"),sideOffset:4,children:[e.jsx("div",{className:Xv,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:Jv,"data-testid":"source-editor-title",children:ma}),e.jsx("p",{className:eN,children:"Select a source candidate for this comparable."})]}),e.jsx("button",{type:"button",onClick:()=>E(!1),className:"rounded p-0.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600","aria-label":"Close","data-testid":`button-close-source-picker-${t}`,children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]})}),e.jsxs("div",{className:"p-1",role:"radiogroup","aria-label":`${ma} source`,children:[tr.map(qe=>{const Ze=qe.value!==null&&qe.value!==void 0,It=R==="proximity"?a.source!=="User":(_??a.source)===qe.source;return e.jsxs("div",{className:Q("grid min-h-8 grid-cols-[20px_38px_1fr_auto] items-center gap-1.5 rounded px-2 py-0.5",Ze?"hover:bg-slate-50":"opacity-50"),"data-testid":Ze?`source-${qe.key}-${t}`:`source-empty-${qe.key}-${t}`,"data-editor-row":Ce?"compact-transaction":void 0,children:[e.jsx("button",{type:"button",role:"radio","aria-checked":It,"aria-label":`Use ${qe.label}`,disabled:!Ze,onClick:()=>{!Ze||a.value===qe.value&&a.source===qe.source||(fe.has(R)||R==="proximity"?ua(qe.value,qe.source):s(qe.value,$e?`SelectOnly:${qe.source}`:qe.source))},className:Q("flex h-4 w-4 items-center justify-center rounded border",It?"border-sky-600 bg-sky-600 text-white":"border-slate-300 bg-white"),children:It&&e.jsx(Bs,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:Q("h-2 w-2 rounded-full",qe.dotClass)}),e.jsx("span",{className:Gh,children:qe.label})]}),e.jsx("span",{className:Q(tN,Ze?"font-medium text-slate-900":"text-slate-400"),children:Ze?We(qe.value):"No data"}),re(qe.source,qe.value,qe.key)]},qe.key)}),e.jsxs("div",{className:"grid min-h-8 grid-cols-[20px_38px_1fr_auto] items-center gap-1.5 rounded px-2 py-0.5 hover:bg-slate-50","data-testid":`source-user-${t}`,children:[e.jsx("button",{type:"button",role:"radio","aria-checked":(_??a.source)==="User","aria-label":"Use User",disabled:R!=="proximity"&&!pr&&!$e,onClick:()=>
39{if(!(!pr&&!$e||a.value===zs&&a.source==="User")){if(R==="concessions"){$("User"),V(zs==null||zs===""?"":"Amount"),W(qf("concessions",zs));return}R==="proximity"?ua(zs,"User"):fe.has(R)?ua(zs??"","User"):s(zs??"",$e?"SelectOnly:User":"User")}},className:Q("flex h-4 w-4 items-center justify-center rounded border",(_??a.source)==="User"?"border-violet-600 bg-violet-600 text-white":"border-slate-300 bg-white"),children:(_??a.source)==="User"&&e.jsx(Bs,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-violet-500"}),e.jsx("span",{className:Gh,children:"User"})]}),e.jsxs("div",{className:Q(R==="dateOfSale"?"flex min-w-0 items-center gap-1":"relative min-w-0",Ce&&R!=="dateOfSale"&&"h-7 items-center"),children:[R==="proximity"?e.jsxs("div",{className:"grid min-w-0 grid-cols-[0.8fr_1fr_0.9fr] items-center gap-1",children:[e.jsx("input",{type:"text",inputMode:"decimal",step:"0.01","aria-label":"User proximity distance",value:H,placeholder:"Distance",onChange:qe=>{const Ze=qe.target.value;ye(Ze),Ze.trim()!==""&&Number(Ze)===0&&(ge("Miles"),He(""))},onBlur:qa,onKeyDown:qe=>{qe.key==="Enter"&&qe.currentTarget.blur()},className:Q(rp,"h-7 min-w-0 rounded border border-slate-200 bg-white px-1.5 outline-none placeholder:text-slate-400 focus:border-sky-400 focus:ring-1 focus:ring-sky-200"),"data-testid":`input-user-proximity-distance-${t}`}),e.jsxs("select",{"aria-label":"User proximity unit",value:At?"Miles":de,disabled:!ya||At,onChange:qe=>{const Ze=qe.target.value;ge(Ze),Xa(H,Ze,Be)},className:Q(rp,"h-7 min-w-0 rounded border border-slate-200 bg-white px-1.5 outline-none disabled:text-slate-300 focus:border-sky-400 focus:ring-1 focus:ring-sky-200"),"data-testid":`select-user-proximity-unit-${t}`,children:[e.jsx("option",{value:"Miles",children:"Miles"}),e.jsx("option",{value:"Kilometers",children:"Km."})]}),e.jsxs("select",{"aria-label":"User proximity direction",value:Be,disabled:!Fe,onChange:qe=>{const Ze=qe.target.value;He(Ze),Xa(H,de,Ze)},className:Q(rp,"h-7 min-w-0 rounded border border-slate-200 bg-white px-1.5 outline-none disabled:text-slate-300 focus:border-sky-400 focus:ring-1 focus:ring-sky-200"),"data-testid":`select-user-proximity-direction-${t}`,children:[e.jsx("option",{value:"",children:"Direction"}),Oa.map(({value:qe,label:Ze})=>e.jsx("option",{value:qe,children:Ze},qe))]})]}):R==="dateOfSale"?e.jsx(vN,{value:pe,onChange:qe=>{se(qe),s(qe,"User")},testId:`input-user-${t}`,inputAriaLabel:`User ${pt[R]} value`,className:"min-w-0 flex-1",inputClassName:Q(rp,"h-7 min-w-0 placeholder-hint md:text-[11px]"),pickerButtonClassName:"h-7 w-7 p-0"}):R==="saleType"?e.jsxs("div",{className:"relative",children:[e.jsx("input",{"aria-label":`User ${pt[R]} value`,type:"text",value:me,onFocus:()=>D(!0),onBlur:()=>{window.setTimeout(()=>D(!1),0)},onChange:qe=>{const Ze=qe.currentTarget.value.trim();Z(qe.currentTarget.value);const It=cp(Ze),Ne=Ve.get(Ze.toLocaleLowerCase()),Ue=vt.has(It)?It:Ne,ct=Ze?Ue||"Other":"";s(ct,"User"),ct==="Other"&&Ze?d?.("saleTypeOtherDescription",Ze==="Other"?c?.saleTypeOtherDescription??"":Ze,"User"):d?.("saleTypeOtherDescription","","User")},className:Q(rp,"h-7 w-full min-w-0 rounded border border-slate-200 bg-white px-2 pr-7 outline-none placeholder:text-slate-400 focus:border-sky-400 focus:ring-1 focus:ring-sky-200"),"data-testid":`input-user-${t}`}),ae&&sa.length>0&&e.jsx("div",{role:"listbox","data-testid":`select-user-${t}-listbox`,className:"absolute left-0 right-0 top-8 z-10 max-h-40 overflow-y-auto rounded border border-slate-200 bg-white p-1 shadow-lg",children:sa.map(qe=>e.jsx("button",{type:"button",role:"option","aria-selected":!1,className:"block w-full rounded px-2 py-1 text-left text-xs hover:bg-slate-50",onMouseDown:Ze=>{Ze.preventDefault(),Z(Hs("SaleType",qe)),s(qe,"User"),d?.("saleTypeOtherDescription","","User"),D(!1)},children:Hs("SaleType",qe)},qe))})]}):R==="attachedDetached"?e.jsxs("select",{"aria-label":`User ${pt[R]} value`,value:zs??"",onChange:qe=>{const Ze=qe.target.value;Ze&&s(Ze,"User")},className:Q(rp,"placeholder-hint h-7 w-full min-w-0 rounded border border-slate-200 bg-white px-2 pr-7 outline-none focus:border-sky-400 focus:ring-1 focus:ring-sky-200",pr?"text-slate-900":"text-slate-400"),"data-testid":`select-user-${t}`,children:[e.jsx("option",{value:"",children:"Select..."}),e.jsx("option",{value:"Attached",children:"Attached"}),e.jsx("option",{value:"Detached",children:"Detached"})]}):R==="listingStatus"?e.jsx(rI,{value:zs===null?"":String(zs),onChange:qe=>{qe&&s(qe,"User")},ariaLabel:`User ${pt[R]} value`,testId:`select-user-${t}`}):e.jsx("input",{"aria-label":`User ${pt[R]} value`,type:"text",inputMode:"numeric",defaultValue:qf(R,zs),placeholder:"Enter value...",onBlur:qe=>{const Ze=Cm(qe.currentTarget.value);Ze===null||String(zs??"")===String(Ze)||s(Ze,"User")},onKeyDown:qe=>{qe.key==="Enter"&&qe.currentTarget.blur()},className:Q(rp,"h-7 w-full min-w-0 rounded border border-slate-200 bg-white px-2 pr-7 outline-none placeholder:text-slate-400 focus:border-sky-400 focus:ring-1 focus:ring-sky-200"),"data-testid":`input-user-${t}`},`${t}:${String(zs??"")}`),pr&&R!=="proximity"&&e.jsx("button",{type:"button","aria-label":`Clear User ${pt[R]} value`,className:Q(R==="dateOfSale"?"shrink-0 rounded p-1 text-slate-400 hover:text-slate-700":"absolute top-1/2 right-5 -translate-y-1/2 roun
39ded p-0.5 text-slate-400 hover:text-slate-700"),onClick:()=>{R==="dateOfSale"&&se(""),s("","ClearUser"),R==="saleType"&&d?.("saleTypeOtherDescription","","ClearUser")},"data-testid":`button-clear-user-${t}`,children:e.jsx(ur,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[re("User",zs,"user"),R==="proximity"&&e.jsx(De,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-slate-400 hover:text-red-600",title:"Clear User proximity","aria-label":"Clear User proximity",onClick:()=>{d?.("ProximityToSubjectDistanceLinearMeasure","","User"),d?.("LinearUnitOfMeasureType","","User"),d?.("ComparableToSubjectDirectionType","","User"),ye(""),ge("Miles"),He("")},"data-testid":`button-clear-user-${t}`,children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})]})]})]})]})]})}return Me?e.jsxs(xn,{open:O,onOpenChange:E,children:[e.jsx(bn,{asChild:!0,children:S}),e.jsxs(yn,{align:"start",collisionPadding:8,className:"w-80 p-0",sideOffset:4,"data-testid":`direct-option-picker-${R}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-slate-200 px-2 py-1.5",children:[e.jsx("p",{className:"text-[9px] font-medium uppercase tracking-wide text-slate-500",children:Re==="location"?"Site Influence":"View"}),e.jsx("button",{type:"button",onClick:()=>E(!1),className:"rounded p-0.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600","aria-label":"Close","data-testid":`button-close-source-picker-${t}`,children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"p-2",children:e.jsx($h,{fieldType:Re,currentValue:a.value,onSelect:s,onCopyToAllComps:Ie,uad36:h,otherDescriptions:c,onOtherDescriptionChange:d})})]})]}):e.jsxs(xn,{open:O,onOpenChange:tt=>{tt||na(!1),tt&&T&&($t(String(a.value??"")),rt.current=!1),E(tt)},children:[e.jsx(bn,{asChild:!0,children:S}),O&&fe.has(R)&&Wp.createPortal(e.jsx("button",{type:"button","aria-label":"Close Sales Concessions editor",className:"fixed inset-0 z-40 cursor-default bg-slate-950/35 backdrop-blur-[1px]","data-testid":R==="concessions"?`sales-concessions-editor-overlay-${t}`:"transaction-editor-backdrop",onClick:()=>E(!1)}),document.body),e.jsxs(yn,{align:"start",collisionPadding:8,onEscapeKeyDown:()=>{T&&(rt.current=!1,Oe.current="")},className:Q("p-0 overflow-y-auto max-h-[var(--radix-popover-content-available-height)]",ne?"w-80":"w-56"),sideOffset:4,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 p-2 border-b border-slate-200",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("p",{className:"text-[10px] uppercase font-semibold text-slate-500 tracking-wide",children:"SELECT SOURCE"})}),e.jsx("button",{type:"button",onClick:()=>E(!1),className:"rounded p-0.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600","aria-label":"Close","data-testid":`button-close-source-picker-${t}`,children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"p-1",children:[(a.mlsValue!==null&&a.mlsValue!==void 0||fe.has(R))&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("button",{type:"button",role:fe.has(R)?"radio":void 0,"aria-checked":fe.has(R)?a.source==="MLS":void 0,"aria-label":fe.has(R)?"Use MLS":void 0,disabled:fe.has(R)&&(R==="concessions"?!st("MLS"):a.mlsValue===null||a.mlsValue===void 0),onClick:()=>ua(R==="concessions"?ut("MLS"):a.mlsValue,"MLS"),className:"flex-1 flex items-center gap-2 px-2 py-1.5 text-left hover:bg-slate-50 rounded","data-testid":`source-mls-${t}`,children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-sky-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-[10px] uppercase text-sky-600 font-medium",children:"MLS LISTING"}),e.jsx("p",{className:"text-[12px] text-slate-900 font-medium",children:Xt("MLS",a.mlsValue)})]}),a.source==="MLS"&&e.jsx(Bs,{className:"w-4 h-4 text-green-600"})]}),i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"ghost",className:Q("h-8 w-8 p-0",l==="MLS"?"text-amber-500":"text-slate-300 hover:text-amber-500"),onClick:tt=>{tt.stopPropagation(),i(R,"MLS")},"data-testid":`button-fav-mls-${t}`,children:e.jsx(Lo,{className:Q("w-3.5 h-3.5",l==="MLS"&&"fill-amber-500")})})}),e.jsx(Wa,{side:"right",className:"text-xs",children:l==="MLS"?"Default source":"Set as default"})]}),r&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"ghost",className:"h-8 w-8 p-0 text-slate-400 hover:text-sky-600",onClick:tt=>{tt.stopPropagation(),r(a.mlsValue,"MLS"),E(!1)},"data-testid":`button-copy-mls-${t}`,children:e.jsx(jr,{className:"w-3.5 h-3.5"})})}),e.jsx(Wa,{side:"right",className:"text-xs",children:"Copy MLS to all comps"})]})]}),lt(a.mlsValue)&&je("MLS LISTING","bg-sky-300","mls"),(a.prValue!==null&&a.prValue!==void 0||fe.has(R))&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("button",{type:"button",role:fe.has(R)?"radio":void 0,"aria-checked":fe.has(R)?a.source==="PublicRecord":void 0,"aria-label":fe.has(R)?"Use PR":void 0,disabled:fe.has(R)&&(R==="concessions"?!st("PublicRecord"):a.prValue===null||a.prValue===void 0),onClick:()=>ua(R==="concessions"?ut("PublicRecord"):a.prValue,"PublicRecord"),className:"flex-1 flex items-center gap-2 px-2 py-1.5 text-left hover:bg-slate-50 rounded","data-testid":`source-pr-${t}`,children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-[10px] uppercase text-blue-600 font-medium",children:"PUBLIC RECORD"}),e.jsx("p",{className:"text-[12px] text-slate-900 font-medium",children:Xt("PublicRecord",a.prValue)})]}),a.source==="PublicRecord"&&e.jsx(Bs,{className:"w-4 h-4 text-green-600"})]}),i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"ghost",className:Q("h-8 w-8 p-0",l==="PublicRecord"?"text-amber-500":"text-slate-300 hover:text-amber-500"),onClick:tt=>{tt.stopPropagation(),i(R,"PublicRecord")},"data-testid":`button-fav-pr-${t}`,children:e.jsx(Lo,{className:Q("w-3.5 h-3.5",l==="PublicRecord"&&"fill-amber-500")})})}),e.jsx(Wa,{side:"right",className:"text-xs",children:l==="PublicRecord"?"Default source":"Set as default"})]}),r&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"ghost",className:"h-8 w-8 p-0 text-slate-400 hover:text-blue-600",onClick:tt=>{tt.stopPropagation(),r(a.prValue,"PublicRecord"),E(!1)},"data-testid":`button-copy-pr-${t}`,children:e.jsx(jr,{className:"w-3.5 h-3.5"})})}),e.jsx(Wa,{side:"right",className:"text-xs",children:"Copy PR to all comps"})]})]}),lt(a.prValue)&&je("PUBLIC RECORD","bg-blue-300","pr"),(a.aiValue!==null&&a.aiValue!==void 0||fe.has(R))&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("button",{type:"button",role:fe.has(R)?"radio":void 0,"aria-checked":fe.has(R)?a.source==="AI":void 0,"aria-label":fe.has(R)?"Use AI":void 0,disabled:fe.has(R)&&(R==="concessions"?!st("AI"):a.aiValue===null||a.aiValue===void 0),onClick:()=>ua(R==="concessions"?ut("AI"):a.aiValue,"AI"),className:"flex-1 flex items-center gap-2 px-2 py-1.5 text-left hover:bg-slate-50 rounded","data-testid":`source-ai-${t}`,children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-emerald-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-[10px] uppercase text-emerald-600 font-medium",children:"AI SUGGESTED"}),e.jsx("p",{className:"text-[12px] text-slate-900 font-medium",children:Xt("AI",a.aiValue)})]}),a.source==="AI"&&e.jsx(Bs,{className:"w-4 h-4 text-green-600"})]}),i&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"ghost",className:Q("h-8 w-8 p-0",l==="AI"?"text-amber-500":"text-slate-300 hover:text-amber-500"),onClick:tt=>{tt.stopPropagation(),i(R,"AI")},"data-testid":`button-fav-ai-${t}`,children:e.jsx(Lo,{className:Q("w-3.5 h-3.5",l==="AI"&&"fill-amber-500")})})}),e.jsx(Wa,{side:"right",className:"text-xs",children:l==="AI"?"Default source":"Set as default"})]}),r&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"ghost",className:"h-8 w-8 p-0 text-slate-400 hover:text-emerald-600",onClick:tt=>{tt.stopPropagation(),r(a.aiValue,"AI"),E(!1)},"data-testid":`button-copy-ai-${t}`,children:e.jsx(jr,{className:"w-3.5 h-3.5"})})}),e.jsx(Wa,{side:"right",className:"text-xs",children:"Copy AI value to all comps"})]})]}),lt(a.aiValue)&&je("AI SUGGESTED","bg-emerald-300","ai"),a.strValue!==null&&a.strValue!==void 0&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("button",{onClick:()=>ua(a.strValue,"Airbnb"),className:"flex-1 flex items-center gap-2 px-2 py-1.5 text-left hover:bg-slate-50 rounded","data-testid":`source-airbnb-${t}`,children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-rose-500"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-[10px] uppercase text-rose-600 font-medium",children:a.strProvider?a.strProvider.toUpperCase():"AIRBNB"}),e.jsx("p",{className:"text-[12px] text-slate-900 font-medium",children:We(a.strValue)})]}),a.source==="Airbnb"&&e.jsx(Bs,{className:"w-4 h-4 text-green-600"})]}),a.strListingUrl&&e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("a",{href:a.strListingUrl,target:"_blank",rel:"noopener noreferrer",className:"h-8 w-8 flex items-center justify-center text-slate-400 hover:text-rose-600 hover:bg-slate-100 rounded",onClick:tt=>tt.stopPropagation(),"data-testid":`link-airbnb-${t}`,children:e.jsx(rf,{className:"w-3.5 h-3.5"})})}),e.jsxs(Wa,{side:"right",className:"text-xs",children:["View on ",a.strProvider||"Airbnb"]})]})]}),Tt&&e.jsx("p",{className:"px-2 pt-1.5 pb-0.5 text-[10px] leading-snug text-slate-400",children:"Blank rows show which sources have no data for this field. Enter the values below."}),fe.has(R)&&e.jsxs("div",{className:"grid min-h-8 grid-cols-[20px_38px_1fr_auto] items-center gap-1.5 rounded px-2 py-0.5 hover:bg-slate-50","data-testid":`source-user-${t}`,children:[e.jsx("button",{type:"button",role:"radio","aria-checked":a.source==="User","aria-label":"Use User",onClick:()=>
39{if(R==="concessions")return;const tt=a.userValue??(a.source==="User"?a.value:"");s(tt??"","SelectOnly:User")},className:Q("flex h-4 w-4 items-center justify-center rounded border",a.source==="User"?"border-violet-600 bg-violet-600 text-white":"border-slate-300 bg-white"),children:a.source==="User"&&e.jsx(Bs,{className:"h-3 w-3"})}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-violet-500"}),e.jsx("span",{className:"text-[9px] font-medium uppercase tracking-wide text-slate-500",children:"User"})]}),e.jsx("span",{className:"truncate text-[11px] font-medium text-slate-900",children:a.userValue??(a.source==="User"?a.value:"")}),e.jsx("span",{})]})]}),ne&&R==="concessions"?e.jsxs("div",{className:"space-y-2 border-t border-slate-200 p-2",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase text-slate-500",children:"User concessions"}),e.jsx("div",{className:"grid grid-cols-3 overflow-hidden rounded-md border border-slate-200","data-testid":`select-user-${t}-mode`,role:"radiogroup","aria-label":"User sales concessions mode",children:["None","Unknown","Amount"].map(tt=>e.jsx("button",{type:"button",role:"radio","aria-label":tt,"aria-checked":z===tt,className:Q("h-8 border-r border-slate-200 text-[11px] font-medium last:border-r-0",z===tt?"bg-violet-600 text-white":"text-slate-600 hover:bg-slate-50"),onClick:()=>V(tt),children:tt},tt))}),z==="Amount"&&e.jsx(ze,{type:"text",inputMode:"decimal",value:le,onChange:tt=>W(tt.target.value),placeholder:"Enter concession amount","aria-label":"User sales concessions amount",className:"h-8 text-xs","data-testid":`input-user-${t}-amount`}),e.jsx("div",{className:"flex justify-end",children:e.jsx(De,{type:"button",size:"sm",onClick:()=>{if(z==="Amount"){const tt=Cm(le);if(tt===null||tt<0)return;m?.("User","Amount",tt)}else if(z==="None"||z==="Unknown")m?.("User",z,null);else return;E(!1)},"data-testid":`sales-concessions-save-${t}`,children:"Save"})})]}):ne?e.jsx("div",{className:"p-2 border-t border-slate-200",children:e.jsx($h,{fieldType:Re,currentValue:a.value,onSelect:(tt,it)=>{s(tt,it),lg(Re)||E(!1)},onCopyToAllComps:Ie?(tt,it)=>{Ie(tt,it),R!=="proximity"&&E(!1)}:void 0,onCopyCompanionToAllComps:n,uad36:h,otherDescriptions:c,onOtherDescriptionChange:d,basementHint:v})}):e.jsxs("div",{className:"p-2 border-t border-slate-200",children:[e.jsx("p",{className:"text-[10px] uppercase text-slate-500 font-medium mb-1.5",children:"MANUAL ENTRY"}),R==="proximity"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ze,{type:"number",value:H,onChange:tt=>ye(tt.target.value),placeholder:"Distance (e.g. 0.86)",min:0,step:"0.01",className:"h-8 text-[12px]","data-testid":`input-manual-prox-dist-${t}`}),Fe?e.jsxs(e.Fragment,{children:[e.jsxs(sr,{value:de,onValueChange:ge,children:[e.jsx(rr,{className:"h-8 text-[12px]","data-testid":`input-manual-prox-unit-${t}`,children:e.jsx(or,{placeholder:"Unit…"})}),e.jsxs(nr,{children:[e.jsx(vs,{value:"Miles",children:"Miles"}),e.jsx(vs,{value:"Kilometers",children:"Km"})]})]}),e.jsxs(sr,{value:Be||void 0,onValueChange:He,children:[e.jsx(rr,{className:"h-8 text-[12px]","data-testid":`input-manual-prox-dir-${t}`,children:e.jsx(or,{placeholder:"Direction…"})}),e.jsx(nr,{children:Oa.map(({value:tt,label:it})=>e.jsx(vs,{value:tt,children:it},tt))})]})]}):e.jsx("p",{className:"text-[11px] text-slate-400",children:"Enter distance to add unit & direction"}),e.jsx(De,{size:"sm",className:"h-8 w-full text-xs",disabled:!ya,onClick:qa,"data-testid":`button-manual-prox-apply-${t}`,children:"Apply"})]}):e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(ze,{...Mo,type:qH(R)?"date":"text","aria-label":T?`${U}Neighborhood Name`:void 0,value:C,onChange:tt=>$t(tt.target.value),placeholder:We(a.value),className:"h-8 text-[12px]",onKeyDown:tt=>tt.key==="Enter"&&zt(),onBlur:()=>na(!0),"data-testid":`input-manual-${t}`}),e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"ghost",className:"h-8 px-2",onMouseDown:tt=>tt.preventDefault(),onClick:zt,children:e.jsx(Bs,{className:"w-4 h-4"})})}),e.jsx(Wa,{side:"top",className:"text-xs",children:"Apply to this comp"})]})}),r&&e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"outline",className:"h-8 px-2",onMouseDown:tt=>tt.preventDefault(),onClick:()=>
39{if(C.trim()){const tt=Number(C),it=isNaN(tt)?C.trim():tt;r(it,"User"),$t(""),E(!1)}},disabled:!C.trim(),"data-testid":`button-copy-to-comps-${t}`,children:e.jsx(jr,{className:"w-4 h-4"})})}),e.jsx(Wa,{side:"top",className:"text-xs",children:"Copy to all comps"})]})})]})]})]})]})}function LW({isOpen:t,onClose:a,photos:s,address:r,compSnapshotId:n,orderId:i,isSubject:l,coverPhotoUrl:c,onCoverChange:d,onPhotosChange:p}){const[u,m]=o.useState(0),[h,f]=o.useState(new Set),[v,S]=o.useState(c),[N,x]=o.useState([]),[y,b]=o.useState(!1),[j,T]=o.useState(!1),O=o.useRef(null),E=[...s,...N],R=!!(n||i&&l),G=M=>{f(B=>new Set(B).add(M))},U=async M=>{if(!y){b(!0);try{let B;if(n?B=await fetch(`/api/comps/${n}/photos/set-primary`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({photoUrl:M,orderId:i})}):i&&l&&(B=await fetch(`/api/orders/${i}/subject-photos/set-primary`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({photoUrl:M})})),B&&!B.ok){console.error("[PhotoGallery] set-primary failed:",B.status,await B.text().catch(()=>""));return}S(M),d?.(M)}catch(B){console.error("[PhotoGallery] set-primary error:",B)}finally{b(!1)}}},C=async M=>{if(!(j||!n)){T(!0);try{const{preprocessImage:B}=await ri(async()=>{const{preprocessImage:_}=await import("./uad36ImagePreprocess-5jaGBucA.js");return{preprocessImage:_}},[]),ae=(await B(M)).dataUrl,D=await fetch(`/api/comps/${n}/photos`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({photoUrls:[ae],source:"User",skipPrimaryUpdate:!0,orderId:i})});if(!D.ok){console.error("[PhotoGallery] upload failed:",D.status,await D.text().catch(()=>""));return}x(_=>[..._,ae]),p?.(ae),m(E.length)}catch(B){console.error("[PhotoGallery] upload error:",B)}finally{T(!1)}}},F=!l&&!!n;if(!E.length&&!F)return null;const A=E.length>0?Math.min(u,E.length-1):0;return e.jsx(xi,{open:t,onOpenChange:a,children:e.jsxs(bi,{className:"max-w-3xl max-h-[90vh]",children:[e.jsx($i,{children:e.jsx(si,{className:"text-sm font-medium truncate",children:r})}),e.jsxs("div",{className:"relative",children:[E.length===0?e.jsx("div",{className:"w-full h-[40vh] bg-slate-100 rounded-lg flex items-center justify-center",children:e.jsxs("div",{className:"text-center text-slate-400",children:[e.jsx(Wh,{className:"w-16 h-16 mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"No photos yet"}),n&&e.jsx("p",{className:"text-xs mt-1",children:"Upload a photo below"})]})}):h.has(A)?e.jsx("div",{className:"w-full h-[60vh] bg-slate-100 rounded-lg flex items-center justify-center",children:e.jsxs("div",{className:"text-center text-slate-400",children:[e.jsx(Wh,{className:"w-16 h-16 mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Image unavailable"})]})}):e.jsx("img",{src:rD(E[A]),alt:`Photo ${A+1}`,className:"w-full h-auto max-h-[60vh] object-contain rounded-lg",onError:()=>G(A)}),E.length>0&&R&&E[A]!==v&&!h.has(A)&&e.jsxs("button",{onClick:()=>U(E[A]),disabled:y,className:"absolute top-2 right-2 flex items-center gap-1 bg-black/60 hover:bg-black/80 text-white text-xs px-2 py-1 rounded-full transition-colors disabled:opacity-50","data-testid":"button-set-cover-main",title:"Set as cover photo",children:[e.jsx(Lo,{className:"w-3 h-3"}),y?"Saving…":"Set as cover"]}),E.length>0&&E[A]===v&&e.jsxs("span",{className:"absolute top-2 right-2 flex items-center gap-1 bg-amber-500/90 text-white text-xs px-2 py-1 rounded-full",children:[e.jsx(Lo,{className:"w-3 h-3 fill-white"}),"Cover"]}),E.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>m(M=>(M-1+E.length)%E.length),className:"absolute left-2 top-1/2 -translate-y-1/2 bg-black/50 text-white p-2 rounded-full hover:bg-black/70","data-testid":"button-gallery-prev",children:e.jsx(oy,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>m(M=>(M+1)%E.length),className:"absolute right-2 top-1/2 -translate-y-1/2 bg-black/50 text-white p-2 rounded-full hover:bg-black/70","data-testid":"button-gallery-next",children:e.jsx(fo,{className:"w-5 h-5"})}),e.jsxs("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 bg-black/50 text-white text-xs px-2 py-1 rounded",children:[A+1," / ",E.length]})]})]}),e.jsxs("div",{className:"flex gap-1 overflow-x-auto py-2 items-center",children:[E.map((M,B)=>{const oe=M===v;return e.jsxs("div",{className:"relative shrink-0 group/thumb",children:[e.jsx("button",{onClick:()=>m(B),className:Q("w-16 h-12 rounded overflow-hidden border-2 bg-slate-100",B===A?"border-blue-500":oe?"border-amber-400":"border-transparent"),"data-testid":`gallery-thumb-${B}`,children:h.has(B)?e.jsx("div",{className:"w-full h-full flex items-center justify-center text-slate-300",children:e.jsx(Wh,{className:"w-4 h-4"})}):e.jsx("img",{src:MI(M),alt:`Thumb ${B+1}`,className:"w-full h-full object-cover",onError:()=>G(B)})}),oe&&e.jsx("span",{className:"absolute top-0.5 left-0.5 bg-amber-500 rounded-sm p-0.5 pointer-events-none",children:e.jsx(Lo,{className:"w-2 h-2 fill-white text-white"})}),R&&!oe&&!h.has(B)&&e.jsx("button",{onClick:()=>U(M),disabled:y,className:"absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover/thumb:opacity-100 transition-opacity rounded disabled:cursor-not-allowed",title:"Set as cover","data-testid":`button-set-cover-thumb-${B}`,children:e.jsx(Lo,{className:"w-4 h-4 text-white"})})]},B)}),n&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:O,type:"file",accept:"image/*",className:"hidden",onChange:M=>{const B=M.target.files?.[0];B&&C(B),M.target.value=""},"data-testid":"input-gallery-upload"}),e.jsx("button",{onClick:()=>O.current?.click(),disabled:j,className:"shrink-0 w-16 h-12 rounded border-2 border-dashed border-slate-300 hover:border-slate-400 bg-slate-50 hover:bg-slate-100 flex flex-col items-center justify-center gap-0.5 text-slate-400 hover:text-slate-600 transition-colors disabled:opacity-50","data-testid":"button-gallery-add-photo",title:"Upload a new photo",children:j?e.jsx(za,{className:"w-4 h-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[9px] leading-tight",children:"Add"})]})})]})]})]})})}function aI({property:t,index:a,onPhotoClick:s,isDragging:r=!1,dragListeners:n,dragAttributes:i,onHide:l,onReplace:c,onRemove:d,allExpanded:p=!1,onFieldU
39pdate:u,coverPhotoUrl:m,onSubjectPhotoUpload:h,missingCount:f,compact:v=!1,uad36Active:S=!1,b1GatingActive:N=!1,onComparableProjectClassificationChange:x,onComparableStructuresChange:y}){const{inspecting:b}=fc(),j=t.photos||(t.photoUrl?[t.photoUrl]:[]),T=m||j[0],O=RW(t.status,t.rawMlsStatus),[E,R]=o.useState(!1),G=o.useRef(null),[U,C]=o.useState(!1),[F,A]=o.useState(!1),[M,B]=o.useState(!1),[oe,ae]=o.useState(""),D=T!=null&&!E,_=!t.isSubject&&!!n&&!v,$=t.isSubject?"subjectProperty":"salesComparison",z=t.isSubject?"":Zi(t.id,""),[V,le]=o.useState(v);o.useEffect(()=>{if(v){le(!0);return}const be=setTimeout(()=>le(!1),350);return()=>clearTimeout(be)},[v]);const W=t.fields?.salePrice?.value,me=typeof W=="number"?ng(W):typeof W=="string"&&W?W:null,Z=t.lat!=null&&t.lng!=null,pe=typeof t.distance=="number"&&(t.distance!==0||Z)?t.distance.toFixed(1):null,se=t.fields?.gla?.value;typeof se=="number"||typeof se=="string"&&parseInt(se.replace(/[^0-9]/g,""),10),t.fields?.daysOnMarket?.value,t.fields?.saleType?.value;const fe=()=>{const be=String(typeof W=="number"?W:W||"");ae(be),B(!0)},ue=()=>{const be=parseInt(oe.replace(/[^0-9]/g,""),10);!isNaN(be)&&u&&u(t.id,"salePrice",be,"User"),B(!1)};return e.jsxs("div",{className:Q("px-1 py-2 relative",a===1&&"border-l-2 border-slate-300",r&&"opacity-50 ring-2 ring-blue-400 ring-offset-2 z-50"),children:[e.jsxs("div",{className:Q("flex items-center gap-1.5 min-w-0 overflow-hidden transition-all duration-300 motion-reduce:transition-none",v?"max-h-8 opacity-100":"max-h-0 opacity-0 pointer-events-none"),"aria-hidden":!v,"data-testid":`header-compact-${t.id}`,children:[e.jsx("div",{className:"w-9 h-7 shrink-0 rounded overflow-hidden bg-slate-200 flex items-center justify-center",children:D?e.jsx("img",{src:rb(T),alt:t.address,className:"w-full h-full object-cover",loading:"lazy"}):e.jsx(Wh,{className:"w-3.5 h-3.5 text-slate-400"})}),t.isSubject?e.jsx("span",{className:"shrink-0 text-[9px] font-bold uppercase px-1.5 py-0.5 rounded bg-amber-500 text-white shadow-sm",children:"Subject"}):e.jsxs("span",{className:"shrink-0 text-[9px] font-bold uppercase px-1.5 py-0.5 rounded bg-[#0f2942] text-white shadow-sm",children:["Comp ",a]}),e.jsx("span",{className:"truncate text-[11px] font-semibold text-slate-700",title:t.address,"data-testid":`compact-address-${t.id}`,children:t.address.split(",")[0]}),b&&S&&e.jsx(Fs,{section:$,fieldName:t.isSubject?"AddressLineText":`${z}.fields.AddressLineText`,displayLabel:t.isSubject?"Subject · Address":`Comp ${a} · Address`})]}),e.jsxs("div",{className:Q("relative rounded-lg border border-slate-200 group transition-all duration-300 motion-reduce:transition-none",v?"max-h-0 opacity-0 pointer-events-none border-transparent":"max-h-[260px] opacity-100",V&&"overflow-hidden"),"aria-hidden":v,children:[e.jsxs("div",{className:Q("peer w-full relative aspect-[4/3] overflow-hidden rounded-t-lg",_&&"cursor-grab active:cursor-grabbing",!_&&"cursor-default"),"data-testid":`header-${t.id}`,..._?n:{},..._?i:{},children:[D?e.jsx("img",{src:rb(T),alt:t.address,className:"absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-200",onError:()=>R(!0),loading:"lazy"}):e.jsx("div",{className:"absolute inset-0 w-full h-full bg-slate-200 flex items-center justify-center",children:e.jsx(Wh,{className:"w-8 h-8 text-slate-400"})}),D&&e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 via-trans
39parent to-black/5"}),e.jsxs("div",{className:"absolute top-1.5 left-1.5 right-1.5 flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[t.isSubject&&e.jsx("span",{className:"text-[9px] font-bold uppercase px-1.5 py-0.5 rounded bg-amber-500 text-white shadow-sm",children:"Subject"}),!t.isSubject&&e.jsxs("span",{className:"text-[9px] font-bold uppercase px-1.5 py-0.5 rounded bg-[#0f2942] text-white shadow-sm",children:["Comp ",a]}),e.jsx("span",{className:Q("text-[9px] font-semibold px-1.5 py-0.5 rounded-full",O.bg,O.text),children:O.label})]}),!t.isSubject&&(l||c||d)&&e.jsxs("div",{className:"relative z-50 flex items-center gap-0.5 opacity-100 transition-opacity",children:[_&&e.jsx("span",{className:"bg-white/80 hover:bg-white text-slate-500 rounded p-1 cursor-grab",children:e.jsx(pN,{className:"w-3 h-3"})}),l&&e.jsx("button",{onClick:be=>{be.stopPropagation(),l()},className:"bg-white/80 hover:bg-white text-slate-500 rounded p-1","data-testid":`button-hide-comp-${t.id}`,title:"Hide comp",children:e.jsx(XO,{className:"w-3 h-3"})}),c&&e.jsx("button",{onClick:be=>{be.stopPropagation(),c()},className:"bg-white/80 hover:bg-white text-slate-500 rounded p-1","data-testid":`button-replace-comp-${t.id}`,title:"Replace comp",children:e.jsx(Kl,{className:"w-3 h-3"})}),d&&e.jsx("button",{onClick:be=>{be.stopPropagation(),d()},className:"bg-white/80 hover:bg-red-100 text-red-500 rounded p-1","data-testid":`button-remove-comp-${t.id}`,title:"Remove comp",children:e.jsx(Ci,{className:"w-3 h-3"})}),S&&N&&u&&e.jsx("span",{className:"bg-white/80 hover:bg-white text-slate-500 rounded p-0",onClick:be=>be.stopPropagation(),children:e.jsx(yW,{itemId:t.id,compNumber:a,fields:t.fields,structures:qL(t.fields),onFieldChange:(be,H)=>u(t.id,be,H??"","manual"),onStructuresChange:be=>{y&&y(t.id,be)},onProjectClassificationChange:x?be=>x(t.id,be):void 0,disabled:!1,showPropertyRights:!1})})]})]}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-2 pb-1.5 flex items-end justify-between z-50",children:[M?e.jsx("span",{className:"inline-block bg-black/70 backdrop-blur-sm rounded px-1.5 py-0.5",children:e.jsx("input",{autoFocus:!0,t
39ype:"text",value:oe,onChange:be=>ae(be.target.value),onKeyDown:be=>{be.key==="Enter"?ue():be.key==="Escape"&&B(!1)},onBlur:ue,className:"w-24 h-5 bg-transparent text-white font-bold text-[15px] leading-tight outline-none border-b border-white/50","data-testid":`input-edit-price-${t.id}`})}):me?e.jsx("span",{className:"inline-block bg-black/50 backdrop-blur-sm rounded px-1.5 py-0.5 cursor-pointer hover:bg-black/70 transition-colors",onClick:be=>{be.stopPropagation(),fe()},title:"Click to edit price","data-testid":`editable-price-${t.id}`,children:e.jsx("span",{className:"text-white font-bold text-[15px] leading-tight",children:me})}):u&&e.jsx("span",{className:"inline-block bg-black/50 backdrop-blur-sm rounded px-1.5 py-0.5 cursor-pointer hover:bg-black/70 transition-colors",onClick:be=>{be.stopPropagation(),fe()},title:"Click to set price","data-testid":`editable-price-${t.id}`,children:e.jsx("span",{className:"text-white/60 text-[12px]",children:"Set price"})}),!t.isSubject&&pe&&e.jsxs("span",{className:"inline-block bg-black/50 backdrop-blur-sm rounded px-1.5 py-0.5 text-[10px] text-white font-medium",children:[pe," mi"]})]}),e.jsx("button",{onClick:be=>{be.stopPropagation(),s()},className:"absolute inset-0 w-full h-full opacity-0 z-10","data-testid":`photo-click-${t.id}`,"aria-label":`View details for ${t.address}`}),t.isSubject&&h&&e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:G,type:"file",accept:"image/*",className:"hidden",onChange:async be=>{const H=be.target.files?.[0];if(H){C(!0);try{await h(H),R(!1)}finally{C(!1)}be.target.value=""}},"data-testid":"input-subject-photo-upload"}),e.jsx("button",{onClick:be=>{be.stopPropagation(),G.current?.click()},disabled:U,className:"absolute bottom-1.5 right-1.5 z-50 flex items-center gap-1 bg-black/60 hover:bg-black/80 text-white text-[10px] px-1.5 py-0.5 rounded-full opacity-0 group-hover:opacity-100 transition-opacity disabled:opacity-50","data-testid":"button-subject-photo-upload",title:D?"Replace cover photo":"Upload photo",children:U?e.jsx(za,{className:"w-3 h-3 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"w-2.5 h-2.5"}),D?"Replace":"Add photo"]})})]}),b&&S&&e.jsx("div",{className:"absolute bottom-1.5 left-1.5 z-50 max-w-[calc(100%-0.75rem)]",children:e.jsx(Fs,{section:$,fieldName:t.isSubject?"SubjectPhoto":`${z}.photos`,displayLabel:t.isSubject?"Subject · Photo":`Comp ${a} · Photo`})})]}),D&&e.jsx("div",{className:"pointer-events-none absolute left-1/2 top-0 z-40 hidden w-[320px] max-w-[80vw] -translate-x-1/2 peer-hover:block","data-testid":`photo-enlarge-${t.id}`,children:e.jsx("img",{src:rD(T),alt:t.address,className:"w-full rounded-lg shadow-2xl ring-2 ring-white/80",loading:"lazy"})}),e.jsxs("div",{className:"w-full flex items-center justify-center gap-1.5 px-2 py-1 bg-slate-50 text-slate-700 border-t border-slate-200 rounded-b-lg","data-testid":`card-title-${t.id}`,children:[e.jsx("span",{className:"font-bold truncate text-[14px]",children:t.address.split(",")[0]}),b&&S&&e.jsx(Fs,{section:$,fieldName:t.isSubject?"AddressLineText":`${z}.fields.AddressLineText`,displayLabel:t.isSubject?"Subject · Address":`Comp ${a} · Address`}),!t.isSubject&&typeof f=="number"&&f>0&&e.jsxs("span",{className:"flex-shrink-0 inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full bg-slate-200 text-slate-600 text-[9px] font-semibold leading-none",title:`${f} missing data point${f===1?"":"s"}`,"data-testid":`badge-missing-count-${t.id}`,children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-slate-400"}),f," missing"]})]})]})]})}function DW({property:t,index:a,onPhotoClick:s,onHide:r,onReplace:n,onRemove:i,allExpanded:l,onFieldUpdate:c,coverPhotoUrl:d,missingCount:p,compact:u,uad36Active:m,b1GatingActive:h,onComparableProjectClassificationChange:f,onComparableStructuresChange:v}){const{attributes:S,listeners:N,setNodeRef:x,transform:y,transition:b,isDragging:j}=B5({id:t.id}),T={transform:z5.Transform.toString(y),transition:b};return e.jsx("div",{ref:x,style:T,children:e.jsx(aI,{property:t,index:a,onPhotoClick:s,isDragging:j,dragListeners:N,dragAttributes:S,onHide:r,onReplace:n,onRemove:i,allExpanded:l,onFieldU
39pdate:c,coverPhotoUrl:d,missingCount:p,compact:u,uad36Active:m,b1GatingActive:h,onComparableProjectClassificationChange:f,onComparableStructuresChange:v})})}function ju({property:t,isFirstComp:a,showMissing:s,onUpdateQuality:r,onUpdateCondition:n,qualityField:i="quality",conditionField:l="condition",onCopyQualityToAll:c,onCopyConditionToAll:d,fallbackQuality:p,fallbackCondition:u,showOnly:m,inspectSection:h,qualityInspectField:f,conditionInspectField:v,qualityInspectLabel:S,conditionInspectLabel:N,readOnly:x,readOnlyTitle:y,resolvedDisplay:b=!1,qualityFieldData:j,conditionFieldData:T}){const{inspecting:O}=fc(),E=j??t.fields?.[i],R=T??t.fields?.[l],G=E?.value,U=R?.value,C=!G&&p!=null&&p!=="",F=!U&&u!=null&&u!=="",A=G?String(G):C?String(p):"",M=U?String(U):F?String(u):"",B=fe=>{const ue=fe===i?E:fe===l?R:t.fields?.[fe];if(!(ue?.value===null||ue?.value===void 0||String(ue.value).trim()===""))return{MLS:"bg-sky-500",PublicRecord:"bg-amber-500",AI:"bg-emerald-500",User:"bg-violet-500",Airbnb:"bg-rose-500"}[ue.source]},oe=G==null?"":String(G).trim().toUpperCase(),ae=U==null?"":String(U).trim().toUpperCase(),D=P0.some(fe=>fe.code===oe),_=w0.some(fe=>fe.code===ae),$=P0.find(fe=>fe.code===oe)?.description,z=w0.find(fe=>fe.code===ae)?.description,[V,le]=o.useState(null),W=Ov("quality"),me=Ov("condition"),Z=i==="OverallQualityRatingCode",pe=l==="OverallConditionRatingCode",se=!!s&&((m==="condition"?!1:wm(t,i))||(m==="quality"?!1:wm(t,l)));return e.jsxs("div",{className:Q("px-3 py-[5px] flex items-center justify-start gap-2 text-left",t.isSubject?"border-l border-slate-200":a?"border-l-2 border-l-slate-300":"border-l border-slate-200",Gl({fieldName:"qualityCondition",isMissing:se})),children:[m!=="condition"&&e.jsxs(e.Fragment,{children:[B(i)&&!Z&&e.jsx("span",{className:Q("inline-block h-1.5 w-1.5 shrink-0 rounded-full",B(i)),"aria-label":`Source: ${E?.source}`,"data-testid":`source-dot-${t.id}-${i}`}),Z?e.jsxs("div",{className:"inline-flex min-w-0 items-center justify-start gap-2",children:[B(i)&&e.jsx("span",{className:Q("inline-block h-1.5 w-1.5 shrink-0 rounded-full",B(i)),"aria-label":`Source: ${E?.source}`,"data-testid":`source-dot-${t.id}-${i}`}),e.jsxs(Ga,{children:[e.jsxs(sr,{"aria-label":`${t.isSubject?"Subject":"Comparable"} overall quality`,value:oe||"__unanswered__",disabled:x,onValueChange:fe=>r?.(fe==="__unanswered__"?"":fe,"User"),children:[e.jsx(Ha,{asChild:!0,children:e.jsx(rr,{"aria-label":`${t.isSubject?"Subject":"Comparable"} overall quality`,className:Q("h-6 w-[54px] min-w-[54px] !justify-start rounded px-1 !text-xs !font-normal !leading-5 focus:ring-1 focus:ring-blue-400",x?"cursor-default opacity-80":"cursor-pointer",b?"border-transparent bg-transparent text-slate-700 shadow-none hover:bg-slate-50 [&>svg]:hidden":oe?C?"border-dashed border-blue-300 bg-blue-50 text-blue-500":"border-slate-200 bg-white text-slate-700 hover:bg-slate-50":"border-rose-300 bg-rose-50 text-rose-700"),"aria-invalid":!oe||void 0,"data-testid":`select-${i}-${t.id}`,title:x?y:$,children:e.jsx(or,{})})}),e.jsxs(nr,{position:"popper",className:"min-w-[150px]",children:[e.jsx(vs,{value:"__unanswered__",textValue:"Leave unanswered","aria-label":"Leave unanswered"}),oe&&!D&&e.jsxs(vs,{value:oe,children:[oe," (legacy value)"]}),P0.map(fe=>e.jsx(vs,{value:fe.code,title:fe.description,"data-testid":`option-${i}-${t.id}-${fe.code}`,children:fe.code},fe.code)),c&&oe&&D&&e.jsx("div",{className:"mt-1 border-t border-slate-200 p-1",children:e.jsxs("button",{type:"button",onPointerDown:fe=>{fe.preventDefault(),fe.stopPropagation(),c(oe,"User")},className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[11px] font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900 focus:outline-none focus:ring-1 focus:ring-blue-400",title:`Copy ${oe} to all comps`,"data-testid":"uad-quality-copy-all",children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),"Copy ",oe," to all comps"]})})]})]}),e.jsx(Wa,{children:$??"Select Q1–Q6 or leave unanswered"})]})]}):e.jsxs(xn,{open:!x&&V==="quality",onOpenChange:fe=>{fe||le(null)},children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{onClick:()=>{x||le("quality")}
39,className:Q("inline-flex min-h-[18px] items-center justify-start gap-0.5 rounded px-0 py-0 !text-xs !font-normal !leading-5 transition-colors",x?"cursor-default":"cursor-pointer",b?"border-transparent bg-transparent text-slate-700 hover:bg-slate-50 [&>svg]:hidden":C?"bg-blue-50 text-blue-500 border border-dashed border-blue-300 hover:bg-blue-100":"bg-white text-slate-700 border border-slate-200 hover:bg-slate-50"),"data-testid":`badge-${i}-${t.id}`,title:x?y:C?"Defaulted from Overall Quality — click to confirm or change":"Click to edit quality",children:[A,!x&&e.jsx(Rr,{className:"w-2.5 h-2.5 opacity-60"})]})}),e.jsx(yn,{align:"start",className:"w-72 p-2",sideOffset:4,children:e.jsx($h,{fieldType:W,currentValue:G!=null?String(G):null,onSelect:(fe,ue)=>{r?.(fe,ue),lg(W)||le(null)},onCopyToAllComps:c?(fe,ue)=>{c(fe,ue),le(null)}:void 0})})]}),O&&h&&f&&e.jsx(Fs,{section:h,fieldName:f,displayLabel:S})]}),!m&&e.jsx("span",{className:"text-slate-300 text-[10px]",children:"/"}),m!=="quality"&&e.jsxs(e.Fragment,{children:[B(l)&&!pe&&e.jsx("span",{className:Q("inline-block h-1.5 w-1.5 shrink-0 rounded-full",B(l)),"aria-label":`Source: ${R?.source}`,"data-testid":`source-dot-${t.id}-${l}`}),pe?e.jsxs("div",{className:"inline-flex min-w-0 items-center gap-1",children:[B(l)&&e.jsx("span",{className:Q("inline-block h-1.5 w-1.5 shrink-0 rounded-full",B(l)),"aria-label":`Source: ${R?.source}`,"data-testid":`source-dot-${t.id}-${l}`}),e.jsxs(Ga,{children:[e.jsxs(sr,{"aria-label":`${t.isSubject?"Subject":"Comparable"} overall condition`,value:ae||"__unanswered__",disabled:x,onValueChange:fe=>n?.(fe==="__unanswered__"?"":fe,"User"),children:[e.jsx(Ha,{asChild:!0,children:e.jsx(rr,{"aria-label":`${t.isSubject?"Subject":"Comparable"} overall condition`,className:Q("h-6 w-[54px] min-w-[54px] !justify-start rounded px-1 !text-xs !font-normal !leading-5 focus:ring-1 focus:ring-amber-400",x?"cursor-default opacity-80":"cursor-pointer",b?"border-transparent bg-transparent text-slate-700 shadow-none hover:bg-slate-50 [&>svg]:hidden":ae?F?"border-dashed border-amber-300 bg-amber-50 text-amber-500":"border-slate-200 bg-white text-slate-700 hover:bg-slate-50":"border-rose-300 bg-rose-50 text-rose-700"),"aria-invalid":!ae||void 0,"data-testid":`select-${l}-${t.id}`,title:x?y:z,children:e.jsx(or,{})})}),e.jsxs(nr,{position:"popper",className:"min-w-[150px]",children:[e.jsx(vs,{value:"__unanswered__",textValue:"Leave unanswered","aria-label":"Leave unanswered"}),ae&&!_&&e.jsxs(vs,{value:ae,children:[ae," (legacy value)"]}),w0.map(fe=>e.jsx(vs,{value:fe.code,title:fe.description,"data-testid":`option-${l}-${t.id}-${fe.code}`,children:fe.code},fe.code)),d&&ae&&_&&e.jsx("div",{className:"mt-1 border-t border-slate-200 p-1",children:e.jsxs("button",{type:"button",onPointerDown:fe=>{fe.preventDefault(),fe.stopPropagation(),d(ae,"User")},className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[11px] font-medium text-slate-600 hover:bg-slate-100 hover:text-slate-900 focus:outline-none focus:ring-1 focus:ring-amber-400",title:`Copy ${ae} to all comps`,"data-testid":"uad-condition-copy-all",children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),"Copy ",ae," to all comps"]})})]})]}),e.jsx(Wa,{children:z??"Select C1–C6 or leave unanswered"})]})]}):e.jsxs(xn,{open:!x&&V==="condition",onOpenChange:fe=>{fe||le(null)},children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{onClick:()=>{x||le("condition")},className:Q("inline-flex min-h-[18px] items-center justify-start gap-0.5 rounded px-0 py-0 !text-xs !font-normal !leading-5 transition-colors",x?"cursor-default":"cursor-pointer",b?"border-transparent bg-transparent text-slate-700 hover:bg-slate-50 [&>svg]:hidden":F?"bg-amber-50 text-amber-500 border border-dashed border-amber-300 hover:bg-amber-100":"bg-white text-slate-700 border border-slate-200 hover:bg-slate-50"),"data-testid":`badge-${l}-${t.id}`,title:x?y:F?"Defaulted from Overall Condition — click to confirm or change":"Click to edit condition",children:[M,!x&&e.jsx(Rr,{className:"w-2.5 h-2.5 opacity-60"})]})}),e.jsx(yn,{align:"start",className:"w-72 p-2",sideOffset:4,children:e.jsx($h,{fieldType:me,currentValue:U!=null?String(U):null,onSelect:(fe,ue)=>{n?.(fe,ue),lg(me)||le(null)},onCopyToAllComps:d?(fe,ue)=>{d(fe,ue),le(null)}:void 0})})]}),O&&h&&v&&e.jsx(Fs,{section:h,fieldName:v,displayLabel:N})]})]})}function kW(t){if(t.source!=="catalog"||!t.rowId)return null;const a=Pr(t.rowId);if(a&&a.length>0)return a;const s=mb.find(r=>r.rowId===t.rowId);if(s?.uad36Element){const r=Pr(s.uad36Element);if(r&&r.length>0)return r}return null}const dv={id:"unitRoomCounts",label:"Baths – Full | Half"},MS=[...CD.map(t=>
39t.id),dv.id],MW={PUDIndicator:"PUD",PropertyInProjectIndicator:"Property in a Project",PropertyEstateType:"Property Rights Appraised",BodyOfWaterType:"Body of Water",BodyOfWaterTypeOtherDescription:"Body of Water — Other",PrivateAccessIndicator:"Private Access",BodyOfWaterName:"Body of Water Name",WaterAccessDepthType:"Water Access Depth",WaterAccessDepthTypeOtherDescription:"Water Access Depth — Other",WaterFrontageTotalLengthLinearMeasure:"Water Frontage Length",WaterfrontFeatureType:"Waterfront Features",WaterfrontFeatureTypeOtherDescription:"Waterfront Features — Other",WaterfrontDevelopmentRightsIndicator:"Waterfront Development Rights",SwimmingPoolFeatureType:"Swimming Pool Features",SwimmingPoolFeatureTypeOtherDescription:"Swimming Pool Features — Other",BedroomCount:"Bedrooms",FullBathroomCount:"Baths - Full",HalfBathroomCount:"Baths - Half",NoFinancingTransactionIndicator:"Financing Type",ContractAmountUnknownIndicator:"Contract Amount Unknown",ContractDateUnknownIndicator:"Contract Date Unknown",SalesContractAmount:"Contract Price",SameBuilderAsSubjectIndicator:"Same Builder as Subject",HazardZoneType:"Hazard Zone",HeatingSystemType:"Heating",CoolingSystemType:"Cooling",SalesContractDate:"Contract Date",SaleToListPriceRatioPercent:"Sale to List Price Ratio",...Object.fromEntries(cd.map(t=>[zx(t),rg[t]]))},FW={PropertyInProjectIndicator:"Property in a project",ProjectLegalStructureType:"Project legal structure",ValuationAssignmentType:"assignment type",NewConstructionIndicator:"new construction",LandOwnedInCommonIndicator:"land owned in common",HazardZoneType:"hazard zone",PUDIndicator:"PUD",AssociationSpecialAssessmentStatusType:"special assessment status"};function n1(t){return t.replace(/\b[A-Za-z][A-Za-z0-9]*\b/g,s=>FW[s]??s).replace(/=\s*"true"/g,"= Yes").replace(/=\s*"false"/g,"= No")}const _W={general:[...PN,...zI,"PropertyEstateType"],generalInfo:[...DD],site:X0,siteInfo:X0,dwelling:kD,units:ag,water:OD,amenities:LD,energy:PD},UW=new Set(hd.find(t=>t.id==="general")?.fields??[]),VW=new Set(hd.find(t=>t.id==="site")?.fields??[]);function Ej(t){return t.group==="General Information"?Dh(t.rowId,t.group,"urar36")!=="generalInfo":t.rowId&&Ox.has(t.rowId)||t.rowId==="PropertyEstateType"?!1:t.label?.trim().toLowerCase()==="direction from subject"?!0:t.rowId?t.rowId==="ComparableToSubjectDirectionType"||UW.has(t.rowId)||og(t.rowId)==="General Information"||PN.includes(t.rowId)||zI.includes(t.rowId)||DD.includes(t.rowId):!1}function wj(t){return t.group==="Site"?!0:t.rowId?VW.has(t.rowId)||og(t.rowId)==="Site"||X0.includes(t.rowId):!1}const i1=new Set(["NoFinancingTransactionIndicator","ContractDateUnknownIndicator","MortgageType","MortgageTypeOtherDescription","HazardZoneType","HazardZoneTypeOtherDescription","HeatingSystemType","HeatingSystemTypeOtherDescription","HeatingFuelType","HeatingFuelTypeOtherDescription"]),$W=new Set(["catalog_financing_type","catalog_hazard_zone","catalog_heating_cooling"]),gM=new Set(["salePrice","salePricePerGLA","dateOfSale","yearBuilt","constructionMethod","design","attachedDetached","location","site","view","aboveGrade","gla","basement","qualityCondition","heatingCooling","garageCarport","porchPatioDeck"]);function BW(t){return gM.has(t)||/^basementUnit[2-4]$/.test(t)}function o1(t){const a=ok(t.fields?.salePrice?.value,{...t.fields?.finishedAboveGrade?{finishedAboveGrade:t.fields.finishedAboveGrade.value}:{},nonstandardFinishedAboveGrade:t.fields?.nonstandardFinishedAboveGrade?.value,gla:t.fields?.gla?.value});return a===null?"—":`$${a.toFixed(2)}`}const Pj=new Set(["dataSource","mlsNumber","proximity","listPrice","listingStatus","saleType","financing","concessions","financingConcessions","daysOnMarket","leaseholdFeeSimple","neighborhoodName"]);function Oj(t,a){if(!t&&!a)return!1;if(t&&$W.has(t)||t&&i1.has(t)||a&&i1.has(a))return!0;const s=t??"";return s.startsWith("wizard_qc_")||/^Dwelling\d+_Exterior(?:Quality|Condition)RatingCode$/.test(s)||/^Unit\d+_Interior(?:Quality|Condition)RatingCode$/.test(s)||/^Adu\d+_Interior(?:Quality|Condition)RatingCode$/.test(s)}const l1=new Set(["ExteriorQualityRatingCode","ExteriorConditionRatingCode"]);function FS({value:t,enumOptions:a,optionLabel:s,isSubject:r,isFirstComp:n,disabled:i,onCommit:l,testId:c,emptyPlaceholder:d="",source:p,userEdited:u,sourceTestId:m,inspectPill:h,valueClassName:f,resolvedDisplay:v=!1,readOnlyDisplay:S=!1,displaySuffix:N,required:x=!1}){const[y,b]=o.useState(t),[j,T]=o.useState(!v),O=o.useRef(!1);o.useEffect(()=>{b(t)},[t]);const E=c?.includes("catalog_BedroomCount_auto")||c?.includes("catalog_FullBathroomCount_auto")||c?.includes("catalog_HalfBathroomCount_auto"),R=Q("flex items-center justify-start gap-x-2 px-2 py-[5px] text-left",Gl({fieldName:c??"custom",isMissing:!Vh(t),isRequired:x||E}),r?"border-l border-slate-200":n?"border-l-2 border-l-slate-300":"border-l border-slate-200");if(S){const G=t.trim().length>0;return e.jsxs("div",{className:R,"data-testid":c,"aria-readonly":"true",children:[h,p&&e.jsx(Ji,{source:p,userEdited:u,testId:c?`source-dot-${c}`:void 0}),e.jsx("span",{"data-testid":c?`${c}-value`:void 0,className:Q("min-w-0 truncate","text-[11px] leading-4 text-slate-700",!G&&"placeholder-hint text-slate-400"),children:G?`${t}${N??""}`:d})]})}if(v&&!j){const G=t&&a?s?s(t):t:t||d;return e.jsxs("div",{className:Q(R,"min-w-0 cursor-pointer flex-wrap leading-tight transition-colors hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-inset"),role:"button",tabIndex:i?-1:0,"aria-label":`Edit ${c??"value"}`,onClick:U=>{U.target.closest('[data-testid^="datapoint-inspect-pill-"]')||i||T(!0)},onKeyDown:U=>{U.key!=="Enter"&&U.key!==" "||(U.preventDefault(),i||T(!0))},"data-testid":c,children:[h,p&&e.jsx(Ji,{source:p,userEdited:u,testId:c?`source-dot-${c}`:void 0}),e.jsx("span",{className:Q("min-w-0 flex-1 whitespace-normal break-words",Ou,!t&&"placeholder-hint"),children:G})]})}return a&&a.length>0?e.jsxs("div",{className:R,children:[h,p&&e.jsx(Ji,{source:p,userEdited:u,testId:c?`source-dot-${c}`:void 0}),e.jsxs("select",{value:t,disabled:i,onChange:G=>{l(G.target.value),v&&T(!1)},className:Q("h-[18px] w-full px-1 text-[11px] leading-4 border border-slate-200 rounded bg-white focus:outline-none focus:ring-1 focus:ring-blue-300 disabled:opacity-60",f),"data-testid":c,children:[e.jsx("option",{value:"",children:d}),a.map(G=>e.jsx("option",{value:G,children:s?s(G):G},G))]})]}):e.jsxs("div",{className:R,children:[h,p&&e.jsx(Ji,{source:p,userEdited:u,testId:c?`source-dot-${c}`:void 0}),e.jsx("input",{type:"text",value:y,disabled:i,onChange:G=>b(G.target.value),onBlur:()=>{if(O.current){O.current=!1,T(!1);return}y.trim()!==t&&l(y.trim()),v&&T(!1)},onKeyDown:G=>{G.key==="Enter"?(y.trim()!==t&&l(y.trim()),O.current=!0,v&&T(!1),G.target.blur()):G.key==="Escape"&&(b(t),O.current=!0,v&&T(!1),G.target.blur())},placeholder:d,className:Q("h-[18px] w-full px-1 py-0 text-[11px] leading-4 border border-transparent hover:border-slate-200 focus:border-slate-300 rounded bg-transparent focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-300 disabled:opacity-60",f),"data-testid":c})]})}function zW({value:t,unit:a,wrapperClass:s,source:r,userEdited:n,sourceTestId:i,inspectPill:l,onValueChange:c,onUnitChange:d,inputTestId:p,unitTestId:u}
39){const[m,h]=o.useState(!1),f=o.useRef(!1),v=YW(t),S=o.useRef(v),N=o.useRef(a);o.useEffect(()=>{f.current||(S.current=v,N.current=a)},[a,v]);const x=v?R$(v,a):"",y=()=>{const j=HW(S.current,N.current);return j?(d(j.unit),c(j.value),S.current=j.value,N.current=j.unit,!0):!1},b=j=>{const T=WW(S.current,N.current,j);if(T){d(j),c(T),S.current=T,N.current=j,f.current=!1;return}d(j),N.current=j,f.current=!1};return m?e.jsxs("div",{className:Q(s,"flex items-center justify-start gap-x-2 text-left"),onBlur:j=>{j.currentTarget.contains(j.relatedTarget)||h(!1)},children:[l,r&&e.jsx(Ji,{source:r,userEdited:n,testId:i??`source-dot-${p}`}),e.jsx(ze,{value:v,onChange:j=>{const T=GW(j.target.value);f.current=!0,S.current=T,c(T)},onBlur:()=>{f.current&&(y(),f.current=!1)},inputMode:"decimal",placeholder:"Site size",className:Q("h-6 min-w-0 flex-1 text-[12px] font-medium md:text-[12px] placeholder-hint"),"data-testid":p}),e.jsx("select",{value:a,onChange:j=>b(j.target.value),"aria-label":"Site size unit",className:"h-6 w-[58px] shrink-0 border-0 bg-transparent p-0 text-[12px] font-medium text-slate-500 placeholder-hint","data-testid":u,children:qW.map(j=>e.jsx("option",{value:j,children:Hs("@AreaUnitOfMeasureType",j)},j))})]}):e.jsxs("div",{className:Q(s,"min-w-0 cursor-pointer flex-wrap gap-x-2 gap-y-0.5 text-left leading-tight transition-colors hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-inset"),role:"button",tabIndex:0,"aria-label":"Edit Site Size",onClick:()=>h(!0),onKeyDown:j=>{j.key!=="Enter"&&j.key!==" "||(j.preventDefault(),h(!0))},"data-testid":p,children:[l,r&&e.jsx(Ji,{source:r,userEdited:n,testId:i??`source-dot-${p}`}),e.jsx("span",{className:Q("min-w-0 flex-1 whitespace-normal break-words",Ou,(r||l)&&"ml-2",!x&&"placeholder-hint"),children:x})]})}const qW=["Acres","Hectares","SquareFeet","SquareMeters"];function YW(t){const a=String(t??"").replace(/,/g,"").trim();if(!a)return"";const s=a.match(/^(\d*)(?:\.(\d*))?$/);if(!s)return a;const n=(s[1]||"0").replace(/^0+(?=\d)/,"").replace(/\B(?=(\d{3})+(?!\d))/g,",");return s[2]!==void 0?`${n}.${s[2]}`:n}function GW(t){return t.replace(/,/g,"").replace(/[^\d.]/g,"").replace(/(\..*)\./g,"$1")}function HW(t,a){const s=Number(t.replace(/,/g,"").trim());if(!Number.isFinite(s)||s<1)return null;const r=a==="Acres"?{factor:43560,unit:"SquareFeet"}:a==="Hectares"?{factor:1e4,unit:"SquareMeters"}:a==="SquareFeet"&&s>=43560?{factor:1/43560,unit:"Acres"}:a==="SquareMeters"&&s>=1e4?{factor:1/1e4,unit:"Hectares"}:null;if(!r)return null;const n=s*r.factor,i=Math.round(n*100)/100;return{value:String(i),unit:r.unit}}function WW(t,a,s){if(a===s)return null;const r=Number(t.replace(/,/g,"").trim());if(!Number.isFinite(r))return null;const n={SquareFeet:1,Acres:43560,SquareMeters:1,Hectares:1e4},i=n[a],l=n[s];if(i==null||l==null||!((a==="SquareFeet"||a==="Acres")&&(s==="SquareFeet"||s==="Acres"))&&!((a==="SquareMeters"||a==="Hectares")&&(s==="SquareMeters"||s==="Hectares")))return null;const p=r*i/l;return String(Math.round(p*100)/100)}function qp(t){if(t&&typeof t=="object"&&"value"in t)return t;if(typeof t=="string"||typeof t=="number")return{value:t,source:"User",hasConflict:!1,isVerified:!1,userEdited:!0}}const Yo={salePrice:"OwnershipTransferTransactionAmount",saleType:"SaleType",dateOfSale:"OwnershipTransferDate"},KW={dataSource:"Data Source",proximity:"Proximity to Subject",listingStatus:"Listing Status",listPrice:"List Price",daysOnMarket:"DOM",salePrice:"Sale Price",saleType:"Transfer Terms",dateOfSale:"Sale Date",attachedDetached:"Attached/Detached",SalesContractAmount:"Contract Price",SalesContractDate:"Contract Date",TotalSalesConcessionAmount:"Sales Concessions"};function Tx(t){return KW[t]??t}const Ox=new Set(["ContractPrice","NoFinancingTransactionIndicator","ContractAmountUnknownIndicator","ContractDateUnknownIndicator","MortgageType","SalesContractAmount","SalesContractDate","TotalSalesConcessionAmount"]),QW=!1;function Lx(t,a){const s=Yo[a];if(!s)return;const r=t.isSubject?t.fields?.[s]:t.transferHistory?.[0]?.[s]??t.fields?.[s],n=qp(r);if(!n||n.value==null)return n;const i=String(n.source??"").toLowerCase();return i==="mls"?{...n,mlsValue:n.value}:i==="publicrecord"||i==="pr"?{...n,prValue:n.value}:i==="ai"?{...n,aiValue:n.value}:i==="user"?{...n,userValue:n.value}:n}function j0(t){const a=t.isSubject?t.fields?.OwnershipTransferTransactionType:t.transferHistory?.[0]?.OwnershipTransferTransactionType??t.fields?.OwnershipTransferTransactionType;return String(qp(a)?.value??a??"")}const ZW=[{value:"Active",label:"Active"},{value:"OffMarket",label:"Off Market"},{value:"Pending",label:"Pending"},{value:"SettledSale",label:"Settled Sale"}],JW=new Set(["undefined","null","nan"]),_m=t=>t==null||t===""||typeof t=="number"&&Number.isNaN(t)||typeof t=="string"&&JW.has(t.trim().toLowerCase())?null:t,sI=t=>{const a=["listingStatus","listPrice","daysOnMarket"].map(r=>t[r]).filter(r=>_m(r?.value)!=null).map(r=>r?.source).filter(r=>!!r);if(a.includes("User"))return"User";if(a.length>0)return a[0];const s=["listingStatus","listPrice","daysOnMarket"].map(r=>t[r]?.source).filter(r=>!!r);return s.includes("User")?"User":s[0]??null};
39function c1({property:t,isFirstComp:a=!1,stickyLeft:s,onFieldUpdate:r,onSetPreference:n,onCopyToAllComps:i,preferredSource:l,gridMode:c,uad36:d,comparableSequence:p,subjectCanonicalFields:u}){const m=["listingStatus","listPrice","daysOnMarket"],{inspecting:h}=fc(),f=Object.fromEntries(m.map(U=>[U,t.isSubject&&u?u[U]:t.fields?.[U]])),v=t.isSubject?NN(u?u.ListedWithinPreviousYearIndicator?.value:t.fields?.ListedWithinPreviousYearIndicator?.value):"values",S=v==="blank"?[]:m.flatMap(U=>{const C=_m(f[U]?.value);return C==null?[]:[{key:U,value:Yh(C,U,c,d)}]}),N=v==="values",x=N&&m.some(U=>_m(f[U]?.value)==null),y=N&&m.every(U=>{const C=f[U];return _m(C?.value)!=null&&!!C?.isVerified}),b=m.some(U=>!!f[U]?.hasConflict),j=v==="dash"?Kx("listingStatus","subject"):void 0,T=(U,C,F)=>r(t.id,U,C,F),O=sI(f),E=m.some(U=>_m(f[U]?.value)!=null),R=e.jsxs("button",{type:"button",className:Q("flex h-full w-full min-w-0 flex-wrap items-center justify-start gap-x-1 gap-y-0.5 rounded px-0 py-0.5 text-left leading-tight hover:bg-slate-50",Ou),title:j,"data-testid":`cell-${t.id}-listingDetails`,children:[v==="values"&&E&&O&&e.jsx("span",{className:Q("inline-block h-1.5 w-1.5 shrink-0 rounded-full",O==="MLS"?"bg-sky-500":O==="PublicRecord"?"bg-amber-500":O==="AI"?"bg-emerald-500":O==="User"?"bg-violet-500":"bg-slate-400"),"aria-label":`Source: ${O}`,"data-testid":`source-dot-${t.id}-listingDetails`}),S.map(({key:U,value:C},F)=>e.jsxs(Mn.Fragment,{children:[F>0&&e.jsx("span",{className:"text-slate-700",children:"|"}),e.jsx("span",{className:"inline-flex min-w-0 items-center gap-1",children:e.jsx("span",{className:"min-w-0 whitespace-normal break-words",children:C})})]},U)),v==="dash"&&e.jsx(kn,{state:"em-dash",title:j})]}),G=Object.fromEntries(m.map(U=>[U,f[U]]));return e.jsxs("div",{className:Q("flex h-full min-h-8 items-center gap-1.5 px-3 py-[5px]",s&&"sticky z-[2]",t.isSubject?"border-l border-slate-200":a?"border-l-2 border-l-slate-300":"border-l border-slate-200",tI({isVerified:y,isMissing:x,isRequired:N,hasHighlightedConflict:b}),v==="blank"&&"bg-slate-100"),style:s?{left:s}:void 0,"data-testid":`cell-${t.id}-listingDetails-container`,children:[h&&m.map(U=>e.jsx(Fs,{section:t.isSubject?"subjectProperty":"salesComparison",fieldName:t.isSubject?Pm[U]:Zi(t.id,`fields.${Pm[U]}`),displayLabel:U==="listingStatus"?"Status":U==="listPrice"?"Price":"DOM"},U)),e.jsx(fM,{fieldName:`${t.id}-listPrice`,fieldData:f.listPrice??{value:null,source:"User",hasConflict:!1,isVerified:!1},compactListingFields:G,onSelectCompactListing:T,onCopyCompactListing:(U,C)=>i?.(U,C,"User"),comparableSequence:p,entityLabel:t.isSubject?"Subject":p!=null?`Comp ${p}`:void 0,onSetPreference:n,preferredSource:l,onSelect:(U,C)=>T("listPrice",U,C),uad36:d,gridMode:c,children:R})]})}function XW({property:t,sequence:a,onUpdate:s}){const[r,n]=o.useState(!1),i=t.fields?.dataSource,l=Array.isArray(i?.dataSources)?i.dataSources??[]:[],[c,d]=o.useState([]),p=c.some(v=>v.type==="MLS"&&!v.identifier?.trim()),u=c.length>31,m=()=>{n(!1),d([])},h=()=>{p||u||(s(JSON.stringify(c),"User"),n(!1))},f=Yh(i?.value,"dataSource","1004",!0,{});return e.jsxs(xi,{open:r,onOpenChange:v=>{n(v),d(v?l.map(S=>({...S})):[])},children:[e.jsx(w2,{asChild:!0,children:e.jsx("button",{type:"button",className:"w-full min-h-8 px-3 py-[5px] text-left text-[12px] text-slate-700 hover:bg-blue-50/60","data-testid":`cell-${t.id}-dataSource`,children:f||e.jsx("span",{className:"text-slate-300 italic",children:"Click to add source"})})}),e.jsxs(bi,{className:"max-w-2xl gap-0 overflow-hidden border-slate-200 bg-white p-0 shadow-xl",overlayClassName:"bg-black/50","data-testid":`editor-${t.id}-dataSource`,children:[e.jsxs($i,{className:"border-b border-slate-200 px-3 py-3 text-left",children:[e.jsxs(si,{className:"text-sm font-semibold text-slate-800",children:["Comp ",a," Data Source"]}),e.jsx(pl,{className:"text-[11px] text-slate-500",children:"Add or edit structured source and identifier pairs for this comparable."})]}),e.jsxs("div",{className:"max-h-[60vh] overflow-y-auto bg-white",children:[c.map((v,S)=>e.jsxs("div",{className:"flex items-end gap-2 border-b border-slate-200 px-3 py-2",children:[e.jsx("span",{className:"w-4 shrink-0 pb-2 text-[10px] font-semibold tabular-nums text-slate-500",children:S+1}),e.jsxs("label",{className:"min-w-0 flex-1 space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"Data source type"}
39),e.jsx("select",{value:v.type,onChange:N=>{const x=c.map((y,b)=>b===S?{...y,type:N.target.value}:y);d(x)},className:"h-8 w-full rounded-md border border-slate-200 bg-white px-2 text-[11px]","aria-label":`Data Source Type ${S+1}`,children:nV.map(N=>e.jsx("option",{value:N,children:N},N))})]}),e.jsxs("label",{className:"min-w-0 flex-1 space-y-0.5",children:[e.jsx("span",{className:"block text-[9px] font-medium uppercase tracking-[0.04em] text-slate-500",children:"Identifier"}),e.jsx("input",{value:v.identifier??"",maxLength:45,onChange:N=>{const x=c.map((y,b)=>b===S?{...y,identifier:N.target.value.slice(0,45)}:y);d(x)},className:"h-8 w-full rounded-md border border-slate-200 bg-white px-2 text-[11px]",placeholder:v.type==="MLS"?"Required":"Optional","aria-label":`Data Source Identifier ${S+1}`})]}),e.jsx("button",{type:"button",className:"mb-1 h-6 w-6 shrink-0 rounded-sm text-slate-400 hover:bg-rose-50 hover:text-rose-600","aria-label":`Remove ${v.type} data source`,onClick:()=>d(c.filter((N,x)=>x!==S)),children:e.jsx(ur,{className:"h-3.5 w-3.5"})})]},`${v.id}-${S}`)),e.jsxs("div",{className:"px-3 py-2",children:[e.jsxs(De,{type:"button",variant:"outline",size:"sm",onClick:()=>d(v=>[...v,{id:`source_new_${Date.now()}_${v.length}`,type:"MLS",source:"user",userEdited:!0}]),className:"h-8 w-full justify-center rounded-md border-dashed border-slate-400 bg-white text-[11px] font-medium text-slate-700 hover:bg-slate-50",children:[e.jsx(un,{className:"mr-2 h-3.5 w-3.5"})," Add data source"]}),u&&e.jsx("p",{className:"mt-1 text-[10px] text-rose-600",role:"alert",children:"A report can contain no more than 31 data sources."})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-slate-200 bg-slate-50 px-3 py-2",children:[e.jsx(De,{type:"button",variant:"ghost",size:"sm",className:"h-8 text-[11px]",onClick:m,children:"Cancel"}),e.jsx(De,{type:"button",size:"sm",className:"h-8 text-[11px]",disabled:p||u,onClick:h,children:"Save"})]})]})]})}function jh({property:t,fieldName:a,isFirstComp:s,onUpdate:r,onCopyToAllComps:n,onCopyCompanionToAllComps:i,onSetPreference:l,preferredSource:c,gridMode:d="1004",activeScenario:p,siteDisplayUnits:u,showMissing:m,highlightConflicts:h,onFieldUpdate:f,uad36:v,inspectSection:S,inspectFieldName:N,inspectLabel:x,comparableSequence:y,fieldDataOverride:b,displayDash:j,testIdOverride:T,editableText:O=!1}){const{inspecting:E}=fc(),R=v&&!t.isSubject&&a==="dataSource"?Zi(t.id,"fields.DataSources"):N,G=E&&(S||R)&&R?e.jsx(Fs,{section:S??"salesComparison",fieldName:R,displayLabel:x}
39):null,[U,C]=o.useState(null),[F,A]=o.useState(""),[M,B]=o.useState(!1),oe=t.fields??{},ae=a==="attachedDetached",D=b??oe[a]??(!t.isSubject&&v&&ae?{value:null,source:"User",hasConflict:!1,isVerified:!1}:O?{value:null,source:"User",hasConflict:!1,isVerified:!1}:void 0),_=v&&a==="salePrice"?"SalePrice":v&&a==="saleType"?"SaleType":null,$=t.isSubject?t.fields:t.transferHistory?.[0]??t.fields,z=_?DN(_,{role:t.isSubject?"subject":"comparable",get:Me=>{const lt=$[Me];return lt&&typeof lt=="object"&&"value"in lt?lt.value:lt}}):null,V=Ov(a),le=V!==null,W=j?Kx(a,t.isSubject?"subject":"comp"):void 0,me=o.useMemo(()=>{const Me={};for(const[lt,Tt]of Object.entries(oe))(lt.endsWith("OtherDescription")||ZD(lt))&&Tt?.value!=null&&Tt.value!==""&&(Me[lt]=String(Tt.value));return Me},[oe]),Z=f?(Me,lt,Tt="User")=>f(t.id,Me,lt,Tt):void 0,pe=j?!1:wm(t,a,v);if(z&&(z.state==="gray"||z.state==="em-dash"))return e.jsxs("div",{className:Q("h-full min-h-8 self-stretch px-3 py-[5px] flex items-center justify-start gap-2 text-left",t.isSubject?"border-l border-slate-200 bg-slate-100":s?"border-l-2 border-l-slate-300":"border-l border-slate-200"),"data-testid":T??`cell-${t.id}-${a}`,"aria-disabled":"true",children:[G,e.jsx(kn,{state:z.state})]});const se=a==="netAdjustment"||a==="grossAdjustment"||a==="adjustedSalePrice",fe=String(D?.value??"").trim(),be=(a==="attachedDetached"?dC(D?.value)!=="":D?.value!==null&&D?.value!==void 0&&fe!==""&&fe!=="-"&&fe!=="–"&&fe!=="—")?{MLS:"bg-sky-500",PublicRecord:"bg-amber-500",AI:"bg-emerald-500",User:"bg-violet-500",Airbnb:"bg-rose-500"}[D?.source??""]:void 0,H=be&&!se?e.jsx("span",{className:Q("inline-block h-1.5 w-1.5 shrink-0 rounded-full",be),"aria-label":`Source: ${D?.source}`,"data-testid":`source-dot-${t.id}-${a}`}):null,ye=p==="after-repaired",de=Gl({fieldName:a,isMissing:pe,semanticState:j?"em-dash":void 0}),ge=ye?Q("h-full min-h-8 self-stretch px-3 py-[5px] border-l border-amber-200 flex items-center justify-start gap-2 text-left group/subject",de):Q("h-full min-h-8 self-stretch px-3 py-[5px] border-l border-slate-200 flex items-center justify-start gap-2 text-left group/subject",de),Be=t.isSubject&&v&&Qp.has(a)?Q(ge,tI({isVerified:!!D?.isVerified,isMissing:pe,isRequired:dg.has(a),hasHighlightedConflict:!!D?.hasConflict})):ge,He=ye?"px-2 py-0.5 rounded text-[11px] text-amber-400 italic transition-colors flex items-center gap-1.5 cursor-pointer hover:bg-amber-100/40":"px-2 py-0.5 rounded text-[11px] text-blue-400 italic transition-colors flex items-center gap-1.5 cursor-pointer hover:bg-blue-100/50",Ie=ye?"w-3 h-3 text-amber-400 opacity-0 group-hover/subject:opacity-100 transition-opacity":"w-3 h-3 text-blue-400 opacity-0 group-hover/subject:opacity-100 transition-opacity",ce=ye?"w-full h-6 px-2 text-xs border border-amber-300/80 rounded bg-white focus:outline-none focus:ring-1 focus:ring-amber-300":"w-full h-6 px-2 text-xs border border-blue-300/80 rounded bg-white focus:outline-none focus:ring-1 focus:ring-blue-300",Pe=Me=>Q("px-0 py-0.5 rounded transition-colors flex items-center justify-start gap-1.5 cursor-pointer",ae&&"w-full min-w-0",Ou,Me?"bg-amber-100/80 text-amber-800 ring-1 ring-amber-200/80 hover:bg-amber-100":ye?"text-slate-800 hover:bg-amber-50/50":"text-slate-800 hover:bg-slate-50"),We=t.isSubject&&v&&Qp.has(a)?NN(t.fields?.ListedWithinPreviousYearIndicator?.value):null;if(We==="dash"||We==="blank")return e.jsxs("div",{className:Be,"data-testid":`cell-subject-${a}`,children:[G,We==="dash"&&e.jsx(kn,{state:"em-dash",title:Kx("listingStatus","subject")})]});if(t.isSubject&&v&&a==="listingStatus"){const Me=D?.value===null||D?.value===void 0?"":String(D.value);return e.jsxs("div",{className:Be,children:[G,H,e.jsx(rI,{value:Me,onChange:lt=>{lt&&r(lt,"User")},ariaLabel:"Subject listing status value",testId:"cell-subject-listingStatus",includeSettledSale:!1,blendWithCellSurface:!0}),D?.hasConflict&&e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-amber-400"})]})}if(v&&a==="dataSource")return t.isSubject?e.jsx("div",{className:"h-full min-h-8 self-stretch border-l border-slate-200 bg-slate-100 px-3 py-[5px] text-[11px] text-slate-500","data-testid":"cell-subject-dataSource-disabled",children:G}):e.jsxs("div",{className:"h-full min-h-8 self-stretch border-l border-slate-200 bg-white",children:[G,e.jsx(XW,{property:t,sequence:y??1,onUpdate:r})]});
39if(!D){if(j)return e.jsxs("div",{className:Q("h-full min-h-8 self-stretch px-3 py-[5px] flex items-center",t.isSubject?"border-l border-slate-200":s?"border-l-2 border-l-slate-300":"border-l border-slate-200",Gl({fieldName:a,isMissing:!1,semanticState:"em-dash"})),title:W,"data-testid":T??`cell-${t.id}-${a}-dash`,children:[G,e.jsx(kn,{state:"em-dash"})]});if(t.isSubject&&!se){if(le)return e.jsxs("div",{className:ge,children:[G,e.jsxs(xn,{open:M,onOpenChange:B,children:[e.jsx(bn,{asChild:!0,children:e.jsx("button",{className:Q(He,ae&&"w-full min-w-0 justify-between"),"data-testid":`cell-subject-${a}`,"aria-label":`Set ${a}`,children:e.jsx(Rr,{className:Ie})})}),e.jsx(yn,{align:"start",className:"w-72 p-2",sideOffset:4,children:e.jsx($h,{fieldType:V,currentValue:null,onSelect:(lt,Tt)=>{r(lt,Tt),lg(V)||B(!1)},uad36:v,subjectMode:!0,otherDescriptions:me,onOtherDescriptionChange:Z})})]})]});const Me=U===a;return e.jsx("div",{className:ge,children:Me?e.jsx("input",{autoFocus:!0,type:"text",value:F,onChange:lt=>A(lt.target.value),onBlur:()=>{if(F.trim()){const lt=Number(F),Tt=isNaN(lt)?F.trim():lt;r(Tt,"User")}C(null)},onKeyDown:lt=>{if(lt.key==="Enter"){if(F.trim()){const Tt=Number(F),je=isNaN(Tt)?F.trim():Tt;r(je,"User")}C(null)}else lt.key==="Escape"&&C(null)},className:ce,"data-testid":`input-subject-${a}`}):e.jsx("button",{onClick:()=>{C(a),A("")},className:He,"data-testid":`cell-subject-${a}`,"aria-label":`Set ${a}`})})}return/^basementUnit\d+$/.test(a)&&le?e.jsx("div",{className:Q("h-full min-h-8 self-stretch px-3 py-[5px] flex items-center gap-2",s?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:e.jsxs(xn,{open:M,onOpenChange:B,children:[e.jsx(bn,{asChild:!0,children:e.jsx("button",{className:"px-2 py-0.5 rounded text-[11px] text-slate-400 italic transition-colors flex items-center gap-1.5 cursor-pointer hover:bg-slate-100/80","data-testid":`cell-${t.id}-${a}`,"aria-label":`Set ${a}`,children:e.jsx(Rr,{className:"w-3 h-3 text-slate-400 shrink-0"})})}),e.jsx(yn,{align:"start",className:"w-72 p-2",sideOffset:4,children:e.jsx($h,{fieldType:V,currentValue:null,onSelect:(Me,lt)=>{r(Me,lt),lg(V)||B(!1)},onCopyToAllComps:n?(Me,lt)=>{n(Me,lt),B(!1)}:void 0,onCopyCompanionToAllComps:i,uad36:v,otherDescriptions:me,onOtherDescriptionChange:Z})})]})}):e.jsx("div",{className:Q("h-full min-h-8 self-stretch px-3 py-[5px] flex items-center gap-1.5",t.isSubject?"border-l border-slate-200":s?"border-l-2 border-l-slate-300":"border-l border-slate-200",Gl({fieldName:a,isMissing:!0})),children:G})}const Re=(()=>{if(z)return z.text;if(v&&pe&&Qp.has(a))return tK(a,{gridMode:d,uad36:v,isSubject:t.isSubject,subjectListedWithinPreviousYear:t.fields?.ListedWithinPreviousYearIndicator?.value});if(a==="site"&&u&&D&&D.source!=="User"){const Me=u==="auto"?D.autoSiteUnits||"sf":u,lt=D.lotSizeSf,Tt=D.lotSizeAcres;if(Me==="ac"){const je=Tt??(lt!=null?lt/43560:null);if(je!=null)return sb(je,"acres")}if(Me==="sf"){const je=lt??(Tt!=null?Math.round(Tt*43560):null);if(je!=null)return sb(je,"sqft")}}if(a==="RenewableEnergyComponentType"){const Me=Lv(D.value);if(Me.includes("None"))return"None";if(Me.length===0)return"";const lt=me?.RenewableEnergyComponentTypeOtherDescription??"",Tt=lt?lt.split("|").map(Le=>Le.trim()).filter(Boolean):[];return Me.flatMap(Le=>Le==="Other"?Tt.length>0?Tt:["Other"]:[Le==="WindTurbine"?"Wind Turbine":Le]).join(" | ")}if(a==="GreenCertificationName"){const Me=String(D.value??"").split("|").map(Tt=>Tt.trim()).filter(Boolean);if(Me.length===0)return"";const lt=String(me?.GreenCertificationLevelName??"").split("|").map(Tt=>Tt.trim());return Me.map((Tt,je)=>lt[je]?`${Tt} | ${lt[je]}`:Tt).join(", ")}if(a==="EfficiencyRatingName"){const Me=String(D.value??"").split("|").map(Tt=>Tt.trim()).filter(Boolean);if(Me.length===0)return"";const lt=String(me?.EfficiencyRatingScoreValue??"").split("|").map(Tt=>Tt.trim());return Me.map((Tt,je)=>lt[je]?`${Tt} | ${lt[je]}`:Tt).join(", ")}return IW(a,Yh(D.value,a,d,v,me),t.fields??{},v)})(),ne=j?e.jsx(kn,{state:"em-dash",title:W}):Re;if(t.isSubject&&!O){if(p==="after-repaired"){if(le)return e.jsxs("div",{className:ge,children:[G,H,e.jsxs(xn,{open:M,onOpenChange:B,children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{className:Q("px-0 py-0.5 rounded text-xs font-medium transition-colors flex items-center justify-start gap-1.5 cursor-pointer",ae&&"w-full min-w-0",D.hasConflict?"bg-amber-100/80 text-amber-800 ring-1 ring-amber-200/80 hover:bg-amber-100":"text-slate-800 hover:bg-amber-50/50"),"data-testid":`cell-subject-${a}`,children:[ne,e.jsx(Rr,{className:"w-3 h-3 text-amber-400 opacity-0 group-hover/subject:opacity-100 transition-opacity"})]})}),e.jsx(yn,{align:"start",className:"w-72 p-2",sideOffset:4,children:e.jsx($h,{fieldType:V,currentValue:D.value,onSelect:(Le,ut)=>{r(Le,ut),lg(V)||B(!1)},uad36:v,subjectMode:!0,otherDescriptions:me,onOtherDescriptionChange:Z})})]}),D.hasConflict&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"})]});const je=U===a;return e.jsxs("div",{className:ge,children:[H,je?e.jsx("input",{autoFocus:!0,t
39ype:"text",value:F,onChange:Le=>A(Le.target.value),onBlur:()=>{if(F.trim()){const Le=Number(F),ut=isNaN(Le)?F.trim():Le;r(ut,"User")}C(null)},onKeyDown:Le=>{if(Le.key==="Enter"){if(F.trim()){const ut=Number(F),st=isNaN(ut)?F.trim():ut;r(st,"User")}C(null)}else Le.key==="Escape"&&C(null)},className:"w-full h-6 px-2 text-xs border border-amber-300/80 rounded bg-white focus:outline-none focus:ring-1 focus:ring-amber-300","data-testid":`input-subject-${a}`}):e.jsx("button",{onClick:()=>{C(a),A(D.value!=null?String(D.value):"")},className:Q("px-0 py-0.5 rounded transition-colors flex items-center justify-start gap-1.5 cursor-pointer",Ou,D.hasConflict?"bg-amber-100/80 text-amber-800 ring-1 ring-amber-200/80 hover:bg-amber-100":"text-slate-800 hover:bg-amber-50/50"),"data-testid":`cell-subject-${a}`,children:ne}),D.hasConflict&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"})]})}const Me=a==="location"&&t.elsScore!=null&&t.elsScore>=0?e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("span",{className:Q("inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-bold leading-none shrink-0",t.elsScore>=67?"bg-emerald-100 text-emerald-700":t.elsScore>=34?"bg-slate-100 text-slate-600":"bg-red-100 text-red-700"),"data-testid":`els-badge-${t.id}`,children:["L:",t.elsScore]})}),e.jsxs(Wa,{side:"top",className:"text-xs bg-white text-slate-800 border border-slate-200 shadow-md max-w-[220px]",children:[e.jsxs("p",{className:"font-semibold mb-1",children:["Echo Location Score: ",t.elsScore,"/100"]}),t.elsFactors&&t.elsFactors.length>0&&e.jsx("div",{className:"space-y-0.5",children:t.elsFactors.map((je,Le)=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-slate-600",children:je.name}),e.jsx("span",{className:je.subscore>=80?"text-emerald-600 font-medium":je.subscore>=50?"text-slate-500 font-medium":"text-red-600 font-medium",children:je.subscore})]},Le))})]})]})}):null,lt=h&&D.hasConflict?e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"}):null;if(se)return e.jsxs("div",{className:Q("h-full min-h-8 self-stretch px-3 py-[5px] border-l border-slate-200 flex items-center gap-2",Gl({fieldName:a,isMissing:pe,semanticState:j?"em-dash":void 0})),children:[e.jsx("span",{className:Q("px-0 py-0.5 rounded text-[12px] font-semibold text-left",D.hasConflict?"bg-amber-100/80 text-amber-800 ring-1 ring-amber-200/80":"text-slate-800"),children:ne}),lt]});if(le)return e.jsxs("div",{className:ge,children:[G,H,e.jsxs(xn,{open:M,onOpenChange:B,children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{className:Pe(!!D.hasConflict),"data-testid":`cell-subject-${a}`,children:[ne,e.jsx(Rr,{className:Ie})]})}),e.jsx(yn,{align:"start",className:"w-72 p-2",sideOffset:4,children:e.jsx($h,{fieldType:V,currentValue:D.value,onSelect:(je,Le)=>{r(je,Le),lg(V)||B(!1)},uad36:v,subjectMode:!0,otherDescriptions:me,onOtherDescriptionChange:Z})})]}),Me,lt]});const Tt=U===a;return e.jsxs("div",{className:ge,children:[H,Tt?e.jsx("input",{autoFocus:!0,t
39ype:"text",value:F,onChange:je=>A(je.target.value),onBlur:()=>{if(F.trim()){const je=Number(F),Le=isNaN(je)?F.trim():je;r(Le,"User")}C(null)},onKeyDown:je=>{if(je.key==="Enter"){if(F.trim()){const Le=Number(F),ut=isNaN(Le)?F.trim():Le;r(ut,"User")}C(null)}else je.key==="Escape"&&C(null)},className:ce,"data-testid":`input-subject-${a}`}):e.jsx("button",{onClick:()=>{C(a),A(D.value!=null?String(D.value):"")},className:Pe(!!D.hasConflict),"data-testid":T??`cell-subject-${a}`,children:Re}),Me,lt]})}return e.jsxs("div",{title:W,className:Q("h-full min-h-8 self-stretch px-3 py-[5px] flex items-center justify-start gap-2 text-left",tI({isVerified:!!D.isVerified,isMissing:pe,isRequired:dg.has(a),hasHighlightedConflict:!!h&&!!D.hasConflict}),s?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:[G,b&&!t.isSubject&&e.jsx("span",{className:"h-2 w-2 shrink-0","data-testid":`source-slot-${t.id}-${a}`,"aria-hidden":"true"}),H,e.jsx("div",{className:ae?"min-w-0 flex-1":void 0,"data-testid":ae?`value-track-${t.id}-${a}`:void 0,children:e.jsx(fM,{fieldName:`${t.id}-${a}`,editableText:O,fieldData:D,onSelect:r,onCopyToAllComps:n,onCopyCompanionToAllComps:i,comparableSequence:y,entityLabel:t.isSubject?"Subject":y!=null?`Comp ${y}`:void 0,onSetPreference:l,preferredSource:c,otherDescriptions:me,onOtherDescriptionChange:Z,uad36:v,gridMode:d,basementHint:a==="basement"||/^basementUnit\d+$/.test(a)?D.basementHint??void 0:void 0,children:e.jsxs("button",{className:Q("px-0 py-0.5 rounded transition-all duration-100 group flex items-center justify-start gap-1.5 text-left",O&&"min-h-6 min-w-0 w-full",ae&&"w-full min-w-0",Ou,h&&D.hasConflict?"bg-amber-50/80 text-amber-800 ring-1 ring-amber-200/80 hover:bg-amber-100/80 hover:ring-amber-300":"text-slate-800 hover:bg-slate-100/80 hover:ring-1 hover:ring-slate-200",a==="netAdjustment"&&typeof D.value=="number"&&D.value>0&&"text-emerald-700",a==="netAdjustment"&&typeof D.value=="number"&&D.value<0&&"text-red-700",a==="adjustedSalePrice"&&typeof D.value=="number"&&"text-slate-900 font-bold text-[13px]",b&&"flex-1 justify-start tabular-nums"),"data-testid":T??`cell-${t.id}-${a}`,"aria-label":O?`Edit ${t.isSubject?"Subject":`Comp ${y??""}`} Neighborhood Name`:void 0,children:[ne,D.displaySuffix&&e.jsx("span",{className:"text-slate-400 text-[10px] ml-1 font-normal",children:D.displaySuffix}),le&&a!=="listingStatus"&&a!=="attachedDetached"&&e.jsx(Rr,{className:"h-3 w-3 shrink-0 text-slate-400 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100"})]})})}),a==="location"&&t.elsScore!=null&&t.elsScore>=0&&e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("span",{className:Q("inline-flex items-center px-1.5 py-0.5 rounded text-[9px] font-bold leading-none shrink-0",t.elsScore>=67?"bg-emerald-100 text-emerald-700":t.elsScore>=34?"bg-slate-100 text-slate-600":"bg-red-100 text-red-700"),"data-testid":`els-badge-${t.id}`,children:["L:",t.elsScore]})}),e.jsxs(Wa,{side:"top",className:"text-xs bg-white text-slate-800 border border-slate-200 shadow-md max-w-[220px]",children:[e.jsxs("p",{className:"font-semibold mb-1",children:["Echo Location Score: ",t.elsScore,"/100"]}),t.elsFactors&&t.elsFactors.length>0&&e.jsx("div",{className:"space-y-0.5",children:t.elsFactors.map((Me,lt)=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-slate-600",children:Me.name}),e.jsx("span",{className:Me.subscore>=80?"text-emerald-600 font-medium":Me.subscore>=50?"text-slate-500 font-medium":"text-red-600 font-medium",children:Me.subscore})]},lt))})]})]})})]})}function Ph({propertyId:t,fieldName:a,adjustment:s,hasExplicitValue:r,onAdjustmentChange:n,suggestion:i,salePrice:l,isSacred:c,isPulsing:d,isJustFilled:p,onResetSacred:u,chipDerivations:m,prereqsMet:h=!0,compact:f=!1}){const v=(A,M)=>A===0?M?"0":"":Math.round(A).toLocaleString("en-US"),S=(A,M)=>A===0?M?"0":"":String(Math.round(A)),[N,x]=o.useState(v(s,r)),[y,b]=o.useState(!1),[j,T]=o.useState(null);o.useEffect(()=>{x(y?S(s,r):v(s,r)),T(null)},[s,r]);const O=()=>{b(!0),x(S(s,r))},E=()=>{b(!1),T(null);const A=N.trim();if(A===""){n(t,a,null),x(v(0,!1));return}const M=A.match(/^([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*%$/);if(M&&l&&l>
390){const oe=parseFloat(M[1]),ae=Math.round(oe/100*l);x(v(ae,!0)),n(t,a,ae);return}const B=parseFloat(A.replace(/[^0-9.-]/g,""));if(!isNaN(B)){const oe=Math.round(B);x(v(oe,!0)),n(t,a,oe)}},R=A=>{const M=A.target.value;x(M);const B=M.trim().match(/^([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*%$/);if(B&&l&&l>0){const oe=parseFloat(B[1]),ae=Math.round(oe/100*l);T(`= $${Math.abs(ae).toLocaleString()}${ae<0?" (neg)":""}`)}else T(null)},G=s!==0||!!r,U=i&&i.amount!==0,C=i?Math.abs(i.rangeHigh-i.rangeLow):0,F=!G&&!U&&!h;return e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("div",{className:Q("w-[60px] min-w-[60px] h-full self-stretch flex flex-col items-start justify-start gap-0.5 relative bg-slate-100",f?"h-full px-1 py-0":"px-1.5 py-[5px]",d&&"animate-cascade-flash",p&&"ring-2 ring-sky-400 ring-offset-1 bg-sky-50/60"),"data-just-filled":p?"true":void 0,children:[e.jsx("input",{type:"text",value:N,onChange:R,onFocus:O,onBlur:E,onKeyDown:A=>{A.key==="Enter"&&A.target.blur()},placeholder:U?`${i.amount>0?"+":""}${Math.round(i.amount/100)*100}`:"$0",className:Q("text-left border rounded transition-colors",f?"w-11 h-5 text-[9px]":"w-12 h-6 text-[10px]",G?s>0?"bg-emerald-100 border-emerald-200 text-emerald-700 font-medium":s<0?"bg-rose-100 border-rose-200 text-rose-700 font-medium":"bg-slate-100 border-transparent text-slate-800 font-semibold":U?"bg-white border-indigo-200/80 text-slate-400 placeholder:text-indigo-300 focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200":"bg-slate-100 border-transparent text-slate-500 placeholder:text-slate-400 hover:bg-slate-200/70 focus:bg-white focus:border-slate-300 focus:ring-1 focus:ring-slate-200"),"data-testid":`adj-${t}-${a}`,"data-explicit-zero":r&&s===0?"true":void 0,"data-sacred":c?"true":void 0,"data-prereq-empty":F?"true":void 0,"aria-label":F?"Adjustment cell — Run Adjustments to populate. Lock both Market and Sub-Market datasets, verify the subject, and ensure usable comps first.":void 0,title:F?"Run Adjustments to populate (see the disabled toolbar button for the full prereq list)":void 0}),c&&e.jsx(q5,{className:"absolute top-0.5 right-0.5 w-2.5 h-2.5 text-amber-600","aria-label":"Manual override — protected from cascade","data-testid":`pin-sacred-${t}-${a}`}),j&&y&&e.jsx("div",{className:"absolute -bottom-3.5 left-1/2 -translate-x-1/2 whitespace-nowrap text-[8px] text-indigo-600 font-medium bg-white/90 px-1 rounded shadow-sm border border-indigo-100 z-10",children:j}),U&&!G&&e.jsx("div",{className:"w-10 h-1 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-indigo-300/60 rounded-full",style:{width:`${Math.min(100,Math.max(20,(1-C/Math.max(Math.abs(i.amount)*3,1))*100))}%`,marginLeft:"auto",marginRight:"auto"}})})]})}),(U||c||m&&m.length>0)&&e.jsxs(Wa,{side:"top",className:"max-w-xs text-xs bg-white text-slate-700 border border-slate-200 shadow-lg",children:[c&&e.jsxs("div",{className:"mb-1.5 pb-1.5 border-b border-slate-200",children:[e.jsx("p",{className:"font-semibold text-slate-900",children:"Manual override"}),e.jsx("p",{className:"text-slate-500 text-[11px]",children:"Cascades won't change this cell. Reset to allow auto-fill again."}),u&&e.jsx("button",{type:"button",onClick:()=>u(t,a),className:"mt-1 inline-flex items-center gap-1 text-[11px] font-medium text-indigo-600 hover:text-indigo-800 hover:underline","data-testid":`button-reset-sacred-${t}-${a}`,children:"Reset to suggested"})]}),m&&m.length>0&&e.jsxs("div",{className:Q("space-y-0.5",(U||c)&&"mb-1.5 pb-1.5 border-b border-slate-200"),"data-testid":`tooltip-chip-derivation-${t}-${a}`,children:[e.jsx("p",{className:"font-semibold text-indigo-700",children:"From Master Rate chip"}),m.map(A=>e.jsx("p",{className:"text-muted-foreground text-[11px] font-mono leading-tight","data-testid":`tooltip-chip-derivation-line-${t}-${a}-${A.attribute}`,children:A.formula},`${A.attribute}-${A.formula}`)),m.length>1&&e.jsxs("p",{className:"text-[11px] font-medium text-slate-700 pt-0.5",children:["Total: ",s>0?"+":"","$",Math.abs(s).toLocaleString()]})]}),U&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"font-medium",children:["Suggested: ",i.amount>
390?"+":"","$",Math.abs(i.amount).toLocaleString()]}),e.jsxs("p",{className:"text-muted-foreground",children:["Range: $",Math.abs(i.rangeLow).toLocaleString()," to $",Math.abs(i.rangeHigh).toLocaleString()]})]})]})]})})}function eK({subject:t,comps:a,subjectSiteInfo:s,gridTemplateColumns:r,showMasterRateColumn:n,effectiveShowAdjustments:i,getAdjustment:l,hasAdjustment:c,onAdjustmentChange:d,onSubjectSiteInfoChange:p,onComparableSiteInfoChange:u,sitePickerOpen:m=!1,sitePicker:h,onSitePickerClose:f,canonicalRows:v,showMissingOnly:S=!1,isRequiredSiteRowMissing:N,isRequiredSiteRowMissingForProperty:x}){const{inspecting:y}=fc(),b=U=>U==="mls"||U==="MLS"?"MLS":U==="public_records"||U==="PublicRecord"?"PublicRecord":U==="ai_derived"||U==="AI"?"AI":"User",j=(U,C)=>{const F=U.fields?.[C];return F&&typeof F=="object"?F:{}},T=U=>U==="mls"||U==="MLS"?"mls":U==="public_records"||U==="PublicRecord"?"public_records":U==="ai_derived"||U==="AI"?"ai_derived":"user",O=U=>{const C=U.sourceCandidates;return C&&typeof C=="object"?C:void 0},E=(U,C)=>{const F=C==="SiteInfluenceType"?"location":"view",A=U.fields?.[C]!==void 0?C:F,M=U.fields?.[A]?.value;return[{id:`legacy-site-${U.id}-${C}`,[C]:M}].filter(B=>B[C]!==void 0&&B[C]!==null&&String(B[C]).trim()!=="")},R=U=>{const C=O(U);return C?.mls!==void 0?"ClearUser:MLS":C?.public_records!==void 0?"ClearUser:PublicRecord":C?.ai_derived!==void 0?"ClearUser:AI":"ClearUser"},G=(U,C)=>{a.forEach(F=>{const A=C.map((M,B)=>({...M,id:`user-${U}-${F.id}-${B+1}-${globalThis.crypto?.randomUUID?.()??Date.now()}`}));u?.(F.id,U,A,"User")})};return e.jsxs(e.Fragment,{children:[m&&e.jsx("button",{type:"button",className:"fixed inset-0 z-50 cursor-default bg-white/50","aria-label":"Close Site row selector","data-testid":"site-picker-grid-scrim",onMouseDown:f}),e.jsxs("div",{className:"relative min-w-full border-y border-slate-300","data-testid":"band-siteInfo",children:[e.jsx("div",{className:Q("relative bg-slate-700",m&&"z-[60]"),"data-testid":"band-siteInfo-header",children:e.jsxs("div",{className:"sticky left-0 z-[2] flex w-max items-center gap-2 px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-white",children:[e.jsx("span",{children:"Site"}),h]})}),v,R7.map(U=>{const C=U.id==="siteInfluence"?"SiteInfluenceType":"ViewType";return S&&N&&!N(C)?null:e.jsxs("div",{className:"grid border-b border-slate-200 bg-white last:border-b-0",style:{gridTemplateColumns:r},"data-testid":`site-info-row-${U.id}`,children:[e.jsx("div",{className:"sticky left-0 z-[2] flex min-h-[32px] w-[170px] min-w-[170px] items-center bg-slate-50 px-3 text-[12px] font-semibold text-slate-700",children:U.label}),n&&e.jsx("div",{className:"min-h-[32px] border-r border-slate-200 bg-slate-50","aria-hidden":"true"}),(()=>{const F=U.id==="siteInfluence"?s?s.influences:E(t,"SiteInfluenceType"):s?s.views:E(t,"ViewType"),A=U.id==="siteInfluence"?s?.influencesSource:s?.viewsSource;return e.jsxs("div",{className:Q("sticky z-[2] flex min-h-[32px] items-center justify-start border-r border-slate-200 bg-white text-left text-[11px] text-slate-700",F.length>0&&A&&"pl-8",Gl({fieldName:C,isMissing:x?.(t,C)??!1,isRequired:!0})),style:{left:n?"320px":"170px"},"data-testid":`subject-site-info-cell-${U.id}`,children:[y&&e.jsx(Fs,{section:"site",fieldName:U.id==="siteInfluence"?"influences":"views",displayLabel:`Subject · ${U.label}`}),F.length>0&&A&&e.jsx("span",{className:"absolute left-2 top-1/2 z-[1] -translate-y-1/2",children:e.jsx(Ji,{source:A,testId:`source-dot-subject-site-info-${U.id}`})}),e.jsx(yP,{kind:U.id==="siteInfluence"?"influence":"view",label:`Subject ${U.label}`,items:F,subjectMode:!0,onChange:M=>p?.(U.id==="siteInfluence"?"influences":"views",M),testId:`subject-site-info-${U.id}`})]})})(),a.map((F,A)=>{const M=U.id==="siteInfluence"?"SiteInfluences":"SiteViews",B=j(F,M),oe=Array.isArray(B.value)?B.value:E(F,U.id==="siteInfluence"?"SiteInfluenceType":"ViewType"),ae=U.id==="siteInfluence"?"SiteInfluence":"ViewRange";return e.jsxs(Mn.Fragment,{children:[e.jsxs("div",{className:Q("relative flex min-h-[32px] items-center justify-start border-r border-slate-200 text-left",oe.length>0&&B.source&&"pl-8",Gl({fieldName:C,isMissing:x?.(F,C)??!1,isRequired:!0})),children:[y&&e.jsx(Fs,{section:"salesComparison",fieldName:Zi(F.id,`fields.${M}`),displayLabel:`Comp ${A+1} · ${U.label}`}),oe.length>0&&e.jsx("span",{className:"absolute left-2 top-1/2 z-[1] -translate-y-1/2",children:e.jsx(Ji,{source:T(B.source),testId:`source-dot-site-info-${U.id}-${F.id}`})}),e.jsx(yP,{kind:U.id==="siteInfluence"?"influence":"view",label:`Comp ${A+1} ${U.label}`,items:oe,activeSource:T(B.source),sourceCandidates:O(B),onChange:(D,_)=>u?.(F.id,M,D,b(_)),onClearUser:()=>u?.(F.id,M,[],R(B)),onCopyToAll:D=>G(M,D),testId:`comp-site-info-${U.id}-${F.id}`})]}),i?e.jsxs("div",{className:"flex min-h-[32px] items-center justify-start border-r border-slate-200",children:[y&&e.jsx(Fs,{section:"salesComparison",fieldName:Zi(F.id,`adjustments.${ae}`),displayLabel:`Comp ${A+1} · ${U.label} adjustment`}),e.jsx(Ph,{propertyId:F.id,fieldName:ae,adjustment:l(F.id,ae),hasExplicitValue:c(F.id,ae),onAdjustmentChange:(D,_,$)=>d?.(D,_,$),compact:!0})]}):null]},`${U.id}-${F.id}`)})]},U.id)})]})]})}function Lj({rowId:t,label:a,ruleText:s,outputRule:r,showAutomaticInclusion:n=!0}){const i=n1(s),l=r?n1(r):void 0,c=n?"automatic inclusion":"report output",d=n?i:l??i;return e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-slate-400 hover:bg-slate-100 hover:text-slate-600 focus:outline-none focus:ring-1 focus:ring-blue-400","aria-label":`Explain ${c} for ${a}: ${d}`,"data-testid":`tooltip-trigger-picker-${t}`,children:e.jsx(on,{className:"h-3.5 w-3.5","aria-hidden":"true"})})}),e.jsxs(Wa,{side:"right",align:"start",className:"max-w-xs text-xs","data-testid":`tooltip-picker-${t}`,children:[n&&e.jsxs("p",{children:["Automatic inclusion and locking: ",i]}),l&&e.jsx("p",{className:n?"mt-1":void 0,children:l})]})]})})}function d1({subject:t,comps:a,detectedOptionalSections:s,onFieldU
39pdate:r,onComplete:n,onBack:i,onPropertyClick:l,onReplaceComp:c,onRemoveComp:d,onAdjustmentChange:p,onComparabilityChange:u,onCompOrderChange:m,gridMode:h="1004",activeScenario:f,pendingAdvisorApply:v,onAdvisorApplyConsumed:S,pendingAdvisorApplyForceFields:N,advisorSuggestions:x,onMapSnapshotChange:y,persistedAdjustments:b,assignmentId:j,effectiveDate:T,multiMethodSubject:O,multiMethodComps:E,onOpenTimeWizard:R,runAdjustmentsButton:G,toolbarExtraActions:U,adjustmentBar:C,multiMethodCanRun:F,enableUad36:A=!1,uad36ReconciliationValue:M,uad36ReconciliationValueMode:B,uad36ReconciliationFieldPresent:oe=!1,uad36ReconciliationHydrated:ae=!1,onUad36ReconciliationValueChange:D,onUad36ReconciliationValueModeChange:_,evalGridProfile:$=!1,evalCustomComparisonFactors:z=[],onEvalCustomComparisonFactorsChange:V,subjectOccupancy:le,subjectUnitCount:W,onNonSalesSlotCountChange:me,saleHistoryGetValue:Z,saleHistoryGetSource:pe,saleHistorySetValue:se,subjectVehicleStorageItems:fe=[],subjectVehicleStorageLoading:ue=!1,subjectVehicleStorageSource:be,subjectVehicleStorageUserEdited:H,subjectVehicleStorageExplicitNone:ye=!1,onSubjectVehicleStorageChange:de,onComparableVehicleStorageChange:ge,subjectSiteInfo:Be,onSubjectSiteInfoChange:He,onComparableSiteInfoChange:Ie,vehicleStorageRows:ce=[],vehicleStorageSubjectValues:Pe={},onVehicleStorageRowsChange:We,onVehicleStorageCustomValueChange:Re,subjectEnergyFeatures:ne,onSubjectEnergyCollectionChange:Me,onComparableEnergyCollectionChange:lt,energyRows:Tt=[],onEnergyRowsChange:je,siteRows:Le=[],onSiteRowsChange:ut,amenityRows:st=[],onAmenityRowsChange:Xt,subjectAmenities:ua=[],subjectAmenitiesSource:Oa,subjectAmenitiesHasManufacturedHome:Xa=!1,uad36SubjectPropertyFields:qa,uad36ValuationAssignmentType:os,uad36SubjectCanonicalFields:ya,onUad36SubjectCanonicalFieldChange:At,uad36SubjectContractExists:Fe,uad36SubjectContractReviewed:Oe,uad36ProjectFields:rt,onSubjectAmenitiesChange:$t,onComparableAmenitiesChange:na,onComparableProjectClassificationChange:zt,onComparableStructuresChange:Ua,onSubjectConcessionTransactionChange:Ce,onComparableConcessionTransactionChange:St}){const vt=A&&!!We,Ve=A&&!!je,sa=A&&!!ut,tt=A&&!!Xt,{inspecting:it}=fc(),[Je,ht]=o.useState("grid"),Kt=o.useCallback(J=>{ht(J)},[]),[Sa,Qt]=o.useState("sales"),[ea,tr]=o.useState(0),[ir,zs]=o.useState(0),{data:pr}=Vr({queryKey:["/api/uad36/prefill",j],queryFn:async()=>{const J=await fetch(`/api/uad36/prefill/${j}`);if(!J.ok)throw new Error("prefill fetch failed");return J.json()},enabled:A&&!!j&&j!=="new",staleTime:6e4}),$e=A?lU(pr?.sections?.costApproach).length:0,Ot=Number(pr?.sections?.rentalComparison?.CompCount?.value??0),_e=Number(pr?.sections?.grmComparison?.CompCount?.value??0),ma=Math.max(ea,Ot),pt=Math.max(ir,_e);o.useEffect(()=>{me?.($e+ma+pt)},[$e,ma,pt,me]);const{useRentalApproach:re,useIncomeApproach:qe,useSalesComparison:Ze}=AN(j,A),It=qe||re,Ne=qe,Ue=!A||Ze!==!1,ct=A&&(It||Ne),xt=A?void 0:t.fields,Na=o.useCallback(J=>{const he=ya?.[J]??(J==="SalesContractAmount"?ya?.ContractPrice:J==="SalesContractDate"?ya?.ContractDate:void 0);return A&&J==="SalesContractDate"?he:he??qp(qa?.[J])},[A,ya,qa]),qt=o.useCallback((J,he)=>{if(he!==void 0)return he;const Ae=Na(J)?.value;return Ae===!0||String(Ae).toLowerCase()==="true"},[Na]),la=o.useCallback((J,he)=>{At?.(J==="SalesContractDate"?"salesContract":J==="SalesContractAmount"?"subjectProperty":"salesContract",J,he)},[At]),fs=qt("SalesContractExistsIndicator",Fe),ps=qt("SalesContractReviewedIndicator",Oe),Te=(Ue?1:0)+(It?1:0)+(Ne?1:0),at=ct&&Te>1,yt=o.useMemo(()=>{const J=Ae=>Ae==="sales"?Ue:Ae==="rental"?It:Ne;return J(Sa)?Sa:["sales","rental","grm"].find(J)??"sales"},[Sa,Ue,It,Ne]),nt=h!=="str",Wt=A?ID:$?P3:hd,ts=o.useMemo(()=>{if(!nt)return[];const J=parseInt(String(W??""),10);return!Number.isFinite(J)||J<2?[]:Array.from({length:Math.min(J,4)-1},(he,Ae)=>`basementUnit${Ae+2}`)},[nt,W]),gs=o.useCallback(J=>{Qt(J),Kt("grid")},[Kt]),[Va,Mr]=o.useState(!1),[xs,Sn]=o.useState(!1),[ds,Zt]=o.useState(!1),[Rs,Os]=o.useState(null),qs=o.useCallback(J=>{Os(J)},[]),Ks=o.useCallback((J,he)=>{he.currentTarget.contains(he.relatedTarget)||Os(Ae=>Ae===J?null:Ae)}
39,[]),[Tn,Bn]=o.useState({}),[Ka,Ee]=o.useState([]),[dt,ot]=o.useState(new Set),[xa,rs]=o.useState(!1),[Gs,bs]=o.useState(!1),[ba,ln]=o.useState(()=>cd.filter(J=>st.some(he=>he.rowId===zx(J)&&he.relevant!==!1))),[zn,fd]=o.useState(!1),[go,Zd]=o.useState({marketPctYr:"3",glaPerSf:"",qcPct:"",qcCondPct:"",roomsBedRate:"",roomsBathRate:"",basementFinRate:"",basementUnfinRate:"",sitePerSf:"",yearBuiltPerYr:"",garageSpaceRate:"",bgBedRate:"",bgBathRate:""}),[Mu,hp]=o.useState({}),[qn,gd]=o.useState({}),[Bi,xd]=o.useState({quality:"percent",condition:"percent"}),[Jp,hf]=o.useState(!1),[_c,bd]=o.useState(null),In=o.useRef(new Map),Yn=o.useRef(new Set),Qa=o.useRef(new Set),[Xi,Ri]=o.useState(null),{setPreference:yd,getPreferredSource:Zo}=_I(),[Tg,Xp]=o.useState(new Set),[ni,ki]=o.useState(null),[fp,Ol]=o.useState({}),$m=Vr({queryKey:["/api/orders",j,"subject-photos"],enabled:!!j,retry:!1}),Jd=o.useMemo(()=>{const J=$m.data?.photos;if(J?.length)return J.find(he=>he.isPrimary)?.originalUrl},[$m.data]);o.useEffect(()=>{Ol(J=>{const he={...J};let Ae=!1;for(const Ke of a)Ke.primaryPhotoUrl&&he[Ke.id]===void 0&&(he[Ke.id]=Ke.primaryPhotoUrl,Ae=!0);return Jd&&he[t.id]===void 0&&(he[t.id]=Jd,Ae=!0),Ae?he:J})},[a,Jd,t.id]);const[Ig,Cg]=o.useState({}),[Sd,ml]=o.useState({}),[Rg,hl]=o.useState([]),[ff,vd]=o.useState(null),[gf,Gn]=o.useState(!1),[zi,em]=o.useState(new Set),[Bm,xb]=o.useState(!1),[gc,zm]=o.useState(!1),Nd=o.useRef(!1),Fu=o.useRef(null),Uc=o.useRef(!1),Xd=o.useRef(null),eu=o.useRef(null),qm=o.useRef(null),Eg=o.useRef(null);o.useEffect(()=>()=>{Fu.current!=null&&cancelAnimationFrame(Fu.current),Xd.current!=null&&clearTimeout(Xd.current)},[]);const Ym=o.useRef(!1);o.useLayoutEffect(()=>{if(!Ym.current){Ym.current=!0;return}const J=eu.current;if(J&&gc){const he=qm.current;if(he){const Ae=he.getBoundingClientRect().height;Eg.current=Ae;const ft=Ae-32;if(ft>0){const mt=Math.max(0,J.scrollHeight-J.clientHeight);J.scrollTop=Math.min(J.scrollTop+ft,mt)}}}else if(J&&!gc){const he=Eg.current,Ae=32;if(he!=null){const Ke=he-Ae;Ke>0&&(J.scrollTop=Math.max(0,J.scrollTop-Ke))}}Xd.current!=null&&clearTimeout(Xd.current),Uc.current=!0,Xd.current=setTimeout(()=>{Uc.current=!1,Xd.current=null,eu.current?.scrollTop<=8&&zm(!1)},350)},[gc]);const gy=o.useCallback(J=>{const he=J.currentTarget;eu.current=he,!Uc.current&&(Nd.current||(Nd.current=!0,Fu.current=requestAnimationFrame(()=>{Nd.current=!1,Fu.current=null;const Ae=he.scrollTop;zm(Ke=>Ke?Ae>8:Ae>40)})))},[]),[Vc,tm]=o.useState(""),tu=o.useRef("");tu.current=Vc;const[ii,Gm]=o.useState("suggested"),eo=A&&!$&&!!(D&&_),Wr=(()=>{if(M==null||M==="")return"";const J=typeof M=="number"?M:Number(String(M).replace(/[^0-9.-]/g,""));return Number.isFinite(J)&&J>0?String(J):""})(),$c=eo?Wr:Vc,Bc=eo?xj(B,Wr):ii,[_u,xf]=o.useState(""),[No,gp]=o.useState([]),[xp,wg]=o.useState(""),Pg=o.useCallback(J=>{gp(he=>he.includes(J)?he.filter(Ae=>Ae!==J):[...he,J])},[]),qi=o.useRef(T);qi.current=T;const[Jo,Ll]=o.useState({}),[oi,zc]=o.useState([]),[am,xo]=o.useState(ce),[Yi,Og]=o.useState(Tt),[Xo,Lg]=o.useState(Le.filter(J=>J.rowId!=="LotSizeAreaMeasure")),[au,Tr]=o.useState(null),[Fr,Zl]=o.useState(null),qc=o.useRef(null);o.useEffect(()=>{if(!Fr)return;const J=he=>{qc.current?.contains(he.target)||Zl(null)};return document.addEventListener("mousedown",J,!0),()=>document.removeEventListener("mousedown",J,!0)},[Fr]);const bf=o.useCallback(J=>{const he=cd.filter(Ae=>J.includes(Ae));if(ln(he),tt)Xt?.(cd.map(Ae=>({rowId:zx(Ae),kind:"optional",relevant:he.includes(Ae)})));else{const Ae=he.length>0;Bn(Ke=>({...Ke,amenities:Ae})),Ee(Ke=>Ae?Ke.includes("amenities")?Ke:[...Ke,"amenities"]:Ke.filter(ft=>ft!=="amenities"))}},[tt,Xt]),sm=o.useCallback(J=>{Og(J),je?.(J)},[je]),rm=o.useCallback(async J=>{const he=J.filter(Ae=>Ae.rowId!=="LotSizeAreaMeasure");return Lg(he),ut?ut(he):!1},[ut]),[nm,Dg]=o.useState(0),yf=o.useCallback(async(J,he)=>{if(!We)return!1;xo(J),Dg(Ae=>Ae+1);try{return await We(J,he)}finally{Dg(Ae=>Math.max(0,Ae-1))}},[We]);o.useEffect(()=>{vt&&nm===0&&xo(ce)},[vt,nm,ce]),o.useEffect(()=>{Ve&&Og(Tt)},[Ve,Tt]),o.useEffect(()=>{sa&&Lg(Le.filter(J=>J.rowId!=="LotSizeAreaMeasure"))},[sa,Le]),o.useEffect(()=>{tt&&ln(cd.filter(J=>st.some(he=>he.rowId===zx(J)&&he.relevant!==!1)))},[st,tt]);const[el,Jn]=o.useState(new Set),[Yc,vn]=o.useState(!1),[su,Ei]=o.use
39State(new Set),[Gc,$r]=o.useState(""),[Mi,tl]=o.useState(null),[to,Ao]=o.useState(null),[Gi,li]=o.useState(null),fl=Gi!==null,[im,Ad]=o.useState(null),[gl,Nn]=o.useState(null),_o=o.useRef(null),mr=o.useRef(null),Jl=o.useRef(!1),bp=o.useRef(0),Uu=o.useRef(!1),ru=o.useRef(!1),yp=o.useRef(Promise.resolve()),jd=o.useRef(new Set),Uo=o.useRef(new Set),[xl,om]=o.useState(0),Br=new Set(["ReasonPropertyNotUsedType","ReasonPropertyNotUsedTypeOtherDescription","catalog_hoa_fee","catalog_project_name","PUDIndicator","PropertyInProjectIndicator","ProjectName","ProjectLegalStructureType","SameProjectAsSubjectIndicator","AssociationChargeType","AssociationChargeAmount","AssociationChargePeriodType","AssociationSpecialAssessmentStatusType","ProjectCommonAmenityType"]);o.useEffect(()=>{if(!j){Jl.current=!0;return}Jl.current=!1;const J=++bp.current;let he=!1;return(async()=>{try{const Ae=await fetch(`/api/orders/${j}/sales-grid-custom-rows`);if(!Ae.ok)throw new Error(`HTTP ${Ae.status}`);const Ke=await Ae.json();if(he||bp.current!==J)return;const ft=Array.isArray(Ke?.customRows)?Ke.customRows.map(mt=>{if(!mt||typeof mt.id!="string"||typeof mt.label!="string")return null;const Xe=mt.source==="catalog"?"catalog":"custom",_t=typeof mt.group=="string"?mt.group:void 0,oa=A&&Xe==="catalog"&&typeof mt.rowId=="string"?_t??og(mt.rowId):_t;return{id:mt.id,label:mt.label,source:Xe,rowId:typeof mt.rowId=="string"?mt.rowId:void 0,group:oa,relevant:mt.relevant===!1?!1:void 0}}).filter(Boolean).filter(mt=>!Br.has(mt.rowId)&&!(A&&Xh(mt.rowId,mt.group)&&!(typeof mt.rowId=="string"&&sd.includes(mt.rowId)))&&!(A&&Ej(mt))&&!(A&&wj(mt)&&!(typeof mt.rowId=="string"&&sd.includes(mt.rowId)))):[];ru.current=!0,zc(ft)}catch(Ae){console.warn("[SalesComparisonGrid] Failed to load custom rows:",Ae)}finally{!he&&bp.current===J&&(Jl.current=!0,om(Ae=>Ae+1))}})(),()=>{he=!0}},[j,vt,A]);const nu=o.useCallback(J=>{const he=yp.current.catch(()=>{}).then(async()=>{const Ae=await fetch(`/api/orders/${j}/sales-grid-custom-rows`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({customRows:A?J.filter(Ke=>!Xh(Ke.rowId,Ke.group)):J}),keepalive:!0});if(!Ae.ok)throw new Error(`HTTP ${Ae.status}`)});return yp.current=he.catch(()=>{}),he},[j,A]);Fx({enabled:!!j,scopeId:j,isHydrated:()=>Jl.current&&!ru.current,label:"[SalesComparisonGrid] custom rows",persist:()=>{const J=new Set([...Array.from(jd.current),...Array.from(Uo.current)]);return nu(A?oi.filter(he=>!Ej(he)&&!wj(he)&&!(he.source==="catalog"&&typeof he.rowId=="string"&&J.has(he.rowId))):oi)},deps:[j,oi,A]}),o.useEffect(()=>{ru.current&&(ru.current=!1)},[oi]),o.useEffect(()=>{if(!sa||!Jl.current)return;const J=new Set(sd),he=oi.filter(Xe=>Xe.source==="catalog"&&typeof Xe.rowId=="string"&&J.has(Xe.rowId)&&Xe.rowId!=="LotSizeAreaMeasure").map(Xe=>({rowId:Xe.rowId,kind:"optional",label:Xe.label,group:"Site",relevant:Xe.relevant!==!1}));if(he.length===0||Uu.current)return;const Ae=new Set(Le.map(Xe=>Xe.rowId)),Ke=new Set(Xo.map(Xe=>Xe.rowId)),ft=he.filter(Xe=>!Ke.has(Xe.rowId)),mt=new Set(he.map(Xe=>Xe.rowId));Uu.current=!0,(async()=>{try{const Xe=ft.filter(oa=>!Ae.has(oa.rowId));if(Xe.length>0&&!await rm([...Xo,...Xe]))throw new Error("canonical Site relevance save was not acknowledged");const _t=oi.filter(oa=>!(oa.source==="catalog"&&typeof oa.rowId=="string"&&mt.has(oa.rowId)));for(const oa of Array.from(mt))jd.current.add(oa);await nu(_t);for(const oa of Array.from(mt))jd.current.delete(oa),Uo.current.add(oa);ru.current=!0,zc(oa=>oa.filter(ls=>!(ls.source==="catalog"&&typeof ls.rowId=="string"&&mt.has(ls.rowId))))}catch(Xe){for(const _t of Array.from(mt))jd.current.delete(_t);console.warn("[SalesComparisonGrid] Site row migration deferred:",Xe)}finally{Uu.current=!1}})()},[j,Xo,sa,oi,nu,rm,xl,Le]);const lm=o.useRef(!1),[xc,cm]=o.useState(!1),Hc=o.useRef(0),Hi=o.useRef({});o.useEffect(()=>{if(!j){lm.current=!0,cm(!0);return}lm.current=!1,cm(!1);const J=++Hc.current;let he=!1;return(async()=>{try{const Ae=await fetch(`/api/orders/${j}/sales-grid-ui-state`);if(!Ae.ok)throw new Error(`HTTP ${Ae.status}`);const Ke=await Ae.json();if(he||Hc.current!==J)return;
39const ft=Ke?.optionalBandsOpen,mt={};if(ft&&typeof ft=="object"){for(const Ps of Wt)if(Ps.optional&&typeof ft[Ps.id]=="boolean"){if(Ps.autoOnly&&ft[Ps.id]===!1)continue;mt[Ps.id]=ft[Ps.id]}}Hi.current=mt;const _t=(Array.isArray(Ke?.optionalBandOrder)?Ke.optionalBandOrder:[]).filter(Ps=>typeof Ps=="string"&&Wt.some(Er=>Er.optional&&Er.id===Ps));_t.length>0&&Ee(Ps=>[..._t.filter(Er=>!Ps.includes(Er)),...Ps]),Bn(Ps=>Object.keys(mt).length===0&&Object.keys(Ps).length===0?Ps:{...mt,...Ps});const ls=(Array.isArray(Ke?.collapsedBands)?Ke.collapsedBands:[]).filter(Ps=>typeof Ps=="string"&&Wt.some(Er=>Er.id===Ps));ls.length>0&&ot(Ps=>{const Er=new Set(Ps);for(const mn of ls)Er.add(mn);return Er})}catch(Ae){console.warn("[SalesComparisonGrid] Failed to load optional-section state:",Ae)}finally{!he&&Hc.current===J&&(lm.current=!0,cm(!0),om(Ae=>Ae+1))}})(),()=>{he=!0}},[j,Wt]),o.useEffect(()=>{if(!j||!xc)return;let J=!0;const he=qD(j,"SalesComparisonGrid",async()=>{if(J)try{const Ae=await fetch(`/api/orders/${j}/sales-grid-ui-state`);if(!Ae.ok||!J)return;const Ke=await Ae.json(),ft=Ke?.optionalBandsOpen,mt={};if(ft&&typeof ft=="object")for(const oa of Wt)oa.optional&&typeof ft[oa.id]=="boolean"&&(mt[oa.id]=ft[oa.id]);if(!J)return;Bn(oa=>{const ls=Hi.current,Ps={},Er=new Set([...Object.keys(ls),...Object.keys(mt)]);for(const vr of Er)ls[vr]!==mt[vr]&&mt[vr]!==void 0&&(Ps[vr]=mt[vr]);if(Hi.current={...mt},Object.keys(Ps).length===0)return oa;const mn={...oa,...Ps};return YD(oa,mn)?oa:mn});const _t=(Array.isArray(Ke?.optionalBandOrder)?Ke.optionalBandOrder:[]).filter(oa=>typeof oa=="string"&&Wt.some(ls=>ls.optional&&ls.id===oa));_t.length>0&&Ee(oa=>oa.length===_t.length&&oa.every((ls,Ps)=>ls===_t[Ps])?oa:_t)}catch{}});return()=>{J=!1,he()}},[j,xc]);const Sp=o.useRef(new Set);o.useEffect(()=>{if(!xc||h==="str")return;const J={};for(const[he,Ae]of Object.entries(s??{}))Ae&&Wt.some(Ke=>Ke.id===he)&&Hi.current[he]===void 0&&(Sp.current.has(he)||(Sp.current.add(he),J[he]=!0));Object.keys(J).length>0&&Bn(he=>({...he,...J}))},[xc,s,h]),Fx({enabled:!!j,scopeId:j,isHydrated:()=>lm.current,label:"[SalesComparisonGrid] optional-section state",persist:()=>fetch(`/api/orders/${j}/sales-grid-ui-state`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(A?(()=>{const J=new Set(Wt.filter(Ae=>Ae.optional).map(Ae=>Ae.id)),he=new Set(Wt.map(Ae=>Ae.id));return{optionalBandsOpen:Object.fromEntries(Object.entries(Tn).filter(([Ae])=>J.has(Ae))),optionalBandOrder:Ka.filter(Ae=>J.has(Ae)),collapsedBands:[...dt].filter(Ae=>he.has(Ae))}})():{optionalBandsOpen:Tn,optionalBandOrder:Ka,collapsedBands:[...dt]}),keepalive:!0}).then(J=>(J.ok&&j&&zD(j,"SalesComparisonGrid"),J)),deps:[j,Tn,Ka,dt]});const iu=o.useRef(!1),vp=o.useRef(0),Np=o.useRef(!1);o.useEffect(()=>{if(!j){iu.current=!0;return}iu.current=!1;const J=++vp.current;let he=!1;return(async()=>{try{const Ae=await fetch(`/api/orders/${j}/sales-grid-auto-adjust`);if(!Ae.ok)throw new Error(`HTTP ${Ae.status}`);const Ke=await Ae.json();if(he||vp.current!==J)return;const ft=new Set;for(const _t of Object.values(ac))ft.add(_t.rateKey),_t.rate2Key&&ft.add(_t.rate2Key);for(const _t of Object.values(sc))ft.add(_t.rateKey);const mt=new Set([...Object.keys(ac),...Object.keys(sc)]),Xe=wP(Ke,ft,mt);PP(Xe)||(Np.current=!0),Object.keys(Xe.rates).length>0&&Zd(_t=>({..._t,...Object.fromEntries(Object.entries(Xe.rates).filter(([oa])=>{const ls=_t[oa];return ls===void 0||ls===""||oa==="marketPctYr"&&ls==="3"}))})),Object.keys(Xe.thresholds).length>0&&hp(_t=>({...Xe.thresholds,..._t})),Object.keys(Xe.basis).length>0&&gd(_t=>({...Xe.basis,..._t})),Xe.qualityConditionBasis&&(xd(Xe.qualityConditionBasis),hf(!0))}catch(Ae){console.warn("[SalesComparisonGrid] Failed to load auto-adjust config:",Ae)}finally{!he&&vp.current===J&&(iu.current=!0)}})(),()=>{he=!0}},[j,Wt]),Fx({enabled:!!j,scopeId:j,isHydrated:()=>iu.current,label:"[SalesComparisonGrid] auto-adjust config",persist:()=>{const J=wP({rates:go,thresholds:Mu,basis:qn,...Jp?{qualityConditionBasis:Bi}:{}}),he=PP(J);
39if(!(he&&!Np.current))return Np.current=!he,fetch(`/api/orders/${j}/sales-grid-auto-adjust`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),keepalive:!0})},deps:[j,go,Mu,qn,Bi,Jp]}),o.useEffect(()=>{if(!Yc){$r(""),tl(null),Ao(null),Ei(new Set);return}if(to==="vehicle")return;const J=Ae=>{const Ke=Ae.target,ft=_o.current?.contains(Ke)??!1,mt=mr.current?.contains(Ke)??!1;!ft&&!mt&&vn(!1)},he=Ae=>{Ae.key==="Escape"&&vn(!1)};return document.addEventListener("mousedown",J),document.addEventListener("keydown",he),()=>{document.removeEventListener("mousedown",J),document.removeEventListener("keydown",he)}},[Yc,to]);const ao=o.useRef(!1),[Zs,al]=o.useState(!1),Fi=o.useRef(0),Td=o.useRef(!1),Vu=o.useRef(!1),Ap=o.useRef(!1),Hm=o.useRef(!1);o.useEffect(()=>{if(!(!$||!j))return Hm.current=!0,nM(j,"grid",(J,he)=>{const Ae=J==null?"":String(J);tu.current!==Ae&&(ao.current||(Td.current=!0),Ap.current=!0,tu.current=Ae,tm(Ae),he==="edit"&&Gm("manual"))})},[j,$]),o.useEffect(()=>{if(!j){ao.current=!0,al(!0),qi.current&&wg(Ae=>Ae||qi.current||"");return}ao.current=!1,al(!1),Td.current=!1,Vu.current=!1;const J=++Fi.current;let he=!1;return(async()=>{try{const Ae=await fetch(`/api/orders/${j}/sales-grid-weights`);if(!Ae.ok)throw new Error(`HTTP ${Ae.status}`);const Ke=await Ae.json();if(he||Fi.current!==J)return;const ft=Ke?.weights&&typeof Ke.weights=="object"?Ke.weights:{},mt={};for(const[ls,Ps]of Object.entries(ft))mt[ls]=Zf(Ps);Ll(mt);const Xe=typeof Ke?.indicatedValue=="string"?Ke.indicatedValue:"",_t=Td.current?tu.current:Xe;Td.current||(tu.current=Xe,tm(Xe)),Td.current||Gm(xj(Ke?.valueMode,Xe)),typeof Ke?.opinionOfMarketValue=="string"&&xf(Ke.opinionOfMarketValue),Array.isArray(Ke?.marketValueCondition)&&gp(Ke.marketValueCondition.filter(ls=>typeof ls=="string"));const oa=typeof Ke?.effectiveDate=="string"?Ke.effectiveDate:"";wg(oa||qi.current||""),$&&j&&(Vu.current&&lv(j,"grid",_t),JT(j,"grid",_t))}catch(Ae){console.warn("[SalesComparisonGrid] Failed to load weights:",Ae),!he&&$&&j&&(Vu.current&&lv(j,"grid",tu.current),JT(j,"grid",Td.current?tu.current:null))}finally{!he&&Fi.current===J&&(ao.current=!0,al(!0))}})(),()=>{he=!0}},[j]);const js=(()=>{if(!eo||!ae||!Zs||oe)return null;const J=Number(Vc.replace(/[^0-9.-]/g,""));return Number.isFinite(J)&&J>0?J:null})();o.useEffect(()=>{js!=null&&(D?.(js),_?.(xj(ii,Vc)))},[Vc,js,D,_,ii]),o.useEffect(()=>{if(!(!$||!j||!ao.current||!Hm.current)){if(Ap.current){Ap.current=!1;return}lv(j,"grid",Vc)}},[j,$,Vc]),Fx({enabled:!!j,scopeId:j,isHydrated:()=>ao.current,label:"[SalesComparisonGrid] weights",persist:()=>fetch(`/api/orders/${j}/sales-grid-weights`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({weights:Jo,indicatedValue:Vc,valueMode:ii,opinionOfMarketValue:_u,marketValueCondition:No,effectiveDate:xp}),keepalive:!0}),deps:[j,Jo,Vc,ii,_u,No,xp]});const[bo,Wm]=o.useState("auto"),[ou,Xl]=o.useState(new Set),Id=o.useCallback(J=>{Xl(he=>{const Ae=new Set(he);return Ae.has(J)?Ae.delete(J):Ae.add(J),Ae})},[]),[$u,Km]=o.useState({}),Qm=o.useRef(null);o.useEffect(()=>{if(!y)return;const J=AW(t,a,Sd),he=J?JSON.stringify({s:J.subject,c:J.comps.map(Ae=>`${Ae.id}:${Ae.lat}:${Ae.lng}:${Ae.index}:${Ae.salePrice}:${Ae.adjustedPrice}`)}):null;he!==Qm.current&&(Qm.current=he,y(J))},[t,a,Sd,y]);const Sf=P5(HR(D5,{activationConstraint:{delay:250,tolerance:8}}),HR(L5,{coordinateGetter:O5})),Zm=o.useRef(null);o.useEffect(()=>{const J=a.map(Ae=>Ae.id),he=J.join(",");if(Zm.current&&he===Zm.current){Zm.current=null;return}Zm.current=null,hl(Ae=>Ae.join(",")===he?Ae:J)},[a]);const kg=o.useRef(a);kg.current=a;const dm=o.useRef(p);dm.current=p;const Vo=o.useRef(S);Vo.current=S;const xr=o.useRef(new Set),[Ir,Mg]=o.useState(0),lu=o.useCallback(()=>Mg(J=>J+1),[]),[ec,Jm]=o.useState(new Set),Ma=o.useRef(null),[Xn,Bu]=o.useState(null),Ea=o.useCallback((J,he)=>{const Ae=[],Ke=[];if(ml(ft=>{const mt={...ft};return J.forEach(({effectiveId:Xe,adjustments:_t})=>{Object.entries(_t).forEach(([oa,ls])=>{const Ps=`${Xe}:${oa}`,Er=he?.has(oa)??!1,mn=xr.current.has(Ps);mn&&!Er||(mt[Xe]||(mt[Xe]={}),mt[Xe]===ft[Xe]&&(mt[Xe]={...ft[Xe]}
39),mt[Xe][oa]=ls,Ae.push(Ps),mn&&Er&&Ke.push(Ps),dm.current?.(Xe,oa,ls))})}),mt}),Ke.length>0){for(const ft of Ke)xr.current.delete(ft);lu()}Ae.length>0&&(Jm(ft=>{const mt=new Set(ft);for(const Xe of Ae)mt.add(Xe);return mt}),Ma.current&&clearTimeout(Ma.current),Ma.current=setTimeout(()=>{Jm(new Set),Ma.current=null},1e3))},[lu]);o.useEffect(()=>{if(!v||v.length===0)return;const J=v.map(Ke=>{const mt=kg.current.find(Xe=>{const _t=Xe.snapshotId;return Xe.id===Ke.compId||_t===Ke.compId})?.id||Ke.compId;return{compId:Ke.compId,effectiveId:mt,adjustments:Ke.adjustments}}),he=new Set(N??[]),Ae=[];ml(Ke=>(J.forEach(({effectiveId:ft,adjustments:mt})=>{const Xe=Ke[ft]??{};Object.entries(mt).forEach(([_t,oa])=>{const ls=Xe[_t];if(he.has(_t)){const Ps=`${ft}:${_t}`;xr.current.has(Ps)&&(ls??0)!==oa&&Ae.push({effectiveId:ft,field:_t,existing:ls??0,incoming:oa})}else ls!=null&&ls!==0&&ls!==oa&&Ae.push({effectiveId:ft,field:_t,existing:ls,incoming:oa})})}),Ke)),Ae.length===0?(Ea(J,he.size>0?he:void 0),Vo.current?.()):Bu({resolved:J,conflicts:Ae,forceOverwriteFields:he.size>0?he:void 0})},[v,N,Ea]);const so=o.useRef(""),Xm=o.useRef("");o.useEffect(()=>{const J=a.map(_t=>_t.id).join(","),he=J!==so.current,Ae=b,Ke=!!Ae&&Object.keys(Ae).length>0,ft=Ke&&Xm.current!==J;if(!he&&!ft)return;const mt=()=>{const _t={};return a.forEach(oa=>{const ls={};Object.entries(oa.fields).forEach(([Ps,Er])=>{Er.adjustment!==void 0&&Er.adjustment!==0&&(ls[Ps]=Er.adjustment)}),Object.keys(ls).length>0&&(_t[oa.id]=ls)}),_t},Xe=_t=>{if(!Ke)return _t;const oa={..._t};for(const[ls,Ps]of Object.entries(Ae))oa[ls]={...oa[ls]||{},...Ps};return oa};he?(so.current=J,Ke&&(Xm.current=J),ml(Xe(mt()))):(Xm.current=J,ml(_t=>Xe(_t)))},[a,b]);const zu=o.useRef("");o.useEffect(()=>{if(h!=="str")return;const J=a.map(Ae=>`${Ae.id}:${Ae.strComparability||""}`).join(",");if(J===zu.current)return;zu.current=J;const he={};a.forEach(Ae=>{const Ke=Ae.strComparability;Ke&&["Superior","Similar","Inferior"].includes(Ke)&&(he[Ae.id]=Ke)}),Object.keys(he).length>0&&Km(Ae=>Object.entries(he).some(([ft,mt])=>Ae[ft]!==mt)?{...Ae,...he}:Ae)},[a,h]);const jo=o.useMemo(()=>{const J=new Map(a.map(he=>[he.id,he]));return Rg.map(he=>J.get(he)).filter(he=>he!==void 0)},[a,Rg]),$a=o.useMemo(()=>jo.filter(J=>!zi.has(J.id)).map(J=>{const he=Sd[J.id],Ae=J.fields.mlsNumber?.value,Ke=Ae==null||String(Ae).trim()===""?J.
39id:String(Ae),ft=$?LN(z,Ke):0;if((!he||Object.keys(he).length===0)&&ft===0)return J;const mt=new Set;Object.entries(he||{}).forEach(([lo])=>{const Si=$k[lo];Si&&Si.forEach(Bo=>mt.add(Bo))});const Xe=Object.entries(he||{}).filter(([lo])=>!Vp.has(lo)&&!mt.has(lo)),_t=Xe.reduce((lo,[,Si])=>lo+Si,0)+ft,oa=$?z.reduce((lo,Si)=>lo+Math.abs(Number(Si.adjustments?.[Ke])||0),0):0,ls=Xe.reduce((lo,[,Si])=>lo+Math.abs(Si),0)+oa,Ps=J.fields.salePrice?.value,Er=Ps!=null?typeof Ps=="number"?Ps:parseFloat(String(Ps).replace(/[^0-9.-]/g,"")):null,mn=Er!=null&&!isNaN(Er)?Er:null,vr=mn!=null?mn+_t:null,tn=mn!=null&&mn>0?(Math.abs(_t)/mn*100).toFixed(1):"0.0",An=mn!=null&&mn>0?(ls/mn*100).toFixed(1):"0.0";return{...J,fields:{...J.fields,netAdjustment:{value:_t,source:"AI",hasConflict:!1,isVerified:!0,displaySuffix:`${tn}%`},grossAdjustment:{value:ls,source:"AI",hasConflict:!1,isVerified:!0,displaySuffix:`${An}%`},adjustedSalePrice:{value:vr,source:"AI",hasConflict:!1,isVerified:!0}}}}),[jo,zi,Sd,$,z]),ci=o.useMemo(()=>[t,...$a],[t,$a]),um=o.useMemo(()=>$a.some(J=>Zf(Jo[J.id])!=="Auto"),[$a,Jo]),Wc=o.useMemo(()=>{if(h==="str")return null;const J=$a.map(he=>{const Ae=mt=>{if(mt==null)return null;const Xe=typeof mt=="number"?mt:parseFloat(String(mt).replace(/[^0-9.-]/g,""));return Number.isFinite(Xe)?Xe:null},Ke=Ae(he.fields.adjustedSalePrice?.value),ft=Ke!=null&&Ke>0?Ke:Ae(he.fields.salePrice?.value);return ft==null?null:{value:ft,weight:Zf(Jo[he.id])}}).filter(he=>he!=null);return um?a7(J):null},[h,$a,Jo,um]),yo=o.useMemo(()=>{if(!eo)return null;const J=ft=>{if(ft==null||ft==="")return null;const mt=typeof ft=="number"?ft:Number(String(ft).replace(/[^0-9.-]/g,""));return Number.isFinite(mt)&&mt>0?mt:null},he=$a.map(ft=>J(ft.fields.adjustedSalePrice?.value)).filter(ft=>ft!==null),Ae=$a.map(ft=>J(ft.fields.salePrice?.value)).filter(ft=>ft!==null),Ke=he.length>=2?he:Ae;return Ke.length===0?null:Math.round((Math.min(...Ke)+Math.max(...Ke))/2)},[eo,$a]);o.useEffect(()=>{if(!eo||!ae||!Zs||js!=null||oe&&Wr===""||Bc!=="suggested"||yo==null)return;B!=="suggested"&&_?.("suggested");const J=Number(Wr);Number.isFinite(J)&&J===yo||D?.(yo)},[Wr,Bc,eo,js,D,_,yo,ae,B,Zs]),o.useEffect(()=>{if(!eo&&ao.current&&ii==="suggested"){if(Wc==null||Wc<=0){h!=="str"&&um&&tm(J=>J===""?J:"");return}tm(J=>{const he=parseFloat(String(J).replace(/[^0-9.]/g,""));return Number.isFinite(he)&&he===Wc?J:String(Wc)})}},[eo,ii,Wc,h,um]);const Kr=o.useCallback(J=>{if(eo){const he=Number(J.replace(/[^0-9.-]/g,""));D?.(J.trim()!==""&&Number.isFinite(he)?he:null),_?.("manual");return}ao.current||(Td.current=!0,Vu.current=!0),tu.current=J,tm(J),Gm("manual")},[eo,D,_]),cu=o.useCallback(()=>{if(eo){_?.("suggested"),yo!=null&&D?.(yo);return}Gm("suggested")},[eo,D,_,yo]),bb=o.useMemo(()=>u8(t,jo,zi),[t,jo,zi]),{cascadeSubject:bc,cascadeComps:Cd,signature:Fg}=bb,_g=o.useCallback(J=>{vd(J.active.id)},[]),eh=o.useCallback(J=>{const{active:he,over:Ae}=J;vd(null),Ae&&he.id!==Ae.id&&hl(Ke=>{const ft=Ke.indexOf(he.id),mt=Ke.indexOf(Ae.id),Xe=k5(Ke,ft,mt);return Zm.current=Xe.join(","),m?.(Xe),Xe})},[m]),jp=o.useMemo(()=>ff&&a.find(J=>J.id===ff)||null,[ff,a]),ei=o.useCallback(J=>{em(he=>{const Ae=new Set(Array.from(he));return Ae.add(J),Ae})},[]),Ug=o.useCallback(J=>{em(he=>{const Ae=new Set(Array.from(he));return Ae.delete(J),Ae})},[]),Vg=o.useCallback(()=>{em(new Set)},[]);o.useMemo(()=>{let J=0,he=0,Ae=0;return ci.filter(ft=>!ft.isSubject).forEach(ft=>{Object.values(ft.fields).forEach(mt=>{Ae++,mt.hasConflict&&J++,mt.isVerified&&he++})}),{conflicts:J,verified:he,total:Ae}},[ci]),o.useCallback(J=>{Xp(he=>{const Ae=new Set(Array.from(he));return Ae.has(J)?Ae.delete(J):Ae.add(J),Ae})},[]);const tc=o.useCallback(J=>ci.some(he=>he.fields?.[J]?.hasConflict),[ci]),du=o.useCallback(J=>h==="str"||Vp.has(J)?!1:ci.some(he=>wm(he,J,h!=="str")),[ci,h]),uu=o.useCallback((J,he)=>{const Ae=he==="SiteInfluenceType"?"SiteInfluences":"SiteViews",Ke=(()=>{if(J.isSubject&&Be)return he==="SiteInfluenceType"?Be.influences:Be.views;const mt=J.fields?.[Ae];if(mt!==void 0){const ls=mt&&typeof mt=="object"&&"value"in mt?mt.value:mt;return Array.isArray(ls)?ls:[]}const Xe=he==="SiteInfluenceType"?"location":"view",_t=J.fields?.[he]!==void 0?he:Xe,oa=J.fields?.[_t]?.value;return oa!=null&&String(oa).trim()!==""?[{[he]:oa}]:[]})();if(Ke.length===0)return!0;
39const ft=he==="SiteInfluenceType"?"SiteInfluenceType":"ViewType";return!Ke.some(mt=>{if(!mt||typeof mt!="object")return!1;const Xe=mt[ft];return Xe!=null&&String(Xe).trim()!==""})},[Be]),yc=o.useCallback((J,he)=>{const Ae=A&&(he==="garageCarport"||he==="RenewableEnergyComponentType"||he==="GreenCertificationName"||he==="EfficiencyRatingName");if(h==="str"||!dg.has(he)&&!Ae||!A&&mM.has(he)||A&&CW.has(he))return!1;if(A&&(he==="SiteInfluenceType"||he==="ViewType"))return uu(J,he);if(A&&J.fields?.[he]===void 0){const mt=he==="OverallQualityRatingCode"?"quality":he==="OverallConditionRatingCode"?"condition":he==="SiteInfluenceType"?"location":he==="ViewType"?"view":void 0;if(mt&&J.fields?.[mt]!==void 0)return wm(J,mt,A)}if(A&&he==="garageCarport"){const mt=J.isSubject?fe:J.vehicleStorageItems??[];return(J.isSubject&&ue)!==!0&&!Px(mt,!J.isSubject)}const ft=A?{RenewableEnergyComponentType:"renewableComponents",GreenCertificationName:"greenCertifications",EfficiencyRatingName:"efficiencyRatings"}[he]:void 0;if(ft){if(!Ve||!Yi.some(Xe=>xh.get(Xe.rowId)===he&&Xe.relevant!==!1))return!1;const mt=J.isSubject?ne:J.fields?.EnergyFeatures?.value;return Jy(ft,Xy(mt)[ft],J.isSubject?"subject":"comparable")}return wm(J,he,A)},[A,h,ne,fe,ue,Yi,Ve,Xo,sa,uu]),wi=o.useCallback(J=>ci.some(he=>yc(he,J)),[ci,yc]),Rd=o.useMemo(()=>{if(h==="str")return[];if(!A)return Array.from(new Set([...TS(),...Mp(),...Array.from(A0)])).filter(he=>!Vp.has(he));const J=new Set(Wt.flatMap(he=>he.fields));for(const he of Array.from(A0))J.add(he);
39if(Wt.some(he=>he.id==="overallQc")&&(J.add("OverallQualityRatingCode"),J.add("OverallConditionRatingCode")),sa)for(const he of Xo)J.add(he.rowId);if(Wt.some(he=>he.id==="siteInfo")&&(J.add("SiteInfluenceType"),J.add("ViewType")),Ve)for(const he of Yi){const Ae=xh.get(he.rowId);Ae&&J.add(Ae)}return Array.from(J).filter(he=>!Vp.has(he))},[Wt,Yi,Ve,Xo,sa,A,TS,Mp,h]),$g=o.useMemo(()=>{const J=new Map;if(h==="str")return J;const he=A?Rd:Array.from(new Set([...Mp(),...Array.from(A0)])).filter(Ae=>!Vp.has(Ae));return $a.forEach(Ae=>{let Ke=0;he.forEach(mt=>{yc(Ae,mt)&&Ke++});const ft=Ae.fields;for(let mt=0;mt<=Vm;mt++){const Xe=ft[`saleHistory${mt}_OwnershipTransferDate`]?.value,_t=ft[`saleHistory${mt}_OwnershipTransferTransactionType`]?.value,oa=ft[`saleHistory${mt}_SaleType`]?.value;Xe&&String(Xe).trim()!==""&&_t==="Sale"&&(!oa||String(oa).trim()==="")&&Ke++}J.set(Ae.id,Ke)}),J},[A,Mp,h,yc,Rd,$a]),qu=Vr({queryKey:["/api/multi-method/locks",j],enabled:!!j,retry:!1}),[bl,Yu]=o.useState({}),[pm,Us]=o.useState({}),Kc=o.useRef(new Map),[yb,Pi]=o.useState(0),Lr=o.useRef(new Set),Qc=o.useRef(null);o.useEffect(()=>{Qc.current!==j&&(Yu({}),Lr.current=new Set,Qc.current=null)},[j]),o.useEffect(()=>{if(!j||!qu.data)return;const J={},he=new Set(Lr.current);for(const Ae of qu.data.locks){const Ke=typeof Ae.lockedRate=="number"?Ae.lockedRate:parseFloat(String(Ae.lockedRate));isFinite(Ke)&&(J[Ae.attributeKey]={rate:Ke,unit:Ae.rateUnit,lockId:Ae.id,method:Ae.method,dataset:Ae.dataset},he.add(Fm[Ae.attributeKey]))}Yu(Ae=>{const Ke={...J};for(const ft of Object.keys(pm))pm[ft]&&(Ae[ft]!==void 0?Ke[ft]=Ae[ft]:delete Ke[ft]);return Ke}),Lr.current=he,Qc.current=j},[j,qu.data,pm]);const Dl=["/api/time-adj/sessions",{assignmentId:j}],$o=Vr({queryKey:Dl,queryFn:async()=>{if(!j)return null;const J=await fetch(`/api/time-adj/sessions?assignmentId=${encodeURIComponent(j)}`,{credentials:"include"});if(J.status===404)return null;if(!J.ok)throw new Error(`Failed to load TimeVault session: ${J.status}`);return J.json()},enabled:!!j&&h!=="str",retry:!1}),Sc=o.useMemo(()=>{const J=$o.data;if(!J||!J.decisionSavedAt)return{isLocked:!1,label:void 0};if(J.selectedOption==="zero"||J.finalMethod==="zero")return{isLocked:!0,label:"0.00%/mo"};const he=J.linearRatePctPerMonth,Ae=typeof he=="string"?parseFloat(he):he;return Ae==null||!isFinite(Ae)?{isLocked:!1,label:void 0}:{isLocked:!0,label:`${Ae>=0?"+":""}${Ae.toFixed(2)}%/mo`}},[$o.data]),Wi=o.useMemo(()=>zk($o.data??null),[$o.data]),ti=o.useMemo(()=>qk($o.data??null),[$o.data]),sl=$o.data?.id??null,Ed=!!$o.data?.isLocked,Tp=!!$o.data?.derivedAt,Ip=!Ed||!Tp,[Cp,ro]=o.useState(!1),[vf,pu]=o.useState(null),mu=o.useCallback(async J=>{if(!sl){pu("Open the full wizard first to lock and derive a rate.");return}pu(null),ro(!0);try{const he=J.isRecommended?void 0:"Selected via chip-level method picker",Ae=await fetch(`/api/time-adj/sessions/${sl}/decision`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({selectedDataset:J.dataset,selectedMethod:J.method,...he?{overrideReason:he}:{},decisionSavedAt:new Date().toISOString()})});if(!Ae.ok){const Ke=await Ae.json().catch(()=>({}));throw new Error(Ke&&Ke.error||`Save failed (${Ae.status})`)}await fi.invalidateQueries({queryKey:Dl})}catch(he){pu(he instanceof Error?he.message:"Failed to save method")}finally{ro(!1)}},[sl,Dl]),hu=o.useCallback(async()=>{if(sl){pu(null),ro(!0);try{const J=await fetch(`/api/time-adj/sessions/${sl}/clear-decision`,{method:"POST",credentials:"include"});if(!J.ok){const he=await J.json().catch(()=>({}));throw new Error(he&&he.error||`Clear failed (${J.status})`)}await fi.invalidateQueries({queryKey:Dl})}catch(J){pu(J instanceof Error?J.message:"Failed to remove time adjustment")}finally{ro(!1)}}},[sl,Dl]),th=o.useCallback(async(J,he)=>{if(!sl)throw new Error("Open the full wizard first to lock and derive the time session.");const Ae=await fetch(`/api/time-adj/sessions/${sl}/decision`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({selectedDataset:$o.data?.selectedDataset??"submarket",selectedMethod:"manual",manualRatePctPerMonth:J,priceBasis:he,decisionSavedAt:new Date().toISOString()})});if(!Ae.ok){const Ke=await Ae.json().catch(()=>({}));throw new Error(Ke&&Ke.error||`Save failed (${Ae.status})`)}await fi.invalidateQueries({queryKey:Dl})},[sl,Dl,$o.data?.selectedDataset]),as=o.useMemo(()=>{const J=$o.data,he=J?.selectedMethod==="manual";let Ae="SALE";if(J?.overrideReason){const Xe=String(J.overrideReason).match(/\[basis:(CTR|SALE)\]/);Xe&&(Ae=Xe[1])}const Ke=J?.linearRatePctPerMonth,ft=typeof Ke=="string"?parseFloat(Ke):Ke,mt=he&&ft!=null&&Number.isFinite(ft)?ft:null;return{isManualLocked:!!he,basis:Ae,rate:mt}},[$o.data]),mm=Qc.current===j,fu=o.useCallback(J=>
39{if(!bc||Cd.length===0){Kc.current=new Map,Pi(Ke=>Ke+1);return}const he=r8(Object.fromEntries(Object.entries(J).map(([Ke,ft])=>[Ke,ft?{rate:ft.rate,unit:ft.unit}:void 0])),bc,Cd),Ae=new Map;he.forEach((Ke,ft)=>{const mt=ft.indexOf(":"),Xe=ft.slice(0,mt),_t=ft.slice(mt+1);xr.current.has(`${Xe}:${_t}`)||Ae.set(`${Xe}:${_t}`,Ke)}),Kc.current=Ae,Pi(Ke=>Ke+1)},[bc,Cd]),hm=o.useCallback((J,he)=>{if(!bc||Cd.length===0)return;he&&Lr.current.add(he);for(const Xe of Object.keys(J))J[Xe]&&Lr.current.add(Fm[Xe]);const Ae=new Set(Lr.current),Ke=KT(Object.fromEntries(Object.entries(J).map(([Xe,_t])=>[Xe,_t?{rate:_t.rate,unit:_t.unit}:void 0])),bc,Cd,Ae);if(fu(J),Ke.length===0)return;const ft=Ke.map(({compId:Xe,adjustments:_t})=>({compId:Xe,effectiveId:Xe,adjustments:_t})),mt=he?new Set([he]):void 0;if(mt&&mt.size>0){const Xe=[];if(ml(_t=>{for(const{effectiveId:oa,adjustments:ls}of ft){const Ps=_t[oa]??{};for(const[Er,mn]of Object.entries(ls)){if(!mt.has(Er))continue;const vr=`${oa}:${Er}`,tn=Ps[Er]??0;xr.current.has(vr)&&tn!==mn&&Xe.push({effectiveId:oa,field:Er,existing:tn,incoming:mn})}}return _t}),Xe.length>0){Bu({resolved:ft,conflicts:Xe,forceOverwriteFields:mt,fromChipCascade:!0});return}}Ea(ft,mt)},[bc,Cd,Ea,fu]),Fn=o.useCallback(()=>{if(!bc||Cd.length===0||Object.keys(bl).length===0||Lr.current.size===0)return;const J=new Set(Lr.current),he=KT(Object.fromEntries(Object.entries(bl).map(([Ke,ft])=>[Ke,ft?{rate:ft.rate,unit:ft.unit}:void 0])),bc,Cd,J);if(fu(bl),he.length===0)return;const Ae=he.map(({compId:Ke,adjustments:ft})=>({compId:Ke,effectiveId:Ke,adjustments:ft}));Ea(Ae)},[bc,Cd,bl,Ea,fu]),Zc=o.useRef(!0);o.useEffect(()=>{if(Zc.current){Zc.current=!1;return}Fn()},[Fg,bl]);const fm=o.useCallback(async(J,he,Ae)=>{if(j){Us(Ke=>({...Ke,[J]:!0}));try{const mt=(await(await Qo("POST","/api/multi-method/lock",{assignmentId:j,locks:[{attributeKey:J,lockedRate:he,rateUnit:Ae,method:"manual-c
39hip",dataset:"manual",sampleSize:0,confidence:"green",alternatives:[],wasRecommendationFollowed:!1}]})).json()).locks?.find(_t=>_t.attributeKey===J),Xe={...bl,[J]:{rate:he,unit:Ae,lockId:mt?.id??bl[J]?.lockId,method:mt?.method??"manual-chip",dataset:mt?.dataset??"manual"}};Yu(Xe),hm(Xe,Fm[J])}catch(Ke){console.error("[MasterRateChip] Apply failed:",Ke)}finally{Us(Ke=>({...Ke,[J]:!1}))}}},[j,bl,hm]),gm=o.useCallback(async J=>{const he=bl[J];if(he){Us(Ae=>({...Ae,[J]:!0}));try{he.lockId&&await Qo("DELETE",`/api/multi-method/locks/${he.lockId}`);const Ae={...bl};delete Ae[J],Yu(Ae),hm(Ae,Fm[J])}catch(Ae){console.error("[MasterRateChip] Clear failed:",Ae)}finally{Us(Ae=>({...Ae,[J]:!1}))}}},[bl,hm]),wn=o.useCallback((J,he,Ae)=>{const Ke=`${J}:${he}`;if(Ae===null){xr.current.delete(Ke),In.current.delete(Ke),Yn.current.delete(Ke),Qa.current.delete(Ke),lu(),ml(ft=>{const mt=ft[J];if(!mt||!(he in mt))return ft;const Xe={...mt};if(delete Xe[he],Object.keys(Xe).length===0){const _t={...ft};return delete _t[J],_t}return{...ft,[J]:Xe}}),p?.(J,he,null);return}xr.current.has(Ke)||(xr.current.add(Ke),lu()),ml(ft=>({...ft,[J]:{...ft[J],[he]:Ae}})),p?.(J,he,Ae)},[p,lu]),no=o.useCallback((J,he)=>{wn(J,he,null),queueMicrotask(()=>Fn())},[wn,Fn]),Pn=o.useCallback((J,he)=>Sd[J]?.[he]??0,[Sd]),ca=o.useCallback((J,he)=>Sd[J]?.[he]!==void 0,[Sd]),pn=o.useCallback(J=>{const he=J.fields?.salePrice?.value??J.fields?.soldPrice?.value??J.fields?.listPrice?.value;if(he==null)return null;const Ae=typeof he=="string"?parseFloat(he.replace(/[^0-9.-]/g,"")):Number(he);return isNaN(Ae)||Ae<=0?null:Ae},[]),io=o.useCallback((J,he)=>{if(h==="str"||Vp.has(he))return!1;if(he==="qualityCondition"){const mt=AS(xt??{}),Xe=AS(J.fields),_t=mt.quality!=null&&Xe.quality!=null&&mt.quality!==Xe.quality,oa=mt.condition!=null&&Xe.condition!=null&&mt.condition!==Xe.condition;return(_t||oa)&&!ca(J.id,he)}const Ae=mt=>String(mt??"").trim().toLowerCase(),Ke=Ae(xt?.[he]?.value);if(!Ke)return!1;const ft=Ae(J.fields?.[he]?.value);return!ft||ft===Ke?!1:!ca(J.id,he)},[h,xt,ca]),Rp=o.useCallback(J=>$a.some(he=>io(he,J)),[$a,io]),ah=o.useCallback(J=>Qa.current.size===0?!1:$a.some(he=>Qa.current.has(`${he.id}:${J}`)),[$a]),ac={dateOfSale:{rateKey:"marketPctYr",label:"%/yr",rateLabel:"Market change (% per year)",ratePlaceholder:"e.g. 3",hint:"Each comp is adjusted by the months between its sale and today × the annual market-conditions %.",thresholdUnit:"months since sale"},gla:{rateKey:"glaPerSf",label:"$/sf",rateLabel:"Rate ($ per sf)",ratePlaceholder:"e.g. 40",hint:"Dollars per square foot × (subject GLA − comp GLA), applied to every comp.",thresholdUnit:"sf",allowFlatBasis:!0},qualityCondition:{rateKey:"qcPct",rate2Key:"qcCondPct",label:"Q/C",rateLabel:"Quality rate per step",ratePlaceholder:"e.g. 3",rate2Label:"Condition rate per step",rate2Placeholder:"e.g. 2",hint:"Choose Percent or Dollars independently for Quality and Condition, then set the amount per rating step.",thresholdUnit:"rating steps"},aboveGrade:{rateKey:"roomsBedRate",rate2Key:"roomsBathRate",label:"$/bd·ba",rateLabel:"Rate ($ per bedroom)",ratePlaceholder:"e.g. 5000",rate2Label:"Rate ($ per bath)",rate2Placeholder:"e.g. 4000",hint:"Set $ per bedroom and per bath; applied from each comp’s bed/bath difference. Total room count is left alone.",thresholdUnit:"beds/baths"},BedroomCount:{rateKey:"roomsBedRate",rate2Key:"roomsBathRate",label:"$/bd·ba",rateLabel:"Rate ($ per bedroom)",ratePlaceholder:"e.g. 5000",rate2Label:"Rate ($ per bath)",rate2Placeholder:"e.g. 4000",hint:"Set $ per bedroom and per bath; adjustments are written to the Bedrooms, Baths–Full, and Baths–Half rows separately. Total room count is left alone.",thresholdUnit:"beds/baths"},basement:{rateKey:"basementFinRate",rate2Key:"basementUnfinRate",label:"$/sf",rateLabel:"Rate ($ per finished sf)",ratePlaceholder:"e.g. 30",rate2Label:"Rate ($ per unfinished sf)",rate2Placeholder:"e.g. 10",hint:"Set $ per finished and per unfinished sf; applied from each comp’s below-grade area difference.",thresholdUnit:"sf"},site:{rateKey:"sitePerSf",label:"$/sf",rateLabel:"Rate ($ per sf of site)",ratePlaceholder:"e.g. 2",hint:"Dollars per square foot of site area × (subject site − comp site). Acre values are converted to square feet automatically.",thresholdUnit:"sf",allowFlatBasis:!0},yearBuilt:{rateKey:"yearBuiltPerYr",label:"$/yr",rateLabel:"Rate ($ per year of age)",ratePlaceholder:"e.g. 1000",hint:"Dollars per year × (subject year built − comp year built): older comps adjust up toward a newer subject, newer comps adjust down.",thresholdUnit:"years",allowFlatBasis:!0},garageCarport:{rateKey:"garageSpaceRate",label:"$/space",rateLabel:"Rate ($ per vehicle storage space)",ratePlaceholder:"e.g. 5000",hint:"Dollars per space × (subject total spaces − comp total spaces), summed across all vehicle storage. “None” counts as 0 spaces.",thresholdUnit:"spaces",allowFlatBasis:!0},belowGrade:{rateKey:"bgBedRate",rate2Key:"bgBathRate",label:"$/bd·ba",rateLabel:"Rate ($ per below-grade bedroom)",ratePlaceholder:"e.g. 3000",rate2Label:"Rate ($ per below-grade bath)",rate2Placeholder:"e.g. 2500",hint:"Set $ per below-grade bedroom and per bath; applied from each comp’s below-grade room difference. Rec room count is left alone.",thresholdUnit:"beds/baths"}},sc={location:{rateKey:"flatLocation",label:"flat $",rateLabel:"Flat $ when location differs",ratePlaceholder:"e.g. 5000 or -5000",hint:"Applied as typed (sign included) to every comp whose location rating differs from the subject."},view:{rateKey:"flatView",label:"flat $",rateLabel:"Flat $ when view differs",ratePlaceholder:"e.g. 5000 or -5000",hint:"Applied as typed (sign included) to every comp whose view rating differs from the subject."},design:{rateKey:"flatDesign",label:"flat $",rateLabel:"Flat $ when design (style) differs",ratePlaceholder:"e.g. 3000 or -3000",hint:"Applied as typed (sign included) to every comp whose design/style differs from the subject."},functionalUtility:{rateKey:"flatFunctionalUtility",label:"flat $",rateLabel:"Flat $ when functional utility differs",ratePlaceholder:"e.g. 4000 or -4000",hint:"Applied as typed (sign included) to every comp whose functional utility differs from the subject."},heatingCooling:{rateKey:"flatHeatingCooling",label:"flat $",rateLabel:"Flat $ when heating/cooling differs",ratePlaceholder:"e.g. 2500 or -2500",hint:"Applied as typed (sign included) to every comp whose heating/cooling differs from the subject."},energyEfficient:{rateKey:"flatEnergyEfficient",label:"flat $",rateLabel:"Flat $ when energy-efficient items differ",ratePlaceholder:"e.g. 2000 or -2000",hint:"Applied as typed (sign included) to every comp whose energy-efficient items differ from the subject."},porchPatioDeck:{rateKey:"flatPorchPatioDeck",label:"flat $",rateLabel:"Flat $ when porch/patio/deck differs",ratePlaceholder:"e.g. 2000 or -2000",hint:"Applied as typed (sign included) to every comp whose porch/patio/deck differs from the subject."}},Bg=o.useCallback((J,he,Ae,Ke)=>
39{const ft=Number.isFinite(he)?he:0,mt=Number.isFinite(Ae)?Ae:0,Xe=!!sc[J];if(Xe?ft===0:!(ft>0)&&!(mt>0))return;const _t=Number.isFinite(Ke?.threshold)&&Ke.threshold>0?Ke.threshold:0,oa=Ke?.basis==="flat"?"flat":"perUnit",ls=wa=>oa==="flat"?TH(wa,ft):Math.round(ft*wa),Ps=new Date,Er=Ps.getMonth()+1,mn=Ps.getFullYear(),vr=lc(xt?.gla?.value),tn=AS(xt??{}),An=Rj(xt?.aboveGrade?.value),lo=eI(xt?.basement?.value),Si=a1(xt?.site?.value),Bo=lc(xt?.yearBuilt?.value),nl=wa=>wa.slice(0,12).reduce((di,us)=>{if(us.TenOrMoreParkingSpacesIndicator===!0)return di+10;const ks=Number(us.ParkingSpacesCount);return di+(Number.isFinite(ks)&&ks>=0?ks:0)},0),Ki=nt?nl(fe):s1(xt?.garageCarport?.value),rc=r1(xt?.belowGrade?.value),Ku=t1(xt?.aboveGrade?.value),wd=(()=>{const wa=lc(xt?.BedroomCount?.value);return Number.isFinite(wa)?wa:Ku.bedrooms})(),vc=(()=>{const wa=lc(xt?.FullBathroomCount?.value);return Number.isFinite(wa)?wa:Ku.fullBaths})(),nc=(()=>{const wa=lc(xt?.HalfBathroomCount?.value);return Number.isFinite(wa)?wa:Ku.halfBaths})(),_n=(wa,di,us)=>{if(!In.current.has(wa))return!1;const ks=ca(di,us)&&Pn(di,us)===In.current.get(wa);return ks||In.current.delete(wa),ks},To=(wa,di,us)=>!xr.current.has(wa)||_n(wa,di,us),So=(wa,di,us)=>{wn(wa,di,us),In.current.set(`${wa}:${di}`,us)};$a.forEach(wa=>{const di=pn(wa);if(J==="dateOfSale"){if(!di)return;const us=`${wa.id}:dateOfSale`;if(!To(us,wa.id,"dateOfSale"))return;const ks=NW(wa.fields?.dateOfSale?.value);if(ks){const On=nd((mn-ks.yr)*12+(Er-ks.mo),_t),ui=On>0?Math.round(di*(ft/100)*(On/12)):0;So(wa.id,"dateOfSale",ui)}}else if(J==="gla"){if(!Number.isFinite(vr))return;const us=`${wa.id}:gla`;if(!To(us,wa.id,"gla"))return;const ks=lc(wa.fields?.gla?.value);Number.isFinite(ks)&&So(wa.id,"gla",ls(nd(vr-ks,_t)))}else if(J==="qualityCondition"){const us=`${wa.id}:qualityCondition`;if(!To(us,wa.id,"qualityCondition"))return;const ks=AS(wa.fields),On=IH({subject:tn,comp:ks,salePrice:di,qualityRate:ft,conditionRate:mt,qualityBasis:Bi.quality,conditionBasis:Bi.condition,threshold:_t});if(On==null)return;So(wa.id,"qualityCondition",On)}else if(J==="aboveGrade"){const us=`${wa.id}:aboveGrade`;if(!To(us,wa.id,"aboveGrade"))return;const ks=Rj(wa.fields?.aboveGrade?.value),On=nd(Number.isFinite(An.bedrooms)&&Number.isFinite(ks.bedrooms)?An.bedrooms-ks.bedrooms:0,_t),ui=nd(Number.isFinite(An.bathrooms)&&Number.isFinite(ks.bathrooms)?An.bathrooms-ks.bathrooms:0,_t);(On!==0||ui!==0)&&So(wa.id,"aboveGrade",Math.round(ft*On+mt*ui))}else if(J==="BedroomCount"){const us=t1(wa.fields?.aboveGrade?.value),ks=(()=>{const Dr=lc(wa.fields?.BedroomCount?.value);return Number.isFinite(Dr)?Dr:us.bedrooms})(),On=(()=>{const Dr=lc(wa.fields?.FullBathroomCount?.value);return Number.isFinite(Dr)?Dr:us.fullBaths})(),ui=(()=>{const Dr=lc(wa.fields?.HalfBathroomCount?.value);return Number.isFinite(Dr)?Dr:us.halfBaths})(),Xc="catalog_BedroomCount_auto",Nc="catalog_FullBathroomCount_auto",Pd="catalog_HalfBathroomCount_auto";if(Number.isFinite(wd)&&Number.isFinite(ks)){const Dr=`${wa.id}:${Xc}`;if(To(Dr,wa.id,Xc)){const co=nd(wd-ks,_t),Od=In.current.has(Dr);co!==0?So(wa.id,Xc,Math.round(ft*co)):Od&&wn(wa.id,Xc,null)}}if(Number.isFinite(vc)&&Number.isFinite(On)){const Dr=`${wa.id}:${Nc}`;if(To(Dr,wa.id,Nc)){const co=nd(vc-On,_t),Od=In.current.has(Dr);co!==0?So(wa.id,Nc,Math.round(mt*co)):Od&&wn(wa.id,Nc,null)}}if(Number.isFinite(nc)&&Number.isFinite(ui)){const Dr=`${wa.id}:${Pd}`;if(To(Dr,wa.id,Pd)){const co=nd(nc-ui,_t),Od=In.current.has(Dr);co!==0?So(wa.id,Pd,Math.round(mt*.5*co)):Od&&wn(wa.id,Pd,null)}}}else if(J==="basement"){const us=`${wa.id}:basement`;if(!To(us,wa.id,"basement"))return;const ks=eI(wa.fields?.basement?.value),On=nd(Number.isFinite(lo.finished)&&Number.isFinite(ks.finished)?lo.finished-ks.finished:0,_t),ui=nd(Number.isFinite(lo.unfinished)&&Number.isFinite(ks.unfinished)?lo.unfinished-ks.unfinished:0,_t);(On!==0||ui!==0)&&So(wa.id,"basement",Math.round(ft*On+mt*ui))}else if(J==="site"){if(!Number.isFinite(Si))return;const us=`${wa.id}:site`;if(!To(us,wa.id,"site"))return;const ks=a1(wa.fields?.site?.value);Number.isFinite(ks)&&So(wa.id,"site",ls(nd(Si-ks,_t)))}else if(J==="yearBuilt"){if(!Number.isFinite(Bo))return;const us=`${wa.id}:yearBuilt`;if(!To(us,wa.id,"yearBuilt"))return;const ks=lc(wa.fields?.yearBuilt?.value);Number.isFinite(ks)&&So(wa.id,"yearBuilt",ls(nd(Bo-ks,_t)))}else if(J==="garageCarport"){if(!Number.isFinite(Ki))return;const us=nt?"VehicleStorage":"garageCarport",ks=`${wa.id}:${us}`;if(!To(ks,wa.id,us))return;const On=nt?nl(wa.vehicleStorageItems??[]):s1(wa.fields?.garageCarport?.value);Number.isFinite(On)&&So(wa.id,us,ls(nd(Ki-On,_t)))}else if(J==="belowGrade"){const us=`${wa.id}:belowGrade`;if(!To(us,wa.id,"belowGrade"))return;const ks=r1(wa.fields?.belowGrade?.value),On=nd(Number.isFinite(rc.bedrooms)&&Number.isFinite(ks.bedrooms)?rc.bedrooms-ks.bedrooms:0,_t),ui=nd(Number.isFinite(rc.bathrooms)&&Number.isFinite(ks.bathrooms)?rc.bathrooms-ks.bathrooms:0,_t);(On!==0||ui!==0)&&So(wa.id,"belowGrade",Math.round(ft*On+mt*ui))}else if(Xe){const us=`${wa.id}:${J}`;if(!To(us,wa.id,J))return;const ks=xt?.[J]?.value,On=wa.fields?.[J]?.value;if(ks==null||String(ks).trim()===""||On==null||String(On).trim()==="")return;So(wa.id,J,CH(ks,On)?Math.round(ft):0)}})},[t,$a,Bi,pn,wn,Pn,ca]),Sb=new Set(["catalog_BedroomCount_auto","catalog_FullBathroomCount_auto","catalog_HalfBathroomCount_auto"]),yl=o.useCallback(J=>{const he=J==="BedroomCount"?Sb:null;In.current.forEach((Ae,Ke)=>
39{const ft=Ke.indexOf(":");if(ft<0)return;const mt=Ke.slice(0,ft),Xe=Ke.slice(ft+1);(he?!he.has(Xe):Xe!==J)||(ca(mt,Xe)&&Pn(mt,Xe)===Ae&&no(mt,Xe),In.current.delete(Ke))})},[Pn,ca,no]),zg=o.useCallback(()=>{if(h==="str")return;const J=[];Mp().forEach(he=>{Vp.has(he)||$a.forEach(Ae=>{if(!io(Ae,he))return;const Ke=`${Ae.id}:${he}`;wn(Ae.id,he,0),In.current.set(Ke,0),Yn.current.add(Ke),Qa.current.add(Ke),J.push(Ke)})}),Ri(J.length>0?{cells:J}:null)},[h,$a,io,wn]),Gu=o.useCallback(J=>{h!=="str"&&Array.from(J).forEach(he=>{const Ae=he.indexOf(":");if(Ae<0){Yn.current.delete(he);return}const Ke=he.slice(0,Ae),ft=he.slice(Ae+1);ca(Ke,ft)&&Pn(Ke,ft)===0&&In.current.get(he)===0&&(no(Ke,ft),In.current.delete(he)),Yn.current.delete(he)})},[h,Pn,ca,no]),sh=o.useCallback(()=>{Gu(Yn.current)},[Gu]),gu=o.useMemo(()=>{let J=0;return Yn.current.forEach(he=>{const Ae=he.indexOf(":");if(Ae<0)return;const Ke=he.slice(0,Ae),ft=he.slice(Ae+1);ca(Ke,ft)&&Pn(Ke,ft)===0&&In.current.get(he)===0&&J++}),J},[Pn,ca]),rl=o.useMemo(()=>{const J=new Set;return Xi&&Xi.cells.forEach(he=>{const Ae=he.indexOf(":");if(Ae<0)return;const Ke=he.slice(0,Ae),ft=he.slice(Ae+1);ca(Ke,ft)&&Pn(Ke,ft)===0&&In.current.get(he)===0&&J.add(he)}),J},[Xi,Pn,ca]),Hu=o.useMemo(()=>{const J=[],he=new Set;return rl.forEach(Ae=>{const Ke=Ae.indexOf(":");if(Ke<0)return;const ft=Ae.slice(Ke+1);he.has(ft)||(he.add(ft),J.push(ft))}),J.sort((Ae,Ke)=>Mp().indexOf(Ae)-Mp().indexOf(Ke)).map(Ae=>({field:Ae,label:Ah(Ae,h,nt)}))},[rl,h,nt]),Nf=o.useCallback(()=>{Xi&&Gu(Xi.cells),Ri(null)},[Xi,Gu]);o.useEffect(()=>{(h==="str"||Je!=="grid"||yt!=="sales")&&Ri(null)},[h,Je,yt]);const _i=o.useCallback((J,he,Ae)=>{if(jo.forEach(Ke=>{r(Ke.id,J,he,Ae)}),J==="financingConcessions"){const{saleType:Ke,financing:ft,concessions:mt}=WD(he);jo.forEach(Xe=>{r(Xe.id,"saleType",Ke,Ae),r(Xe.id,"financing",ft,Ae),r(Xe.id,"concessions",mt,Ae)})}if(J==="porchPatioDeck"){const{amenityType:Ke}=yB(he);jo.forEach(ft=>{r(ft.id,"porchPatioDeck",he,Ae),r(ft.id,"amenityType",Ke,Ae)})}},[jo,r]),Af=o.useCallback((J,he,Ae)=>{jo.forEach(Ke=>{r(Ke.id,J,he,Ae)})},[jo,r]),oo=o.useCallback((J,he)=>{yd(J,he)},[yd]),Wu=o.useCallback((J,he)=>{Km(Ae=>({...Ae,[J]:he})),u?.(J,he)},[u]),Qr=h!=="str",hr=Qr&&!!j&&!!O,Hn=o.useMemo(()=>{const J=hr?"150px ":"";return Qr?`170px ${J}230px ${$a.map(()=>"170px 60px").join(" ")}`:`170px 170px ${$a.length>0?`repeat(${$a.length}, 170px)`:""}`},[Qr,hr,$a.length]),rh=o.useMemo(()=>{const J=hr?"150px ":"";return Qr?`170px ${J}230px ${$a.length>0?`repeat(${$a.length}, 230px)`:""}`:`170px 170px ${$a.length>0?`repeat(${$a.length}, 170px)`:""}`},[Qr,hr,$a.length]),xm=h==="str"?0:Mp().filter(J=>Rp(J)).length,nh=h==="str"?0:Rd.filter(wi).length,jf=(h==="str"?DP():[...TS(),...Mp()]).filter(J=>tc(J)).length,Tf=$?[...Pj].filter(J=>du(J)||tc(J)||Rp(J)).length:0,Jc=$?Mp().filter(J=>!gM.has(J)&&!Pj.has(J)&&(du(J)||tc(J)||Rp(J))).length:0;return e.jsx(gr,{children:e.jsxs("div",{className:"relative isolate h-full flex flex-col bg-white font-sans [&_h1]:font-sans [&_h2]:font-sans [&_h3]:font-sans [&_h4]:font-sans","data-testid":"sales-comparison-grid",children:[e.jsxs("div",{className:"shrink-0 border-b border-slate-200/80 px-4 py-1.5 flex items-center gap-3 bg-white/90 backdrop-blur-sm shadow-[0_1px_3px_rgba(0,0,0,0.04)]",children:[e.jsxs("div",{className:"inline-flex items-center rounded-md bg-slate-100 p-0.5 ring-1 ring-slate-200","data-testid":"toggle-grid-map",children:[at?e.jsxs(Qh,{children:[e.jsx(Zh,{asChild:!0,children:e.jsxs("button",{className:Q("flex items-center gap-1 rounded px-2.5 py-1 text-[11px] font-medium transition-colors",Je!=="map"?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-700"),"data-testid":"button-grid-view",children:[e.jsx(tT,{className:"w-3.5 h-3.5"}),yt==="sales"?"Grid":yt==="rental"?"Rental":"GRM",e.jsx(Rr,{className:"w-3 h-3 opacity-60"})]})}),e.jsxs(Jh,{align:"start",className:"min-w-[9rem]",children:[Ue&&e.jsx(Yl,{onClick:()=>gs("sales"),"data-testid":"menu-grid-sales",children:"Sales grid"}),It&&e.jsx(Yl,{onClick:()=>gs("rental"),"data-testid":"menu-grid-rental",children:"Rental grid"}),Ne&&e.jsx(Yl,{onClick:()=>gs("grm"),"data-testid":"menu-grid-grm",children:"GRM grid"})]})]}):e.jsxs("button",{onClick:()=>Kt("grid"),className:Q("flex items-center gap-1 rounded px-2.5 py-1 text-[11px] font-medium transition-colors",Je==="grid"?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-700"),"data-testid":"button-grid-view",children:[e.jsx(tT,{className:"w-3.5 h-3.5"}),yt==="sales"?"Grid":yt==="rental"?"Rental":"GRM"]}),e.jsxs("button",{onClick:()=>Kt("map"),className:Q("flex items-center gap-1 rounded px-2.5 py-1 text-[11px] font-medium transition-colors",Je==="map"?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-700"),"data-testid":"button-map-view",children:[e.jsx(mN,{className:"w-3.5 h-3.5"}),"Map"]})]}),A&&j&&j!=="new"&&h!=="str"&&e.jsx(J8,{orderId:j,enableUad36:A,occupancy:le,unitCount:W,variant:"compact"}),h!=="str"&&Je==="grid"&&yt==="sales"&&e.jsxs("button",{type:"button",onClick:()=>{Qa.current.clear(),Ri(null),Zt(J=>!J)},"aria-pressed":ds,"data-testid":"switch-needs-adjustment",title:"Rows where a comp differs from the subject but no dollar adjustment or comment is entered yet, plus rows still missing data.",className:Q("flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium ring-1 transition-colors",ds?"bg-amber-100 text-amber-800 ring-amber-300":"bg-white text-slate-600 ring-slate-200 hover:bg-slate-50"),children:["Needs adjustment",e.jsx("span",{className:Q("rounded-full px-1.5 text-[10px] font-semibold",ds?"bg-white/70":"bg-slate-100 text-slate-500"),children:xm})]}),h!=="str"&&Je==="grid"&&yt==="sales"&&ds&&xm>0&&e.jsx("button",{type:"button",onClick:zg,"data-testid":"button-apply-zero-needs-adjustment",title:"Fill $0 into every cell that still needs adjustment — where a comp differs from the subject but no adjustment is entered yet. Never overrides existing values; a later Auto-adjust can still replace these $0 placeholders.",className:"flex items-center gap-1 rounded-md bg-amber-50 px-2 py-1 text-[11px] font-medium text-amber-700 ring-1 ring-amber-200 transition-colors hover:bg-amber-100",children:"Apply $0 to all"}),h!=="str"&&Je==="grid"&&yt==="sales"&&ds&&gu>0&&e.jsx("button",{type:"button",onClick:sh,"data-testid":"button-clear-zero-needs-adjustment",title:"Remove the $0 placeholders that 'Apply $0 to all' just wrote. Hand-typed values and computed Auto-adjust results are left untouched.",className:"flex items-center gap-1 rounded-md bg-white px-2 py-1 text-[11px] font-medium text-amber-700 ring-1 ring-amber-200 transition-colors hover:bg-amber-50",children:"Clear the $0s"}),h!=="str"&&Je==="grid"&&yt==="sales"&&ds&&rl.size>0&&e.jsxs("div",{"data-testid":"zero-apply-summary",className:"flex items-center gap-1.5 rounded-md bg-sky-50 px-2 py-1 text-[11px] font-medium text-sky-800 ring-1 ring-sky-200",children:[e.jsxs("span",{"data-testid":"text-zero-apply-summary",children:["Filled $0 into ",rl.size," ",rl.size===1?"cell":"cells"," across"," ",Hu.length," ",Hu.length===1?"field":"fields"]}),Hu.length>0&&e.jsxs(xn,{children:[e.jsx(bn,{asChild:!0,children:e.jsx("button",{type:"button","data-testid":"button-zero-apply-fields",className:"inline-flex items-center gap-0.5 rounded px-1 py-0.5 text-sky-700 underline decoration-dotted underline-offset-2 hover:bg-sky-100",children:"view fields"})}),e.jsxs(yn,{align:"start",className:"w-56 p-2 text-xs",children:[e.jsx("p",{className:"mb-1 font-semibold text-slate-700",children:"Fields filled with $0"}),e.jsx("ul",{className:"space-y-0.5","data-testid":"list-zero-apply-fields",children:Hu.map(({field:J,label:he})=>e.jsx("li",{"data-testid":`item-zero-apply-field-${J}`,className:"text-slate-600",children:he},J))})]})]}),e.jsx("span",{className:"text-sky-300",children:"·"}),e.jsx("button",{type:"button",onClick:Nf,"data-testid":"button-undo-zero-apply",title:"Undo this bulk fill — removes only the $0 placeholders it just wrote. Hand-typed values and computed Auto-adjust results are left untouched.",className:"inline-flex items-center gap-0.5 rounded px-1 py-0.5 font-semibold text-sky-700 hover:bg-sky-100",children:"Undo"})]}),h!=="str"&&Je==="grid"&&yt==="sales"&&e.jsxs("button",{type:"button",onClick:()=>Sn(J=>
39!J),"aria-pressed":xs,"data-testid":"switch-missing-only",title:"Rows with a missing required value for at least one property.",className:Q("flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium ring-1 transition-colors",xs?"bg-rose-100 text-rose-800 ring-rose-300":nh>0?"bg-rose-50 text-rose-700 ring-rose-200 hover:bg-rose-100":"bg-white text-slate-600 ring-slate-200 hover:bg-slate-50"),children:["Required",e.jsx("span",{className:Q("rounded-full px-1.5 text-[10px] font-semibold",xs?"bg-white/70":nh>0?"bg-rose-100 text-rose-700":"bg-slate-100 text-slate-500"),children:nh})]}),Je==="grid"&&yt==="sales"&&e.jsxs("button",{type:"button",onClick:()=>Mr(J=>!J),"aria-pressed":Va,"data-testid":"switch-conflicts-only",title:"Rows where two sources disagree on a value.",className:Q("flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium ring-1 transition-colors",Va?"bg-slate-200 text-slate-800 ring-slate-300":"bg-white text-slate-600 ring-slate-200 hover:bg-slate-50"),children:["Conflicts only",e.jsx("span",{className:Q("rounded-full px-1.5 text-[10px] font-semibold",Va?"bg-white/70":"bg-slate-100 text-slate-500"),children:jf})]}),Je==="grid"&&yt==="sales"&&e.jsx("span",{className:"h-5 w-px bg-slate-200"}),Je==="grid"&&yt==="sales"&&$a.length>0&&e.jsxs("span",{className:"rounded-full px-2 py-0.5 text-[10px] font-semibold bg-slate-100 text-slate-500","data-testid":"chip-comp-count",children:[$a.length," comp",$a.length!==1?"s":""]}),h!=="str"&&Je==="grid"&&yt==="sales"&&e.jsxs("button",{type:"button","data-testid":"button-auto-adjust",onClick:()=>fd(J=>(J&&bd(null),!J)),title:"Show per-row auto-adjusters — set one rate (e.g. $40/sf or 3%/yr) and apply it consistently across every comp. For market-derived rates, use Run Adjustments.",className:Q("flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium ring-1 transition-colors",zn?"bg-blue-600 text-white ring-blue-600":"bg-white text-slate-600 ring-slate-300 hover:text-blue-700"),children:[e.jsx(Bx,{className:"w-3.5 h-3.5"}),"Auto-adjust"]}),h==="str"&&e.jsxs(De,{variant:"outline",size:"sm",onClick:()=>Gn(!0),className:"text-slate-600 gap-1 h-7 text-xs","data-testid":"button-str-guidance",children:[e.jsx(on,{className:"w-3.5 h-3.5"}),"Guide"]}),x&&Object.keys(x).length>0&&e.jsxs(kt,{variant:"outline",className:"text-[10px] text-indigo-600 border-indigo-200 bg-indigo-50/50 gap-1 cursor-default","data-testid":"badge-advisor-active",children:[e.jsx(M5,{className:"w-3 h-3"}),"Advisor Active"]}),e.jsx("div",{className:"flex-1"}),h!=="str"&&Je==="grid"&&yt==="sales"&&U,h!=="str"&&Je==="grid"&&yt==="sales"&&G,A&&j&&h!=="str"&&e.jsx(RI,{orderId:j,sectionId:"salesComparison",label:"Sales Comparison",commentFieldName:"SalesComparisonCommentText"}),e.jsxs(De,{size:"sm",onClick:n,className:"h-7 text-xs gap-1 bg-blue-600 hover:bg-blue-700","data-testid":"button-continue",children:["Continue",e.jsx(Zp,{className:"w-3.5 h-3.5"})]})]}),Qr&&Je==="grid"&&yt==="sales"&&C,$&&Je==="grid"&&yt==="sales"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-slate-200 bg-slate-50/80 px-4 py-2","data-testid":"eval-sales-grid-disclosure",children:[e.jsx("span",{className:"mr-1 text-[10px] font-semibold uppercase tracking-wide text-slate-500",children:"EVAL view"}),e.jsxs("button",{type:"button","aria-expanded":Gs,onClick:()=>bs(J=>!J),"data-testid":"button-eval-adjustment-details",className:Q("inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium ring-1 transition-colors",Gs?"bg-blue-600 text-white ring-blue-600":"bg-white text-slate-700 ring-slate-200 hover:bg-slate-100"),children:[Gs?e.jsx(Rr,{className:"h-3.5 w-3.5"}):e.jsx(fo,{className:"h-3.5 w-3.5"}),"Detailed adjustments",Jc>0&&e.jsx("span",{className:Q("rounded-full px-1.5 text-[10px] font-semibold",Gs?"bg-white/20 text-white":"bg-amber-100 text-amber-800"),"data-testid":"badge-eval-adjustment-attention",title:"Adjustment fields needing review",children:Jc})]}),e.jsxs("button",{type:"button","aria-expanded":xa,onClick:()=>rs(J=>!J),"data-testid":"button-eval-source-details",className:Q("inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-medium ring-1 transition-colors",xa?"bg-blue-600 text-white ring-blue-600":"bg-white text-slate-700 ring-slate-200 hover:bg-slate-100"),children:[xa?e.jsx(Rr,{className:"h-3.5 w-3.5"}):e.jsx(fo,{className:"h-3.5 w-3.5"}),"Source details",Tf>0&&e.jsx("span",{className:Q("rounded-full px-1.5 text-[10px] font-semibold",xa?"bg-white/20 text-white":"bg-amber-100 text-amber-800"),"data-testid":"badge-eval-source-attention",title:"Source fields needing review",children:Tf})]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:"Report-facing facts stay visible; secondary fields remain saved and available here when needed."})]}),f==="after-repaired"&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-1.5 bg-amber-50/80 border-b border-amber-200/60 text-amber-700","data-testid":"banner-after-repaired",children:[e.jsx(on,{className:"w-3.5 h-3.5 shrink-0"}),e.jsx("span",{className:"text-xs",children:"After-Repaired: Click subject values to set post-renovation improvements"})]}),Je==="map"?e.jsx("div",{className:"flex-1 min-h-0","data-testid":"map-view-container",children:e.jsx(x8,{subject:t,comps:jo,adjustments:Sd,onSnapshotChange:y,onCompLocationUpdate:(J,he,Ae,Ke)=>{r(J,"distance",Ke,"User")},onCompClick:l})}):ct&&yt!=="sales"&&j?e.jsx(W8,{orderId:j,variant:yt,onActiveCompCount:J=>{yt==="rental"?tr(J):zs(J)},subjectCoordinates:t.lat!=null&&t.lng!=null?{lat:t.lat,lng:t.lng}:null,subjectAddress:{AddressLineText:t.address},maxRentalComps:yt==="rental"?12:void 0}):e.jsx("div",{className:"flex-1 min-h-0 overflow-auto","data-testid":"grid-scroll-container",onScroll:gy,children:e.jsx(F5,{sensors:Sf,collisionDetection:_5,onDragStart:_g,onDragEnd:eh,children:e.jsxs("div",{className:"min-w-max",children:[e.jsxs("div",{ref:qm,className:"grid sticky top-0 z-10 bg-slate-50/80 backdrop-blur-sm border-b border-slate-200/80 shadow-[0_1px_2px_rgba(0,0,0,0.04)]",style:{gridTemplateColumns:rh},children:[e.jsxs("div",{className:Q("px-4 flex flex-col items-start justify-between gap-2 transition-[padding] duration-300 motion-reduce:transition-none sticky left-0 z-20 bg-slate-50",gc?"py-2":"py-4"),children:[e.jsx("span",{className:"text-[12px] font-semibold text-slate-500 uppercase tracking-[0.06em] leading-tight",children:gc?"Property Details":e.jsxs(e.Fragment,{children:["Property",e.jsx("br",{}),"Details"]}
39)}),e.jsxs("div",{className:"flex flex-col gap-1.5 w-full",children:[!gc&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>xb(J=>!J),className:"flex items-center gap-1 text-[10px] text-slate-400 hover:text-slate-600 transition-colors","data-testid":"toggle-expand-all",title:Bm?"Collapse all cards":"Expand all cards",children:Bm?e.jsx(WR,{className:"w-3.5 h-3.5"}):e.jsx(KR,{className:"w-3.5 h-3.5"})}),h!=="str"&&Je==="grid"&&yt==="sales"&&e.jsx("button",{type:"button",onClick:()=>{Xl(MS.every(J=>ou.has(J))?new Set:new Set(MS))},"aria-pressed":MS.every(J=>ou.has(J)),"data-testid":"button-toggle-condensed-all",title:"Split every condensed line into its individual rows, or condense them all back.",className:"flex items-center gap-1 text-[10px] text-slate-400 hover:text-slate-600 transition-colors",children:MS.every(J=>ou.has(J))?e.jsxs(e.Fragment,{children:[e.jsx(WR,{className:"w-3.5 h-3.5"}),"Condense"]}):e.jsxs(e.Fragment,{children:[e.jsx(KR,{className:"w-3.5 h-3.5"}),"Split"]})})]}),Je==="grid"&&yt==="sales"&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[9px] font-medium text-slate-500","data-testid":"source-legend",children:[e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-sky-500"}),"MLS"]}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-amber-500"}),"PR"]}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-emerald-500"}),"AI"]}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-violet-500"}),h==="str"?"Inspection":"User"]}),h==="str"&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-rose-500"}),"Airbnb"]})]})]})]}),hr&&e.jsxs("div",{className:Q("px-3 flex flex-col items-start justify-start transition-[padding] duration-300 motion-reduce:transition-none sticky left-[170px] z-20 bg-slate-50",gc?"py-2":"py-4"),"data-testid":"master-rate-header",children:[e.jsx("span",{className:"text-[12px] font-semibold text-slate-500 uppercase tracking-[0.06em] leading-tight",children:gc?"Master Rate":e.jsxs(e.Fragment,{children:["Master",e.jsx("br",{}),"Rate"]})}),!gc&&e.jsx("span",{className:"text-[10px] text-slate-400 mt-0.5",children:"$ / unit"})]}),e.jsx("div",{className:"sticky z-20 bg-slate-50 overflow-hidden",style:{left:hr?"320px":"170px"},children:e.jsx(aI,{property:t,index:0,onPhotoClick:()=>{if(l)l(t);else{const J=t.photos||(t.photoUrl?[t.photoUrl]:[]),he=fp[t.id]||t.primaryPhotoUrl||J[0];J.length&&ki({photos:J,address:t.address,orderId:j,isSubject:!0,coverPhotoUrl:he})}},allExpanded:Bm,onFieldUpdate:r,coverPhotoUrl:fp[t.id]||t.primaryPhotoUrl,onSubjectPhotoUpload:j?async J=>{const{preprocessImage:he}=await ri(async()=>{const{preprocessImage:mt}=await import("./uad36ImagePreprocess-5jaGBucA.js");return{preprocessImage:mt}},[]),Ke=(await he(J)).dataUrl,ft=await fetch(`/api/orders/${j}/subject-photos`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({photoUrls:[Ke],source:"User"})});if(!ft.ok){console.error("[SubjectUpload] failed:",ft.status,await ft.text().catch(()=>""));return}Ol(mt=>({...mt,[t.id]:Ke})),fi.invalidateQueries({queryKey:["/api/orders",j,"subject-photos"]})}:void 0,compact:gc,uad36Active:nt,b1GatingActive:nt})}),e.jsx(U5,{items:$a.map(J=>J.id),strategy:V5,children:$a.map((J,he)=>e.jsx("div",{className:"overflow-hidden isolate",children:e.jsx(DW,{property:J,index:he+1,onPhotoClick:()=>{if(l)l(J);else{const Ae=J.photos||(J.photoUrl?[J.photoUrl]:[]),Ke=J.snapshotId?Ig[J.snapshotId]||[]:[],ft=[...Ae,...Ke],mt=fp[J.id]||J.primaryPhotoUrl||ft[0];(ft.length||J.snapshotId)&&ki({photos:ft,address:J.address,compSnapshotId:J.snapshotId,orderId:j,coverPhotoUrl:mt})}},onHide:()=>ei(J.id),onReplace:c?()=>c(J.id):void 0,onRemove:d?()=>
39d(J):void 0,allExpanded:Bm,onFieldUpdate:r,coverPhotoUrl:fp[J.id]||J.primaryPhotoUrl,missingCount:$g.get(J.id),compact:gc,uad36Active:nt,b1GatingActive:nt,onComparableProjectClassificationChange:zt,onComparableStructuresChange:Ua})},J.id))})]}),e.jsx($5,{children:jp?e.jsx("div",{style:{width:Qr?230:170},children:e.jsx(aI,{property:jp,index:$a.findIndex(J=>J.id===jp.id)+1,onPhotoClick:()=>{},isDragging:!0,allExpanded:Bm})}):null}),zi.size>0&&e.jsxs("div",{className:"sticky top-0 z-10 flex items-center gap-2 px-4 py-1.5 bg-slate-100/80 border-b border-slate-200/60 text-slate-600","data-testid":"hidden-comps-banner",children:[e.jsx(XO,{className:"w-3.5 h-3.5 shrink-0 text-slate-400"}),e.jsxs("span",{className:"text-xs",children:[zi.size," comp",zi.size>1?"s":""," hidden"]}),e.jsx("div",{className:"flex items-center gap-1.5 ml-1 flex-wrap",children:Array.from(zi).map(J=>{const he=jo.find(Ae=>Ae.id===J);return he?e.jsxs("button",{onClick:()=>Ug(J),className:"flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-white border border-slate-200 hover:bg-slate-50 text-slate-600 transition-colors","data-testid":`button-unhide-comp-${J}`,title:`Show ${he.address}`,children:[e.jsx(of,{className:"w-2.5 h-2.5"}),he.address.split(",")[0]]},J):null})}),e.jsx("button",{onClick:Vg,className:"ml-auto text-[10px] font-medium text-blue-600 hover:text-blue-800 transition-colors","data-testid":"button-show-all-comps",children:"Show all"})]}),(()=>{const J=new Set(TS()),he=w=>{if(nt&&w==="listPrice")return e.jsxs("div",{className:"grid border-b border-slate-200 bg-slate-50/40 transition-colors hover:bg-blue-50/40",style:{gridTemplateColumns:Hn},"data-testid":"row-reference-listingDetails",children:[e.jsx("div",{className:"sticky left-0 z-[2] flex w-[170px] min-w-[170px] items-center bg-slate-50 px-3 py-[5px]",children:e.jsxs("span",{className:"whitespace-normal break-words text-[12px] font-medium leading-tight text-slate-700",title:"Listing Status | Price | DOM",children:["Listing Status ",e.jsx("span",{className:"mx-1 text-slate-700",children:"|"})," Price ",e.jsx("span",{className:"mx-1 text-slate-700",children:"|"})," DOM"]})}),hr&&e.jsx("div",{className:"flex items-center border-r border-slate-200 px-2 py-[5px] text-[10px] text-slate-300",children:e.jsx(kn,{state:"blank"})}),e.jsx(c1,{property:t,stickyLeft:hr?"320px":"170px",onFieldUpdate:r,onSetPreference:oo,onCopyToAllComps:(ia,Ca,Ls)=>_i(ia,Ca,Ls),preferredSource:Zo("listPrice"),gridMode:h,uad36:nt,subjectCanonicalFields:A?ya:void 0}),$a.map((ia,Ca)=>e.jsxs(Mn.Fragment,{children:[e.jsx(c1,{property:ia,isFirstComp:Ca===0,comparableSequence:Ca+1,onFieldUpdate:r,onSetPreference:oo,onCopyToAllComps:(Ls,Qs,Lt)=>_i(Ls,Qs,Lt),preferredSource:Zo("listPrice"),gridMode:h,uad36:nt}),Qr&&e.jsx("div",{className:"w-[60px] min-w-[60px] px-1.5 py-[5px]"})]},ia.id))]},"ref-listing-details");const wt=tc(w),Pt=nt&&w==="proximity";Pt||wi(w);const Ba=$&&w==="salePricePerGLA",Ts=nt?{interiorQuality:"interiorCondition",exteriorQuality:"exteriorCondition"}[w]:void 0;return e.jsxs("div",{className:Q("grid border-b border-slate-200 transition-colors duration-100",wt?"bg-amber-50/40 hover:bg-amber-50/60":"bg-slate-50/40 hover:bg-slate-50"),style:{gridTemplateColumns:Hn},"data-testid":`row-reference-${w}`,onFocus:()=>qs(w),onBlur:ia=>Ks(w,ia),children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-center gap-1.5 w-[170px] min-w-[170px] bg-slate-50 sticky left-0 z-[2]",children:[e.jsx("span",{className:"text-[12px] font-medium text-slate-700 whitespace-nowrap",children:Ba?"Price per SF":Ah(w,h,nt)}),it&&!nt&&!(nt&&w==="garageCarport")&&!(nt&&Qp.has(w))&&!(nt&&Yo[w])&&e.jsx(Fs,{section:"salesGrid",fieldName:w}),wt&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"})]}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200 text-[10px] text-slate-300 flex items-center",children:e.jsx(kn,{state:"blank"})}),$&&w==="neighborhoodName"||aK(w,{b1GatingActive:Xe,isEvalPricePerSf:Ba})?e.jsx("div",{className:Q("sticky z-[2] h-full min-h-8 self-stretch",Ob(w)?"bg-slate-100":Gl({fieldName:w,isMissing:wm(t,w,nt)})),"data-testid":`subject-surface-${w}`,style:{left:hr?"320px":"170px"},children:Ba?e.jsx("div",{className:"flex h-full min-h-8 items-center border-l border-slate-200 px-3 text-xs font-normal leading-5 text-slate-700","aria-readonly":"true",title:"Calculated from sale price and finished above-grade area","data-testid":"cell-subject-salePricePerGLA-derived",children:o1(t)}):Ts?e.jsx(ju,{property:t,showMissing:h!=="str",qualityField:w,conditionField:Ts,onUpdateQuality:(ia,Ca)=>r(t.id,w,ia,Ca),onUpdateCondition:(ia,Ca)=>r(t.id,Ts,ia,Ca)}):Ob(w)?e.jsx("div",{className:"h-full min-h-8 self-stretch px-1.5 py-[5px] flex items-center justify-center bg-slate-100 select-none","aria-disabled":"true","data-testid":`subject-na-${w}`,title:"Comparable-only fact — not applicable to the Subject (UAD 3.6 B-1)",children:e.jsx(kn,{state:"gray"})}):e.jsx(jh,{property:t,fieldName:w,editableText:$&&w==="neighborhoodName",fieldDataOverride:nt&&!$?Lx(t,w):void 0,onUpdate:(ia,Ca)=>
39r(t.id,w,ia,Ca),onFieldUpdate:r,onSetPreference:oo,preferredSource:Zo(w),gridMode:h,activeScenario:f,showMissing:!0,uad36:nt,inspectSection:nt&&Yo[w]||nt&&Qp.has(w)?"subjectProperty":void 0,inspectFieldName:nt?Yo[w]??Pm[w]:void 0})}):e.jsx("div",{className:"sticky z-[2] bg-slate-100",style:{left:hr?"320px":"170px"},"aria-disabled":"true","data-testid":`subject-na-reference-${w}`}),$a.map((ia,Ca)=>{const Ls=Qr&&(w==="salePrice"||Pt);return e.jsxs(Mn.Fragment,{children:[Ba?e.jsx("div",{className:Q("flex min-h-8 items-center px-3 text-[11px] font-medium tabular-nums text-slate-700",Ca===0?"border-l-2 border-l-slate-300":"border-l border-slate-200"),"aria-readonly":"true",title:"Calculated from sale price and finished above-grade area","data-testid":`cell-comp-salePricePerGLA-derived-${ia.id}`,children:o1(ia)}):Ts?e.jsx(ju,{property:ia,isFirstComp:Ca===0,showMissing:h!=="str",qualityField:w,conditionField:Ts,onUpdateQuality:(Qs,Lt)=>r(ia.id,w,Qs,Lt),onUpdateCondition:(Qs,Lt)=>r(ia.id,Ts,Qs,Lt),onCopyQualityToAll:(Qs,Lt)=>_i(w,Qs,Lt),onCopyConditionToAll:(Qs,Lt)=>_i(Ts,Qs,Lt),fallbackQuality:w==="interiorQuality"&&ia.fields.quality?.value!=null?String(ia.fields.quality.value):null,fallbackCondition:w==="interiorQuality"&&ia.fields.condition?.value!=null?String(ia.fields.condition.value):null}):Ls?e.jsx("div",{className:"col-span-2 h-full self-stretch","data-testid":Pt?`proximity-full-width-cell-${ia.id}`:`cell-comp-salePrice-fullwidth-${ia.id}`,children:e.jsx(jh,{property:ia,fieldName:w,displayDash:nt&&!$&&w==="salePrice"&&j0(ia)!=="Sale",testIdOverride:nt&&!$&&w==="salePrice"&&j0(ia)!=="Sale"&&ia.transferHistory?.length?`cell-${ia.id}-salePrice-dash`:void 0,fieldDataOverride:nt&&!$?Lx(ia,w):void 0,isFirstComp:Ca===0,comparableSequence:Ca+1,onUpdate:(Qs,Lt)=>r(ia.id,w,Qs,Lt),onFieldUpdate:r,onCopyToAllComps:(Qs,Lt)=>_i(w,Qs,Lt),onCopyCompanionToAllComps:Pt?Af:void 0,onSetPreference:oo,preferredSource:Zo(w),gridMode:h,showMissing:!Pt,uad36:nt,inspectSection:nt&&(Pt||Yo[w]||Qp.has(w))?"salesComparison":void 0,inspectFieldName:Pt?Zi(ia.id,"fields.ProximityToSubjectDistanceLinearMeasure"):nt&&Yo[w]?Zi(ia.id,`transferHistory.0.${Yo[w]}`):nt&&Pm[w]?Zi(ia.id,`fields.${Pm[w]}`):void 0,inspectLabel:Pt?`Comp ${Ca+1} · ${Tx(w)}`:nt&&(Yo[w]||Pm[w])?`Comp ${Ca+1} · ${Tx(w)}`:void 0})}):e.jsx(jh,{property:ia,fieldName:w,editableText:$&&w==="neighborhoodName",displayDash:nt&&!$&&w==="salePrice"&&j0(ia)!=="Sale",testIdOverride:nt&&!$&&w==="salePrice"&&j0(ia)!=="Sale"&&ia.transferHistory?.length?`cell-${ia.id}-salePrice-dash`:void 0,fieldDataOverride:nt&&!$?Lx(ia,w):void 0,isFirstComp:Ca===0,comparableSequence:Ca+1,onUpdate:(Qs,Lt)=>r(ia.id,w,Qs,Lt),onFieldUpdate:r,onCopyToAllComps:(Qs,Lt)=>_i(w,Qs,Lt),onSetPreference:oo,preferredSource:Zo(w),gridMode:h,showMissing:!0,uad36:nt,inspectSection:nt&&(Yo[w]||Qp.has(w))?"salesComparison":void 0,inspectFieldName:nt?Yo[w]?Zi(ia.id,`transferHistory.0.${Yo[w]}`):Pm[w]?Zi(ia.id,`fields.${Pm[w]}`):void 0:void 0}),Qr&&!Ls&&e.jsx("div",{className:"w-[60px] min-w-[60px] self-stretch bg-transparent","aria-hidden":"true","data-testid":`adj-na-${w}-${ia.id}`})]},ia.id)})]},`ref-${w}`)},Ae=(w,wt)=>{const Pt=ia=>wt.map(Ca=>{const Ls={};for(const[Qs,Lt]of Object.entries(ia.fields??{}))Qs.endsWith("OtherDescription")&&Lt?.value!=null&&Lt.value!==""&&(Ls[Qs]=String(Lt.value));return Yh(ia.fields?.[Ca]?.value,Ca,h,nt,Ls)}).filter(Ca=>Ca!=null&&Ca!==""&&Ca!=="—").join(w.separator??" · "),Ba=w.adjustmentOwner&&wt.includes(w.adjustmentOwner)?w.adjustmentOwner:void 0,Ts=Ba?Ah(Ba,h,nt):null;return e.jsxs("div",{className:"grid border-b border-slate-200 bg-slate-50/40 hover:bg-blue-50/40 transition-colors duration-100",style:{gridTemplateColumns:Hn},"data-testid":`row-condensed-${w.id}`,children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-center gap-1.5 w-[170px] min-w-[170px] bg-slate-50 sticky left-0 z-[2]",children:[e.jsx("span",{className:"text-[12px] font-medium text-slate-700 truncate min-w-0",title:w.label,children:w.label}),e.jsx("button",{type:"button",onClick:()=>Id(w.id),className:"ml-auto shrink-0 text-[9px] font-medium px-1.5 py-0.5 rounded bg-slate-100 hover:bg-slate-200 text-slate-500 hover:text-slate-700 transition-colors whitespace-nowrap",title:`Split into 
39individual rows${Ts?` (adjustment on ${Ts})`:""}`,"data-testid":`button-split-line-${w.id}`,children:"Split"})]}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200 text-[10px] text-slate-300 flex items-center",children:e.jsx(kn,{state:"blank"})}),e.jsx("div",{className:"px-2 py-[5px] flex items-center min-w-0 border-r border-slate-200 sticky z-[2] bg-white",style:{left:hr?"320px":"170px"},children:e.jsx("span",{className:"text-[11px] text-slate-600 truncate","data-testid":`condensed-subject-${w.id}`,children:Pt(t)||null})}),$a.map(ia=>{const Ca=Ba?Pn(ia.id,Ba):0,Ls=Ba?ca(ia.id,Ba):!1;return e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:"px-2 py-[5px] flex items-center min-w-0 border-r border-slate-200",children:e.jsx("span",{className:"text-[11px] text-slate-600 truncate","data-testid":`condensed-${w.id}-${ia.id}`,children:Pt(ia)||null})}),Qr&&e.jsx("div",{className:"px-1.5 py-[5px] w-[60px] min-w-[60px] flex items-center justify-end",title:Ba?`Adjustment on ${Ts} — split the line to edit`:"Reference facts — no dollar adjustment on this line (Appendix B-1)",children:Ba?Ls?e.jsxs("span",{className:"text-[10px] tabular-nums text-slate-500","data-testid":`condensed-adj-${w.id}-${ia.id}`,children:[Ca<0?"-":Ca>0?"+":"","$",Math.abs(Ca).toLocaleString()]}):e.jsx("span",{className:"text-[10px] tabular-nums text-slate-300","data-testid":`condensed-adj-${w.id}-${ia.id}`,children:"$0"}):e.jsx(kn,{state:"blank"})})]},ia.id)})]},`condensed-${w.id}`)},Ke=w=>e.jsx("div",{className:"bg-blue-50/50 border-b border-slate-200",children:e.jsxs("div",{className:"w-max px-3 py-0.5 flex items-center gap-2 sticky left-0 z-[2]","data-testid":`condensed-group-header-${w.id}`,children:[e.jsx("span",{className:"text-[10px] font-medium text-slate-500",children:w.label}),e.jsx("button",{type:"button",onClick:()=>Id(w.id),className:"text-[9px] font-medium px-1.5 py-0.5 rounded bg-white ring-1 ring-slate-200 hover:bg-slate-100 text-slate-500 hover:text-slate-700 transition-colors","data-testid":`button-merge-line-${w.id}`,children:"Condense"})]})},`condensed-header-${w.id}`),ft=(w,wt)=>{const Pt=dv,Ba=(Ca,Ls)=>{if(Ls.rowId!=="BedroomCount"&&Ls.rowId!=="FullBathroomCount"&&Ls.rowId!=="HalfBathroomCount")return null;const Qs=RP(Ca.fields?.aboveGrade?.value,Ca.fields?.belowGrade?.value);return Qs?Ls.rowId==="BedroomCount"?Qs.bedrooms:Ls.rowId==="FullBathroomCount"?Qs.fullBaths:Qs.halfBaths:null},Ts=(Ca,Ls,Qs)=>{const Lt=String(Ca.fields?.[Ls.id]?.value??"").trim();if(Lt)return e.jsx("span",{children:Lt});const La=Ba(Ca,Ls);return La!==null?e.jsxs("button",{type:"button",onClick:()=>r(Ca.id,Ls.id,String(La),"User"),className:"text-amber-700 border-b border-dashed border-amber-400 hover:bg-amber-100/60 rounded-sm px-0.5 transition-colors",title:"Interpreted from legacy packed room counts (3.6 counts unit totals). Click to confirm and save as the 3.6 value.","data-testid":Qs?`legacy-room-interp-condensed-subject-${Ls.rowId}`:`legacy-room-interp-condensed-${Ls.rowId}-${Ca.id}`,children:[La,e.jsx("span",{className:"ml-0.5 text-[8px] align-super text-amber-500",children:"legacy"})]}):null},ia=(Ca,Ls)=>e.jsx("span",{className:"text-[11px] text-slate-600 flex items-center gap-1 min-w-0",children:w.map((Qs,Lt)=>e.jsxs(Mn.Fragment,{children:[Lt>0&&e.jsx("span",{className:"text-slate-700",children:"|"}),Ts(Ca,Qs,Ls)]},Qs.id))});return e.jsxs("div",{className:"grid border-b border-slate-200 bg-slate-50/40 hover:bg-blue-50/40 transition-colors duration-100",style:{gridTemplateColumns:Hn},"data-testid":`row-condensed-${Pt.id}`,children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-center gap-1.5 w-[170px] min-w-[170px] bg-slate-50 sticky left-0 z-[2]",children:[e.jsx("span",{className:"text-[12px] font-medium text-slate-700 truncate min-w-0",title:Pt.label,children:Pt.label}),e.jsx("button",{type:"button",onClick:()=>Id(Pt.id),className:"ml-auto shrink-0 text-[9px] font-medium px-1.5 py-0.5 rounded bg-slate-100 hover:bg-slate-200 text-slate-500 hover:text-slate-700 transition-colors whitespace-nowrap",title:"Split into individual rows (each carries its own adjustment)","data-testid":`button-split-line-${Pt.id}`,children:"Split"})]}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200 text-[10px] text-slate-300 flex items-center",children:e.jsx(kn,{state:"blank"})}),e.jsx("div",{className:"px-2 py-[5px] flex items-center min-w-0 border-r border-slate-200 sticky z-[2] bg-white",style:{left:hr?"320px":"170px"},"data-testid":`condensed-subject-${Pt.id}`,children:ia(t,!0)}),$a.map(Ca=>{const Ls=w.reduce((Lt,La)=>Lt+Pn(Ca.id,La.id),0),Qs=w.some(Lt=>ca(Ca.id,Lt.id));return e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:"px-2 py-[5px] flex items-center min-w-0 border-r border-slate-200","data-testid":`condensed-${Pt.id}-${Ca.id}`,children:ia(Ca,!1)}),Qr&&e.jsx("div",{className:"px-1.5 py-[5px] w-[60px] min-w-[60px] flex items-center justify-end",title:"Combined bedroom/bath adjustments — split the line to edit each one",children:Qs?e.jsxs("span",{className:"text-[10px] tabular-nums text-slate-500","data-testid":`condensed-adj-${Pt.id}-${Ca.id}`,children:[Ls<0?"-":Ls>
390?"+":"","$",Math.abs(Ls).toLocaleString()]}):e.jsx("span",{className:"text-[10px] tabular-nums text-slate-300","data-testid":`condensed-adj-${Pt.id}-${Ca.id}`,children:"$0"})})]},Ca.id)})]},`condensed-${Pt.id}`)},mt=(w,wt)=>{const Pt=tc(w),Ba=nt&&w==="proximity",Ts=(nt||$)&&w==="garageCarport";Ba||(Ts?!ue&&!Px(fe,!1)||$a.some(Lt=>!Px(Lt.vehicleStorageItems??[],!0)):wi(w));const ia=Vp.has(w),Ca=w==="qualityCondition",Ls=$&&w==="garageCarport"?"Garage/Carport":Ts?"Type | Spaces | Detail":w==="basement"&&ts.length>0?`${Ah(w,h,nt)} — Unit 1`:Ah(w,h,nt);return e.jsxs(Mn.Fragment,{children:[e.jsxs("div",{className:Q("grid border-b transition-colors duration-100",ia?"border-slate-300 bg-slate-50":Pt?"border-slate-200 bg-amber-50/40 hover:bg-amber-50/60":"border-slate-200 bg-white hover:bg-slate-50"),style:{gridTemplateColumns:Hn},onFocus:()=>qs(w),onBlur:Lt=>Ks(w,Lt),children:[e.jsx("div",{className:Q("px-3 py-[5px] flex flex-col gap-0.5 w-[170px] min-w-[170px] sticky left-0 z-[2]",Ts?"bg-white":"bg-slate-50"),children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:Q("text-[12px] font-semibold min-w-0 text-slate-700",$?"whitespace-normal break-words leading-tight":"truncate"),title:Ls,children:Ls}),it&&!nt&&w!=="attachedDetached"&&!(nt&&w==="garageCarport")&&!(nt&&Yo[w])&&e.jsx(Fs,{section:"salesGrid",fieldName:w}),Pt&&e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400"}),w==="financing"&&e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("span",{className:"text-slate-400 hover:text-slate-600 cursor-default","data-testid":"financing-type-hint",children:e.jsx(Xx,{className:"w-3 h-3"})})}),e.jsx(Wa,{side:"right",className:"max-w-[200px] text-[11px]",children:"Enter from MLS remarks or closing disclosure. No automated source available."})]})}),w==="site"&&e.jsx("button",{onClick:()=>Wm(Lt=>Lt==="auto"?"sf":Lt==="sf"?"ac":"auto"),className:"ml-auto text-[9px] font-medium px-1.5 py-0.5 rounded bg-slate-100 hover:bg-slate-200 text-slate-500 hover:text-slate-700 transition-colors whitespace-nowrap",title:"Toggle site display units (Auto / SF / Acres)","data-testid":"toggle-site-units",children:bo==="auto"?"Auto":bo==="sf"?"SF":"AC"}),Qr&&zn&&!hr&&(ac[w]||sc[w])&&(()=>{const Lt=ac[w],La=Lt??sc[w],lr=Lt?.allowFlatBasis?qn[w]??"perUnit":"perUnit",Ys=_c===w;return e.jsxs(xn,{open:Ys,onOpenChange:Ms=>bd(Ms?w:null),children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{type:"button","data-testid":`chip-auto-${w}`,title:`Auto-adjuster — apply one rate across all comps for ${Ah(w,h,nt)}`,className:Q("ml-auto shrink-0 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-semibold ring-1 transition-colors",Ys?"bg-blue-600 text-white ring-blue-600":"bg-white text-blue-700 ring-blue-200 hover:bg-blue-50"),children:[e.jsx(Bx,{className:"w-3 h-3"}),La.label]})}),e.jsx(yn,{align:"start",className:"w-64 p-3",sideOffset:4,collisionPadding:12,children:e.jsxs("div",{className:"space-y-2 text-left",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-slate-500",children:["Auto-adjuster ·"," ",Ah(w,h,nt)]}),e.jsx("p",{className:"text-[10px] text-slate-500 leading-snug",children:La.hint}),e.jsxs("div",{children:[e.jsxs("label",{className:"mb-1 block text-[10px] font-medium text-slate-500",children:[La.rateLabel,w==="qualityCondition"?Bi.quality==="percent"?" (% of sale price)":" ($)":""]}),e.jsx(ze,{"data-testid":`input-auto-rate-${w}`,autoFocus:!0,value:go[La.rateKey]??"",onChange:Ms=>Zd(Zr=>({...Zr,[La.rateKey]:Ms.target.value})),placeholder:La.ratePlaceholder,className:"h-7 w-full text-xs",inputMode:"decimal"})]}),w==="qualityCondition"&&e.jsx("div",{className:"grid grid-cols-2 gap-2",children:["quality","condition"].map(Ms=>e.jsxs("div",{children:[e.jsxs("label",{className:"mb-1 block text-[10px] font-medium capitalize text-slate-500",children:[Ms," basis"]}),e.jsxs(sr,{value:Bi[Ms],onValueChange:Zr=>{xd(cn=>({...cn,[Ms]:Zr})),hf(!0)},children:[e.jsx(rr,{className:"h-7 text-xs","data-testid":`select-auto-${Ms}-basis`,children:e.jsx(or,{})}),e.jsxs(nr,{children:[e.jsx(vs,{value:"percent",children:"Percent"}),e.jsx(vs,{value:"dollars",children:"Dollars"})]})]})]},Ms))}),Lt?.rate2Key&&e.jsxs("div",{children:[e.jsxs("label",{className:"mb-1 block text-[10px] font-medium text-slate-500",children:[Lt.rate2Label,w==="qualityCondition"?Bi.condition==="percent"?" (% of sale price)":" ($)":""]}),e.jsx(ze,{"data-testid":`input-auto-rate2-${w}`,value:go[Lt.rate2Key]??"",onChange:Ms=>Zd(Zr=>({...Zr,[Lt.rate2Key]:Ms.target.value})),placeholder:Lt.rate2Placeholder,className:"h-7 w-full text-xs",inputMode:"decimal"})]}),Lt?.allowFlatBasis&&e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-[10px] font-medium text-slate-500",children:"Basis"}),e.jsxs("div",{className:"flex gap-1",role:"group","aria-label":"Adjustment basis",children:[e.jsx("button",{type:"button","data-testid":`toggle-auto-basis-perunit-${w}`,onClick:()=>gd(Ms=>({...Ms,[w]:"perUnit"})),className:Q("flex-1 rounded px-1.5 py-1 text-[10px] font-semibold ring-1 transition-colors",lr==="perUnit"?"bg-blue-600 text-white ring-blue-600":"bg-white text-slate-600 ring-slate-200 hover:bg-slate-50"),children:"Per-unit rate"}),e.jsx("button",{type:"button","data-testid":`toggle-auto-basis-flat-${w}`,onClick:()=>gd(Ms=>({...Ms,[w]:"flat"})),className:Q("flex-1 rounded px-1.5 py-1 text-[10px] font-semibold ring-1 transition-colors",lr==="flat"?"bg-blue-600 text-white ring-blue-600":"bg-white text-slate-600 ring-slate-200 hover:bg-slate-50"),children:"Flat $"})]}),lr==="flat"&&e.jsx("p",{className:"mt-1 text-[10px] text-slate-500 leading-snug",children:"The amount above is applied once per differing comp; its sign follows the difference direction."})]}),Lt?.thresholdUnit&&e.jsxs("div",{children:[e.jsxs("label",{className:"mb-1 block text-[10px] font-medium text-slate-500",children:["Threshold — only adjust when difference exceeds (",Lt.thresholdUnit,")"]}),e.jsx(ze,{"data-testid":`input-auto-threshold-${w}`,value:Mu[w]??"",onChange:Ms=>hp(Zr=>({...Zr,[w]:Ms.target.value})),placeholder:"Optional, e.g. 100",className:"h-7 w-full text-xs",inputMode:"decimal"}),e.jsx("p",{className:"mt-1 text-[10px] text-slate-500 leading-snug",children:"Comps at or within the threshold get no adjustment; beyond it the full difference is adjusted."})]}),e.jsxs("div",{className:"flex items-start gap-1.5 rounded bg-slate-50 px-2 py-1 text-[10px] text-slate-500",children:[e.jsx(on,{className:"h-3 w-3 shrink-0 mt-0.5"}),"Overwrites every comp's adjustment on this line."]}),e.jsxs(De,{size:"sm",onClick:()=>{Bg(w,lc(go[La.rateKey]??""),Lt?.rate2Key?lc(go[Lt.rate2Key]??""):void 0,{basis:lr,threshold:Lt?.thresholdUnit?lc(Mu[w]??""):void 0}),bd(null)},className:"w-full h-7 gap-1 text-xs bg-blue-600 hover:bg-blue-700","data-testid":`button-auto-apply-${w}`,children:[e.jsx(Bs,{className:"h-3.5 w-3.5"})," ","Apply to all comps"]}),e.jsx(De,{variant:"outline",size:"sm",onClick:()=>{yl(w),bd(null)},className:"w-full h-7 text-xs text-slate-500","data-testid":`button-auto-clear-${w}`,children:"Reset to $0"})]})})]})})()]})}),hr&&e.jsx("div",{className:"px-2 py-[5px] flex flex-col items-start justify-center border-r border-slate-200","data-testid":`master-rate-cell-${w}`,children:w==="dateOfSale"?e.jsx("div",{className:"flex flex-wrap gap-1",children:e.jsx(e8,{isLocked:Sc.isLocked,monthlyRateLabel:Sc.label,isHydrating:$o.isLoading,onOpenFullWizard:()=>R?.(),disabledReason:R?void 0:"Time wizard unavailable",picker:{options:Wi,activeMethodId:ti,needsWizard:Ip,isWorking:Cp,errorMessage:vf,onSelect:mu,onRemove:hu,onOpenFullWizard:()=>R?.()},manual:{isManualLocked:as.isManualLocked,basis:as.basis,rate:as.rate,needsWizard:Ip,onApply:th}})}):Nj[w]?e.jsx("div",{className:"flex flex-wrap gap-1",children:Nj[w].map(Lt=>{const La=bl[Lt],Ys=Nj[w].length>1?Lt==="bedrooms"?"Bed":Lt==="bathrooms"?"Bath":Lt==="quality"?"Q":Lt==="condition"?"C":void 0:void 0;return e.jsx(XH,{attribute:Lt,prefix:Ys,rate:La?.rate??null,unit:La?.unit??HT[Lt],defaultUnit:HT[Lt],supportsPctSf:Lt==="gla",isHydrating:!mm&&qu.isLoading,isApplying:!!pm[Lt],onApply:(Ms,Zr)=>fm(Lt,Ms,Zr),onClear:()=>gm(Lt),disabledReason:E&&E.length===0?"Lock comps to enable chip":void 0,sourceMethod:La?.method,sourceDataset:La?.dataset},Lt)})}):e.jsx(kn,{state:"blank"})}),Ca?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:Q("sticky z-[2] h-full min-h-8 self-stretch",Ba||Ob(w)?"bg-slate-100":Gl({fieldName:w,isMissing:wm(t,w,nt)})),"data-testid":`subject-surface-${w}`,style:{left:hr?"320px":"170px"},children:e.jsx(ju,{property:t,showMissing:h!=="str",onUpdateQuality:(Lt,La)=>
39A?At?.("improvements","OverallQualityRatingCode",Lt):r(t.id,"quality",Lt,La),onUpdateCondition:(Lt,La)=>A?At?.("improvements","OverallConditionRatingCode",Lt):r(t.id,"condition",Lt,La),qualityFieldData:A?ya?.OverallQualityRatingCode:void 0,conditionFieldData:A?ya?.OverallConditionRatingCode:void 0})}),$a.map((Lt,La)=>e.jsxs(Mn.Fragment,{children:[e.jsx(ju,{property:Lt,isFirstComp:La===0,showMissing:h!=="str",onUpdateQuality:(lr,Ys)=>r(Lt.id,"quality",lr,Ys),onUpdateCondition:(lr,Ys)=>r(Lt.id,"condition",lr,Ys)}),Qr&&e.jsx(Ph,{propertyId:Lt.id,fieldName:w,adjustment:Pn(Lt.id,w),hasExplicitValue:ca(Lt.id,w),onAdjustmentChange:wn,suggestion:x?.[Lt.id]?.[w]||x?.[Lt.snapshotId]?.[w]||null,salePrice:pn(Lt),isSacred:xr.current.has(`${Lt.id}:${w}`),isPulsing:ec.has(`${Lt.id}:${w}`),isJustFilled:rl.has(`${Lt.id}:${w}`),onResetSacred:no,chipDerivations:Kc.current.get(`${Lt.id}:${w}`)??null,prereqsMet:F!==!1})]},Lt.id))]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:Q("sticky z-[2] h-full min-h-8 self-stretch",Ba||Ob(w)?"bg-slate-100":Gl({fieldName:w,isMissing:wm(t,w,nt)})),"data-testid":`subject-surface-${w}`,style:{left:hr?"320px":"170px"},children:Ba?e.jsx("div",{className:"h-full min-h-8 self-stretch border-l border-slate-200 bg-slate-100","aria-disabled":"true","data-testid":"subject-na-proximity",title:"Not applicable to the Subject (UAD 3.6 B-1)"}):(nt||$)&&w==="garageCarport"?e.jsx("div",{className:Q("border-l border-slate-200 px-2 py-[5px]",Gl({fieldName:w,isMissing:!ue&&!Px(fe,!1),isRequired:!0})),"data-testid":"vehicle-storage-subject-cell-wrapper",children:e.jsx(xP,{items:fe,isLoading:ue,onChange:Lt=>de?.(Lt.slice(0,12)),source:be,userEdited:H,disabled:!de,emptyLabel:$&&!ye?t.vehicleStorageLegacyLabel||String(xt?.garageParking?.value??xt?.garageCarport?.value??"—"):"None",inspectSection:"vehicleStorage",inspectPrefix:"items",inspectEntityLabel:"Subject",testIdPrefix:"propertylab-subject"})}):Ob(w)?e.jsx("div",{className:"px-1.5 py-[5px] flex items-center justify-center bg-slate-100 select-none","aria-disabled":"true","data-testid":`subject-na-${w}`,title:"Comparable-only fact — not applicable to the Subject (UAD 3.6 B-1)",children:e.jsx(kn,{state:"gray"})}):e.jsx(jh,{property:t,fieldName:w,onUpdate:(Lt,La)=>r(t.id,w,Lt,La),onFieldUpdate:r,onSetPreference:oo,preferredSource:Zo(w),gridMode:h,activeScenario:f,siteDisplayUnits:w==="site"?bo:void 0,showMissing:h!=="str"&&!ia,highlightConflicts:Va,uad36:nt,fieldDataOverride:nt&&!$?Lx(t,w):void 0,inspectSection:nt&&Yo[w]||w==="attachedDetached"?"subjectProperty":void 0,inspectFieldName:nt&&Yo[w]?Yo[w]:w==="attachedDetached"?"AttachmentType":void 0,inspectLabel:nt&&(Yo[w]||w==="attachedDetached")?`Subject · ${Tx(w)}`:void 0})}),$a.map((Lt,La)=>e.jsxs(Mn.Fragment,{children:[Ba?e.jsx("div",{className:"min-w-0 self-stretch",style:{gridColumn:"span 2"},"data-testid":`proximity-full-width-cell-${Lt.id}`,children:e.jsx(jh,{property:Lt,fieldName:w,isFirstComp:La===0,comparableSequence:La+1,onUpdate:(lr,Ys)=>r(Lt.id,w,lr,Ys),onFieldUpdate:r,onCopyToAllComps:(lr,Ys)=>_i(w,lr,Ys),onCopyCompanionToAllComps:Af,onSetPreference:oo,preferredSource:Zo(w),gridMode:h,showMissing:!1,highlightConflicts:Va,uad36:nt,inspectSection:"salesComparison",inspectFieldName:Zi(Lt.id,"fields.ProximityToSubjectDistanceLinearMeasure"),inspectLabel:`Comp ${La+1} · Proximity to Subject`})}):(nt||$)&&w==="garageCarport"?e.jsx("div",{className:Q("px-2 py-[5px]",La===0?"border-l-2 border-l-slate-300":"border-l border-slate-200",Gl({fieldName:w,isMissing:!Px(Lt.vehicleStorageItems??[],!0),isRequired:!0})),children:e.jsx(xP,{items:(Lt.vehicleStorageItems??[]).slice(0,12),onChange:lr=>ge?.(Lt.id,lr.slice(0,12)),source:Lt.vehicleStorageSource,userEdited:Lt.vehicleStorageUserEdited,disabled:!ge,emptyLabel:$&&!Lt.vehicleStorageExplicitNone?Lt.vehicleStorageLegacyLabel||String(Lt.fields.garageParking?.value??Lt.fields.garageCarport?.value??"—"):"None",inspectSection:"salesComparison",inspectPrefix:Zi(Lt.id,"fields.VehicleStorageItems"),inspectEntityLabel:`Comp ${La+1}`,testIdPrefix:`propertylab-comp-${Lt.id}`})}):e.jsx(jh,{property:Lt,fieldName:w,isFirstComp:La===0,comparableSequence:La+1,onUpdate:(lr,Ys)=>
39r(Lt.id,w,lr,Ys),onFieldUpdate:r,onCopyToAllComps:(lr,Ys)=>_i(w,lr,Ys),onSetPreference:oo,preferredSource:Zo(w),gridMode:h,siteDisplayUnits:w==="site"?bo:void 0,showMissing:h!=="str"&&!ia,highlightConflicts:Va,uad36:nt,fieldDataOverride:nt&&!$?Lx(Lt,w):void 0,inspectSection:nt&&Yo[w]||w==="attachedDetached"?"salesComparison":void 0,inspectFieldName:nt&&Yo[w]?Zi(Lt.id,`transferHistory.0.${Yo[w]}`):w==="attachedDetached"?Zi(Lt.id,"fields.AttachmentType"):void 0,inspectLabel:nt&&(Yo[w]||w==="attachedDetached")?`Comp ${La+1} · ${Tx(w)}`:void 0}),Qr&&!Ba&&(nt&&w==="garageCarport"?e.jsx("div",{className:"w-[60px] min-w-[60px] self-stretch","aria-hidden":"true","data-testid":`vehicle-storage-row-adjustment-spacer-${Lt.id}`}):Vp.has(w)?e.jsx("div",{className:"w-[60px] min-w-[60px] self-stretch bg-transparent","aria-hidden":"true","data-testid":`adj-na-${w}-${Lt.id}`}):e.jsx(Ph,{propertyId:Lt.id,fieldName:nt&&w==="garageCarport"?"VehicleStorage":w,adjustment:Pn(Lt.id,nt&&w==="garageCarport"?"VehicleStorage":w),hasExplicitValue:ca(Lt.id,nt&&w==="garageCarport"?"VehicleStorage":w),onAdjustmentChange:wn,suggestion:x?.[Lt.id]?.[w]||x?.[Lt.snapshotId]?.[w]||null,salePrice:pn(Lt),isSacred:xr.current.has(`${Lt.id}:${w}`),isPulsing:ec.has(`${Lt.id}:${w}`),isJustFilled:rl.has(`${Lt.id}:${w}`),onResetSacred:no,chipDerivations:Kc.current.get(`${Lt.id}:${w}`)??null,prereqsMet:F!==!1}))]},Lt.id))]})]}),!1]},w)},Xe=h!=="str",_t={...t,fields:{...t.fields??{},...ya?.ContractPrice?{SalesContractAmount:ya.ContractPrice}:{},...Fe!==void 0?{SalesContractExistsIndicator:{value:Fe}}:{},...Oe!==void 0?{SalesContractReviewedIndicator:{value:Oe}}:{},...Object.fromEntries(Object.entries(qa??{}).map(([w,wt])=>[w,wt&&typeof wt=="object"&&"value"in wt?wt:{value:wt}])),...ya?.listingStatus?{listingStatus:ya.listingStatus}:{},...ya?.ContractDate?{SalesContractDate:ya.ContractDate}:{},...os!==void 0?{ValuationAssignmentType:{value:os}}:{},...Array.isArray(Be?.site?.hazardZones)?{HazardZoneType:{value:Be.site.hazardZones}}:{},...Object.fromEntries(["PropertyInProjectIndicator","ProjectLegalStructureType"].flatMap(w=>{const wt=rt?.[w];return wt===void 0?[]:[[w,wt]]}))}},oa=FP(_t,$a,[...oi,...Xo.filter(w=>w.relevant!==!1).map(w=>({id:w.rowId,source:"catalog",rowId:w.rowId}))]),ls=sa&&nx("hazardZone",oa),Ps=sa&&nx("siteSize",oa),Er=w=>Xe?w.filter(wt=>(!$||!Oj(wt))&&!(A&&Xh(wt)&&!sd.includes(wt))&&!(sa&&wt==="HazardZoneType"&&!ls&&!Xo.some(Pt=>Pt.rowId==="HazardZoneType"&&Pt.relevant===!0))&&!oi.some(Pt=>Pt.source==="catalog"&&Pt.rowId===wt)).map(wt=>({id:X0.includes(wt)?wt:wt==="PropertyEstateType"?"PropertyEstateType":`catalog_${wt}_auto`,label:MW[wt]??mE(wt)?.label??wt,source:"catalog",rowId:wt,auto:!0})):[],mn=new Map(Object.entries(_W).filter(([w])=>Wt.some(wt=>wt.id===w)).map(([w,wt])=>[w,Er(wt)]));if(A&&Xe&&xs&&Wt.some(w=>w.id==="generalInfo")){const w=new Set(Array.from(A0)),wt=ag.filter(Pt=>w.has(Pt)).map(Pt=>({id:`catalog_${Pt}_required`,label:mE(Pt)?.label??Pt,source:"catalog",rowId:Pt,auto:!0}));mn.set("generalInfo",[...mn.get("generalInfo")??[],...wt])}const vr=Array.from(mn.values()).flat(),tn={...t,fields:{...xt??{},...ya?.ContractPrice?{SalesContractAmount:ya.ContractPrice}:{},...Fe!==void 0?{SalesContractExistsIndicator:{value:Fe}}:{},...Oe!==void 0?{SalesContractReviewedIndicator:{value:Oe}}:{},...Object.fromEntries(Object.entries(qa??{}).map(([w,wt])=>[w,wt&&typeof wt=="object"&&"value"in wt?wt:{value:wt}])),...ya?.listingStatus?{listingStatus:ya.listingStatus}:{},...ya?.ContractDate?{SalesContractDate:ya.ContractDate}:{},...Array.isArray(Be?.site?.hazardZones)?{HazardZoneType:{value:Be.site.hazardZones}}:{},...Object.fromEntries(["PropertyInProjectIndicator","ProjectLegalStructureType"].flatMap(w=>{const wt=rt?.[w];return wt===void 0?[]:[[w,wt]]}))}},An=FP(tn,$a,[...oi,...vr,...Xo.filter(w=>w.relevant!==!1).map(w=>({id:w.rowId,source:"catalog",rowId:w.rowId}))]),lo=w=>w.source==="catalog"&&!!w.rowId&&oi.some(wt=>wt.source==="catalog"&&wt.rowId===w.rowId),Si=w=>oi.some(wt=>wt.source==="catalog"&&wt.rowId===w),Bo=w=>w.rowId==="SalesContractAmount"?"ContractPrice":w.rowId,nl=w=>{if(w.source==="custom"&&w.group==="Vehicle Storage"&&w.relevant===!1)return!1;if(!Xe)return!0;
39if((w.rowId==="NoFinancingTransactionIndicator"||w.rowId==="MortgageType")&&!Si("FinancingType"))return!1;const wt=Bo(w),Pt=wt?vv[wt]:void 0,Ba=lo(w),Ts=w.rowId==="HazardZoneType"&&Xo.some(Ca=>Ca.rowId==="HazardZoneType"&&Ca.relevant===!0);if(Pt&&(Pt.inclusionClass==="REL"||Pt.inclusionClass==="APP_OR_REL"||Pt.inclusionClass==="APP_AND_REL")&&(Ba||Ts))return!0;if(Pt?.gateId&&(Pt.inclusionClass==="APP"||Pt.inclusionClass==="APP_OR_REL")&&!nx(Pt.gateId,An))return!1;if(w.rowId==="SalesContractAmount")return!0;const ia=Tu(w);return w.rowId&&(II(w.rowId)||Nv(w.rowId))?!0:$&&Oj(w.rowId,ia)?!1:ia?w.rowId==="HazardZoneType"?Xo.some(Ca=>Ca.rowId==="HazardZoneType"&&Ca.relevant===!0)||ls:l1.has(ia)?gE(An):FA(ia,An):!0},Ki=w=>{const wt=Tu(w);if(!wt?.startsWith("AmenityType_"))return null;const Pt=wt.slice(12);return cd.includes(Pt)?Pt:null},rc=w=>{const wt=A?qp(qa?.[w])?.value:void 0;if(wt!=null&&wt!=="")return!0;const Pt=xt?.[w]?.value;return Pt!=null&&Pt!==""?!0:$a.some(Ba=>{const Ts=Ba.fields[w]?.value;return Ts!=null&&Ts!==""})},Ku=w=>{const wt=Ki(w);return wt?tt?ba.includes(wt):ba.includes(wt)||rc(w.id):!0},wd=w=>Xe&&!!w.rowId&&Nv(w.rowId)&&!rc(w.id)&&!rc(w.rowId),vc=w=>A&&Ej(w),nc=w=>A&&wj(w),_n=new Set(["ReasonPropertyNotUsedType","ReasonPropertyNotUsedTypeOtherDescription","ComparableToSubjectDirectionType","PropertyGroundLeaseAnnualAmount","NativeAmericanLandsIndicator","NativeAmericanLandsType","NativeAmericanLandsTypeOtherDescription","PropertyPartialInterestType","PropertyPartialInterestTypeOtherDescription"]),To=w=>w.rowId?vc(w)||nc(w)||_n.has(w.rowId)?!0:A&&w.source==="catalog"&&vv[w.rowId]?.inclusionClass==="REL"&&Dh(w.rowId,w.group,"urar36")==="generalInfo"?!1:jU(w.rowId)&&!rc(w.id)&&!rc(w.rowId):!1,So=w=>w===0?"$0":`${w>0?"+":"-"}$${Math.abs(w).toLocaleString()}`,wa=(w,wt)=>{if(Xe&&(w.rowId==="FinancingType"||w.rowId==="MortgageType")||Xe&&w.rowId==="ContractPrice"&&nx("contractPrice",An)||!wt?.canonical&&vc(w)||!wt?.canonical&&nc(w))return null;if(Xe&&(w.id?.startsWith("wizard_qc_struct_hdr_d")||w.id?.startsWith("wizard_qc_unit_hdr_u")||w.id?.startsWith("wizard_qc_adu_hdr_a")))return e.jsxs("div",{"data-testid":`added-row-${w.id}`,className:"grid border-b border-slate-200 bg-slate-100 transition-colors duration-100",style:{gridTemplateColumns:Hn},children:[e.jsx("div",{className:"px-3 py-[5px] flex items-center w-[170px] min-w-[170px] bg-slate-100 sticky left-0 z-[2]",children:e.jsx("span",{className:"text-[11px] font-bold text-slate-700 whitespace-nowrap",children:w.label})}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200"}),e.jsx("div",{className:"px-3 py-[5px] border-l border-slate-200 text-xs font-normal leading-5 text-slate-700 flex items-center sticky z-[2]",style:{left:hr?"320px":"170px"},children:w.label}),$a.map((Ge,bt)=>e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:Q("px-3 py-[5px] text-[11px] font-bold text-slate-600 flex items-center",bt===0?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:w.label}),Qr&&e.jsx("div",{className:"px-1.5 py-[5px] w-[60px] min-w-[60px]"})]},Ge.id))]},w.id);if(Xe&&(w.id?.startsWith("wizard_qc_ext_qual_hdr_d")||w.id?.startsWith("wizard_qc_int_qual_hdr_u")||w.id?.startsWith("wizard_qc_adu_qual_hdr_a"))){const Ge=w.rowId??"exteriorQuality",bt=w.id?.startsWith("wizard_qc_ext_"),Za=w.id?.startsWith("wizard_qc_adu_"),ra=parseInt(w.id?.match(/\d+$/)?.[0]??"1",10)||1,ta=xt?.SubjectStructures?.value,Mt=yj(ta),ms=bt?Math.max(Sx(Mt).length,1)>=ra:Za?Nx(Mt).length>=ra:Math.max(vx(Mt).length,1)>=ra;return e.jsxs("div",{"data-testid":`added-row-${w.id}`,className:"grid border-b border-slate-200 bg-white transition-colors duration-100 hover:bg-blue-50/50",style:{gridTemplateColumns:Hn},children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-center w-[170px] min-w-[170px] bg-white sticky left-0 z-[2]",children:[e.jsx("span",{className:"text-[11px] font-bold text-slate-700 whitespace-nowrap",children:"Quality"}),it&&!nt&&e.jsx(Fs,{section:"salesGrid",fieldName:Ge})]}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200 text-[10px] text-slate-300 flex items-center",children:e.jsx(kn,{state:"blank"})}),e.jsx("div",{className:"sticky z-[2] h-full min-h-8 self-stretch bg-inherit",style:{left:hr?"320px":"170px"},children:ms?e.jsx(ju,{property:t,showMissing:!0,qualityField:Ge,showOnly:"quality",onUpdateQuality:(cr,Cn)=>r(t.id,Ge,cr,Cn)}):e.jsx("div",{className:"px-3 py-[5px] border-l border-slate-200 bg-slate-100 text-xs font-normal leading-5 text-slate-700 flex items-center","data-testid":`na-subject-addedrow-${w.id}`,children:e.jsx(kn,{state:"gray"})})}),$a.map((cr,Cn)=>{const Ai=Jb(cr.fields),Rn=bt?Math.max(Sx(Ai).length,1)>=ra:Za?Nx(Ai).length>=ra:Math.max(vx(Ai).length,1)>=ra;return e.jsxs(Mn.Fragment,{children:[Rn?e.jsx(ju,{property:cr,isFirstComp:Cn===0,showMissing:!0,qualityField:Ge,showOnly:"quality",onUpdateQuality:(hn,Ml)=>r(cr.id,Ge,hn,Ml),onCopyQualityToAll:(hn,Ml)=>_i(Ge,hn,Ml)}):e.jsx("div",{className:Q("px-3 py-[5px] text-[11px] text-slate-300 flex items-center",Cn===0?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:e.jsx(kn,{state:"em-d
39ash"})}),Qr&&e.jsx("div",{className:"w-[60px] min-w-[60px] self-stretch bg-slate-100",title:"Not adjustable for this row","data-testid":`na-adjustment-${w.id}-${cr.id}`})]},cr.id)})]},w.id)}if(Xe&&(w.id?.startsWith("wizard_qc_ext_cond_hdr_d")||w.id?.startsWith("wizard_qc_int_cond_hdr_u")||w.id?.startsWith("wizard_qc_adu_cond_hdr_a"))){const Ge=w.rowId??"exteriorCondition",bt=w.id?.startsWith("wizard_qc_ext_"),Za=w.id?.startsWith("wizard_qc_adu_"),ra=parseInt(w.id?.match(/\d+$/)?.[0]??"1",10)||1,ta=xt?.SubjectStructures?.value,Mt=yj(ta),ms=bt?Math.max(Sx(Mt).length,1)>=ra:Za?Nx(Mt).length>=ra:Math.max(vx(Mt).length,1)>=ra;return e.jsxs("div",{"data-testid":`added-row-${w.id}`,className:"grid border-b border-slate-200 bg-white transition-colors duration-100 hover:bg-blue-50/50",style:{gridTemplateColumns:Hn},children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-center w-[170px] min-w-[170px] bg-white sticky left-0 z-[2]",children:[e.jsx("span",{className:"text-[11px] font-bold text-slate-700 whitespace-nowrap",children:"Condition"}),it&&!nt&&e.jsx(Fs,{section:"salesGrid",fieldName:Ge})]}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200 text-[10px] text-slate-300 flex items-center",children:e.jsx(kn,{state:"blank"})}),e.jsx("div",{className:"sticky z-[2] h-full min-h-8 self-stretch bg-inherit",style:{left:hr?"320px":"170px"},children:ms?e.jsx(ju,{property:t,showMissing:!0,conditionField:Ge,showOnly:"condition",onUpdateCondition:(cr,Cn)=>r(t.id,Ge,cr,Cn)}):e.jsx("div",{className:"px-3 py-[5px] border-l border-slate-200 bg-slate-100 text-xs font-normal leading-5 text-slate-700 flex items-center","data-testid":`na-subject-addedrow-${w.id}`,children:e.jsx(kn,{state:"gray"})})}),$a.map((cr,Cn)=>{const Ai=Jb(cr.fields),Rn=bt?Math.max(Sx(Ai).length,1)>=ra:Za?Nx(Ai).length>=ra:Math.max(vx(Ai).length,1)>=ra;return e.jsxs(Mn.Fragment,{children:[Rn?e.jsx(ju,{property:cr,isFirstComp:Cn===0,showMissing:!0,conditionField:Ge,showOnly:"condition",onUpdateCondition:(hn,Ml)=>r(cr.id,Ge,hn,Ml),onCopyConditionToAll:(hn,Ml)=>_i(Ge,hn,Ml)}):e.jsx("div",{className:Q("px-3 py-[5px] text-[11px] text-slate-300 flex items-center",Cn===0?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:e.jsx(kn,{state:"em-dash"})}),Qr&&e.jsx("div",{className:"w-[60px] min-w-[60px] self-stretch bg-slate-100",title:"Not adjustable for this row","data-testid":`na-adjustment-${w.id}-${cr.id}`})]},cr.id)})]},w.id)}if(Xe&&w.id==="wizard_qc_overall_qual"){const Ge="OverallQualityRatingCode";return e.jsxs("div",{"data-testid":`added-row-${w.id}`,className:"grid border-b border-slate-200 bg-white transition-colors duration-100 hover:bg-blue-50/50",style:{gridTemplateColumns:Hn},children:[e.jsx("div",{className:"px-3 py-[5px] flex items-center w-[170px] min-w-[170px] bg-white sticky left-0 z-[2]",children:e.jsx("span",{className:"text-[11px] font-bold text-slate-700 whitespace-nowrap",children:"Quality"})}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200 text-[10px] text-slate-300 flex items-center",children:e.jsx(kn,{state:"blank"})}),e.jsx("div",{className:"sticky z-[2] h-full min-h-8 self-stretch bg-inherit",style:{left:hr?"320px":"170px"},children:e.jsx(ju,{property:t,showMissing:!0,qualityField:"OverallQualityRatingCode",showOnly:"quality",resolvedDisplay:!0,inspectSection:"improvements",qualityInspectField:"OverallQualityRatingCode",qualityInspectLabel:"Subject · Overall Q",onUpdateQuality:(bt,Za)=>A?At?.("improvements","OverallQualityRatingCode",bt):r(t.id,"OverallQualityRatingCode",bt,Za),qualityFieldData:A?ya?.OverallQualityRatingCode:void 0,onCopyQualityToAll:(bt,Za)=>_i("OverallQualityRatingCode",bt,Za)})}),$a.map((bt,Za)=>e.jsxs(Mn.Fragment,{children:[e.jsx(ju,{property:bt,isFirstComp:Za===0,showMissing:!0,qualityField:"OverallQualityRatingCode",showOnly:"quality",resolvedDisplay:!0,inspectSection:"salesComparison",qualityInspectField:Zi(bt.id,"fields.OverallQualityRatingCode"),qualityInspectLabel:`Comp ${Za+1} · Overall Q`,onUpdateQuality:(ra,ta)=>r(bt.id,"OverallQualityRatingCode",ra,ta),onCopyQualityToAll:(ra,ta)=>_i("OverallQualityRatingCode",ra,ta)}),Qr&&e.jsx(Ph,{propertyId:bt.id,fieldName:Ge,adjustment:Pn(bt.id,Ge),hasExplicitValue:ca(bt.id,Ge),onAdjustmentChange:wn,suggestion:x?.[bt.id]?.[Ge]||x?.[bt.snapshotId]?.[Ge]||null,salePrice:pn(bt),isSacred:xr.current.has(`${bt.id}:${Ge}`),isPulsing:ec.has(`${bt.id}:${Ge}`),isJustFilled:rl.has(`${bt.id}:${Ge}
39`),onResetSacred:no,chipDerivations:Kc.current.get(`${bt.id}:${Ge}`)??null,prereqsMet:F!==!1})]},bt.id))]},w.id)}if(Xe&&w.id==="wizard_qc_overall_cond"){const Ge="OverallConditionRatingCode";return e.jsxs("div",{"data-testid":`added-row-${w.id}`,className:"grid border-b border-slate-200 bg-white transition-colors duration-100 hover:bg-blue-50/50",style:{gridTemplateColumns:Hn},children:[e.jsx("div",{className:"px-3 py-[5px] flex items-center w-[170px] min-w-[170px] bg-white sticky left-0 z-[2]",children:e.jsx("span",{className:"text-[11px] font-bold text-slate-700 whitespace-nowrap",children:"Condition"})}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200 text-[10px] text-slate-300 flex items-center",children:e.jsx(kn,{state:"blank"})}),e.jsx("div",{className:"sticky z-[2] h-full min-h-8 self-stretch bg-inherit",style:{left:hr?"320px":"170px"},children:e.jsx(ju,{property:t,showMissing:!0,conditionField:"OverallConditionRatingCode",showOnly:"condition",resolvedDisplay:!0,inspectSection:"improvements",conditionInspectField:"OverallConditionRatingCode",conditionInspectLabel:"Subject · Overall C",onUpdateCondition:(bt,Za)=>A?At?.("improvements","OverallConditionRatingCode",bt):r(t.id,"OverallConditionRatingCode",bt,Za),conditionFieldData:A?ya?.OverallConditionRatingCode:void 0,onCopyConditionToAll:(bt,Za)=>_i("OverallConditionRatingCode",bt,Za)})}),$a.map((bt,Za)=>e.jsxs(Mn.Fragment,{children:[e.jsx(ju,{property:bt,isFirstComp:Za===0,showMissing:!0,conditionField:"OverallConditionRatingCode",showOnly:"condition",resolvedDisplay:!0,inspectSection:"salesComparison",conditionInspectField:Zi(bt.id,"fields.OverallConditionRatingCode"),conditionInspectLabel:`Comp ${Za+1} · Overall C`,onUpdateCondition:(ra,ta)=>r(bt.id,"OverallConditionRatingCode",ra,ta),onCopyConditionToAll:(ra,ta)=>_i("OverallConditionRatingCode",ra,ta)}),Qr&&e.jsx(Ph,{propertyId:bt.id,fieldName:Ge,adjustment:Pn(bt.id,Ge),hasExplicitValue:ca(bt.id,Ge),onAdjustmentChange:wn,suggestion:x?.[bt.id]?.[Ge]||x?.[bt.snapshotId]?.[Ge]||null,salePrice:pn(bt),isSacred:xr.current.has(`${bt.id}:${Ge}`),isPulsing:ec.has(`${bt.id}:${Ge}`),isJustFilled:rl.has(`${bt.id}:${Ge}`),onResetSacred:no,chipDerivations:Kc.current.get(`${bt.id}:${Ge}`)??null,prereqsMet:F!==!1})]},bt.id))]},w.id)}if(Xe&&(w.id?.startsWith("wizard_extra_ext")||w.id?.startsWith("wizard_extra_int")||w.id?.startsWith("wizard_extra_adu")))return null;const Pt=kW(w),Ba=Xe&&w.rowId&&(sd.includes(w.rowId)||Ox.has(w.rowId))?w.rowId:w.id,Ts=w.rowId==="PropertyEstateType",ia=Ts?qp(qa?.PropertyEstateType):void 0,Ca=String(Ts?ia?.value??"":A&&w.rowId&&qa?.[w.rowId]!==void 0?qp(qa[w.rowId])?.value??"":w.source==="custom"&&w.group==="Vehicle Storage"&&vt?Pe[w.id]??"":xt?.[Ba]?.value??""),Ls=Tu(w),Qs=w.rowId==="ContractPrice"?"SalesContractAmount":Ls??w.rowId??w.id,Lt=w.rowId?cH(w.rowId):null,La=w.rowId==="ContractPrice"?"ContractPrice":w.rowId&&Ox.has(w.rowId)?Lt==="FinancingType"?"FinancingType":Lt==="SalesConcessions"?"TotalSalesConcessionAmount":w.rowId:void 0,lr=(Ge,bt)=>Lt?DN(Lt,{role:bt,get:ra=>{const ta=!Ge.isSubject&&ra==="OwnershipTransferTransactionType"?Ge.transferHistory?.[0]?.[ra]??Ge.fields[ra]:Ge.fields[ra];return qp(ta)?.value??ta}}):null,Ys=Xe&&w.rowId==="SalesContractDate",Ms=Ge=>{if(!Ys)return"";const ra=String(Ge.fields?.dateOfSale?.value??"").split(";").map(ta=>ta.trim()).filter(Boolean).find(ta=>/^c/i.test(ta));return ra?`${ra.replace(/^c/i,"").trim()} (MLS)`:""},Zr=Pt&&Pt.length>0?Ge=>Ge==="true"?"Yes":Ge==="false"?"No":Ls?Hs(Ls,Ge):Ge:void 0,cn=Xe&&!!Ls&&l1.has(Ls),Jr=Xe&&Ls?.startsWith("AmenityType_")&&cd.includes(Ls.slice(12))?Ls.slice(12):null,Wn=Jr?w.id.replace("AmenityType_","AmenityCount_"):null,Dt=`catalog_${IU}_auto`,Da=Xe&&w.rowId&&(sd.includes(w.rowId)||Ox.has(w.rowId))?w.rowId:tt&&Jr?sV(Jr).adjustmentToken:w.id==="PropertyEstateType"?"PropertyRightsAppraised":w.id,Ia=(Ge,bt,Za)=>{if(!Jr)return null;if(tt){const ra=bt?void 0:Ge.fields?.PropertyAmenities?.value,ta=ra&&typeof ra=="object"&&"amenities"in ra&&Array.isArray(ra.amenities)?ra.amenities:[],Mt=bt?ua:ta;return e.jsx("div",{className:Q("px-2 py-[5px]",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:e.jsx(i7,{category:Jr,items:Mt,onChange:ms=>{bt?$t?.(ms):na?.(Ge.id,ms)},inspectSection:bt?"propertyAmenities":"salesComparison",inspectPath:bt?`amenities.${Jr}`:Zi(Ge.id,`fields.PropertyAmenities.value.amenities.${Jr}`),inspectLabel:bt?"Subject":`Comp ${$a.findIndex(ms=>ms.id===Ge.id)+1}`,source:bt?Oa:Ge.fields?.PropertyAmenities?.source,testId:bt?`subject-amenities-${Jr}`:`comparable-${Ge.id}-amenities-${Jr}`,comparable:!bt,subjectHasManufacturedHome:bt&&Xa})})}return Wn?e.jsx("div",{className:Q("px-2 py-[5px]",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:e.jsx(s7,{category:Jr,value:String(Ge.fields?.[w.id]?.value??""),countsValue:String(Ge.fields?.[Wn]?.value??""),otherDescription:String(Ge.fields?.[Dt]?.value??""),onValueChange:ra=>r(Ge.id,w.id,ra??"","User"),onCountsChange:ra=>r(Ge.id,Wn,ra??"","User"),onOtherDescriptionChange:ra=>r(Ge.id,Dt,ra,"User"),testId:bt?`input-subject-addedrow-${w.id}`:`input-comp-addedrow-${w.id}-${Ge.id}`})}):null},ar=Xe&&w.rowId?xU(w.rowId):null,Xs=ar?.key===xE,Fa=w.rowId??w.id,is=Xs?Fa.replace(xE,bU):null,Cr=ar?.key==="UtilityType"?Fa.replace("UtilityType","UtilityTypeOtherDescription"):null,Io=(Ge,bt,Za)=>{if(!Ts)return null;const ra=bt?ia:Ge.fields?.PropertyEstateType,ta=String((bt?qp(qa?.PropertyEstateTypeOtherDescription):Ge.fields?.PropertyEstateTypeOtherDescription)?.value??""),Mt=String((bt?qp(qa?.ProjectLegalStructureType):Ge.fields?.ProjectLegalStructureType)?.value??""),ms=bt?"PropertyEstateType":Zi(Ge.id,"fields.PropertyEstateType");return e.jsx(sK,{value:String(ra?.value??""),otherDescription:ta,meta:ra,isSubject:bt,isFirstComp:Za,inspectSection:bt?"subjectProperty":"salesComparison",inspectField:ms,inspectLabel:bt?"Subject · Property Rights Appraised":`Comp ${$a.findIndex(cr=>
39cr.id===Ge.id)+1} · Property Rights Appraised`,inspecting:it,testId:bt?`input-subject-addedrow-${w.id}`:`input-comp-addedrow-${w.id}-${Ge.id}`,emDash:Mt==="Cooperative",resolvedDisplay:!0,onValueChange:cr=>r(bt?t.id:Ge.id,"PropertyEstateType",cr??"","User"),onOtherDescriptionChange:cr=>r(bt?t.id:Ge.id,"PropertyEstateTypeOtherDescription",cr??"","User")})},Qi=(Ge,bt,Za)=>{if(!ar)return null;const ra=Q("px-2 py-[5px]",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200"),ta=bt?`input-subject-addedrow-${w.id}`:`input-comp-addedrow-${w.id}-${Ge.id}`;if(Xs&&is){const Mt=Fa,ms=is;return e.jsx("div",{className:ra,children:e.jsx(uH,{type:String(Ge.fields?.[Mt]?.value??""),otherDescription:String(Ge.fields?.[ms]?.value??""),onTypeChange:cr=>r(Ge.id,Mt,cr??"","User"),onOtherDescriptionChange:cr=>r(Ge.id,ms,cr??"","User"),testId:ta})})}return Cr?e.jsx("div",{className:ra,children:e.jsx(mH,{value:SW(String(Ge.fields?.[Fa]?.value??""),String(Ge.fields?.[Cr]?.value??"")),onChange:Mt=>r(Ge.id,Fa,Mt??"","User"),testId:ta})}):null},ic=Xe&&Ls&&ag.includes(Ls)?Ls:null,dr=(Ge,bt,Za)=>{if(!ic||String(Ge.fields?.[w.id]?.value??"").trim())return null;const ta=RP(Ge.fields?.aboveGrade?.value,Ge.fields?.belowGrade?.value);if(!ta)return null;const Mt=ic==="BedroomCount"?ta.bedrooms:ic==="FullBathroomCount"?ta.fullBaths:ta.halfBaths;if(Mt===null)return null;const ms=ta.includesBelowGrade?"Interpreted from legacy above + below-grade counts (3.6 counts unit totals). Click to confirm and save as the 3.6 value.":"Interpreted from legacy above-grade-only counts — verify any below-grade rooms are included (3.6 counts unit totals). Click to confirm and save as the 3.6 value.";return e.jsx("div",{className:Q("px-2 py-[5px] flex items-center",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:e.jsxs("button",{type:"button",onClick:()=>r(Ge.id,w.id,String(Mt),"User"),className:"text-[11px] text-amber-700 border-b border-dashed border-amber-400 hover:bg-amber-100/60 rounded-sm px-0.5 transition-colors",title:ms,"data-testid":bt?`legacy-room-interp-subject-${w.id}`:`legacy-room-interp-${w.id}-${Ge.id}`,children:[Mt,e.jsx("span",{className:"ml-0.5 text-[8px] align-super text-amber-500",children:"legacy"})]})})},_r=(Ge,bt,Za)=>{const ra=xh.get(w.rowId??""),Mt=ra?{RenewableEnergyComponentType:"renewableComponents",GreenCertificationName:"greenCertifications",EfficiencyRatingName:"efficiencyRatings"}[ra]:void 0;if(!Xe||!ra||!Mt||!Ve)return null;const ms=bt?ne:Ge.fields?.EnergyFeatures?.value,cr=Xy(ms)[Mt],Cn=ms?.[Mt],Ai=Cn&&typeof Cn=="object"&&"source"in Cn?Cn.source:void 0,Rn=Jy(Mt,cr,bt?"subject":"comparable");return e.jsx("div",{className:Q("px-2 py-[5px]",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200",Gl({fieldName:ra,isMissing:Rn,isRequired:!0})),children:e.jsx(jH,{label:ra==="RenewableEnergyComponentType"?"Renewable Energy Component":ra==="GreenCertificationName"?"Building Certification":"Efficiency Rating",collectionKey:Mt,scope:bt?"subject":"comparable",compact:!0,items:cr,disabled:!1,inspectSection:bt?"energyFeatures":"salesComparison",inspectPrefix:bt?"":Zi(Ge.id,"fields.EnergyFeatures"),collectionSource:Ai,onChange:hn=>bt?Me?.(Mt,hn):lt?.(Ge.id,Mt,hn)})})},Ni=xh.get(w.rowId??""),X=Ni?{RenewableEnergyComponentType:"renewableComponents",GreenCertificationName:"greenCertifications",EfficiencyRatingName:"efficiencyRatings"}[Ni]:void 0;Ve&&X!==void 0&&ci.some(Ge=>{const bt=Ge.isSubject?ne:Ge.fields?.EnergyFeatures?.value,Za=Xy(bt)[X];return Jy(X,Za,Ge.isSubject?"subject":"comparable")});const xe=Xe&&(kb(Ls)||_3(w.rowId)),Ye=Xe&&w.source==="custom"&&w.group==="Vehicle Storage",ke=Xe&&w.rowId&&sd.includes(w.rowId)?w.rowId:null,jt=Xe&&w.rowId&&Ox.has(w.rowId)?w.rowId:null,Et=Xe&&w.rowId==="ContractPrice"?"SalesContractAmount":jt,ka=ke??jt??w.id,Yt=(Ge,bt)=>{if(!ke)return{source:void 0,userEdited:void 0};const Za=ke==="LotSizeAreaMeasure"?["LotSizeAreaMeasure","AreaUnitOfMeasureType"]:[ke],ra=bt&&A?qa:Ge.fields??{},ta=Za.map(Mt=>{const ms=ra?.[Mt];return ms&&typeof ms=="object"?ms:void 0}).find(Mt=>Mt?.source);return{source:ta?.source,userEdited:ta?.userEdited}},ha=(Ge,bt)=>{if(!ke||!it)return null;const Za=Ge?ke==="NeighborhoodName"?"subjectProperty":"site":"salesComparison",ra=Ge?ke:Zi(bt,`fields.${ke}`),ta=Ge?`Subject · ${ke}`:`Comp ${$a.findIndex(Mt=>Mt.id===bt)+1} · ${ke}`;return e.jsx(Fs,{section:Za,fieldName:ra,displayLabel:ta})},Rt=(Ge,bt)=>{if(!Et||!it)return null;
39const Za=Et==="SalesContractAmount"||Et==="SalesContractDate"||Et==="TotalSalesConcessionAmount"?Et:null;if(Ge&&!Za)return null;const ra=Et==="SalesContractAmount"?"subjectProperty":"salesContract";return e.jsx(Fs,{section:Ge?ra:"salesComparison",fieldName:Ge?Za:Zi(bt,`fields.${Et}`),displayLabel:Ge?`Subject · ${Tx(Et)}`:`Comp ${$a.findIndex(ta=>ta.id===bt)+1} · ${Tx(Et)}`})},Bt=(Ge,bt,Za)=>{if(!ke)return null;const ra=Yt(Ge,bt),ta=ha(bt,Ge.id),Mt=ra.source?e.jsx(Ji,{source:ra.source,userEdited:ra.userEdited,testId:`source-dot-site-${Ge.id}-${ke}`}):null,ms=Mt||ta?e.jsxs(e.Fragment,{children:[Mt,ta]}):void 0,cr=Q("flex min-h-[30px] items-center justify-start gap-x-2 px-2 py-[5px] text-left",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200"),Cn={...Ge,...bt?{subjectProperty:qa}:{},...bt&&Be?.site?{site:Be.site}:{}};if(ke==="LandOwnedInCommonIndicator"||ke==="NeighborhoodName"||ke==="SiteZoningComplianceType"){const Ai=aS(Cn,ke),Rn=ke==="LandOwnedInCommonIndicator"?["true","false"]:ke==="SiteZoningComplianceType"?Pr(ke):null;return e.jsx(FS,{value:Ai==null?"":String(Ai),enumOptions:Rn,optionLabel:Zr,isSubject:bt,isFirstComp:Za,onCommit:hn=>r(Ge.id,ke,hn,"User"),testId:bt?`input-subject-addedrow-${ke}`:`input-comp-addedrow-${ke}-${Ge.id}`,emptyPlaceholder:"",source:ra.source,userEdited:ra.userEdited,inspectPill:ta,valueClassName:"text-[12px] font-medium",resolvedDisplay:!0,required:dg.has(ke)})}if(ke==="LotSizeAreaMeasure"){if(zE(aS(Cn,"LandOwnedInCommonIndicator")))return e.jsxs("div",{className:Q(cr,"flex items-center justify-start gap-x-2 text-left text-[12px] font-medium text-slate-400"),"data-testid":`site-size-dash-${Ge.id}`,children:[Mt,ta,e.jsx(kn,{state:"em-dash"})]});const Rn=qE(Cn);return e.jsx(zW,{value:Rn.value,unit:String(Rn.unit??"SquareFeet"),wrapperClass:cr,source:ra.source,userEdited:ra.userEdited,sourceTestId:`source-dot-site-${Ge.id}-LotSizeAreaMeasure`,inspectPill:ta,onValueChange:hn=>r(Ge.id,"LotSizeAreaMeasure",hn,"User"),onUnitChange:hn=>r(Ge.id,"AreaUnitOfMeasureType",hn,"User"),inputTestId:`input-site-size-${Ge.id}`,unitTestId:`select-site-size-unit-${Ge.id}`})}if(ke==="HazardZoneType"){const Ai=A$(Cn);return e.jsx("div",{className:Q(cr,"min-w-0"),title:C$(Cn),children:e.jsx(qx,{label:"",hideLabel:!0,compact:!0,values:I$(Ai),options:j$,maxLength:60,maxEntries:7,onChange:Rn=>{const hn=T$(Rn,Ai);bt?He?.("hazardZones",hn):Ie?.(Ge.id,"HazardZoneType",hn,"User")},testId:`input-hazard-zone-${Ge.id}`,resolvedDisplay:!0,leadingContent:ms,controlClassName:"min-h-6 px-0 py-0 placeholder-hint",chipClassName:"text-[12px] font-medium"})})}return null},Jt=(Ge,bt,Za,ra)=>{if(w.rowId==="NoFinancingTransactionIndicator"&&Xe)return e.jsx("div",{className:Q("px-2 py-[5px]",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:e.jsx(dH,{getValue:ta=>bt?Na(ta)?.value:Ge.fields?.[ta]?.value,setValue:(ta,Mt)=>bt&&A?At?.("subjectProperty",ta,Mt):r(Ge.id,ta,Mt,"User"),testId:bt?`input-subject-addedrow-${w.id}`:`input-comp-addedrow-${w.id}-${Ge.id}`,resolvedDisplay:!0})});if(w.rowId==="ContractPrice"&&Xe){const ta=(bt?Na("SalesContractAmount"):Ge.fields?.SalesContractAmount)??{value:null,source:"User",hasConflict:!1,isVerified:!1},Mt=bt?void 0:Ge.fields?.ContractAmountUnknownIndicator,ms=ta?.value==null?"":String(ta.value),cr=bt?`input-subject-addedrow-${w.id}`:`input-comp-addedrow-${w.id}-${Ge.id}`,Cn=Rn=>{const hn=Rn.replace(/[$,\s]/g,"").trim();la("SalesContractAmount",hn===""?null:Number(hn))},Ai=Q("px-2 py-[5px]",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200");return e.jsx("div",{className:Ai,children:bt?e.jsx(FS,{value:ms===""?"":cf(ms),isSubject:!0,enumOptions:null,onCommit:Cn,source:ta?.source,userEdited:ta?.userEdited,inspectPill:Rt(!0,Ge.id),testId:cr,resolvedDisplay:!0}):e.jsx(PW,{amountField:ta,unknownField:Mt,onSelect:(Rn,hn,Ml)=>r(Ge.id,Rn,hn,Ml),fieldKey:`${w.id}-${Ge.id}`,entityLabel:ra,children:e.jsxs("div",{role:"button",tabIndex:0,className:"flex min-h-[18px] w-full items-center gap-2 text-left","data-testid":cr,children:[Rt(!1,Ge.id),ta.source&&e.jsx(Ji,{source:ta.source,userEdited:ta.userEdited,testId:`source-dot-comp-${w.id}-${Ge.id}`}),e.jsx("span",{className:Ou,children:String(Mt?.value)==="true"?"Unknown":ms?(()=>{const Rn=Number(String(ms).replace(/[$,\s]/g,""));return Number.isFinite(Rn)?cf(Rn):ms})():""})]})})})}if(w.rowId==="SalesContractDate"&&Xe){const ta=(bt?Na("SalesContractDate"):Ge.fields?.SalesContractDate)??{value:null,source:"User",hasConflict:!1,isVerified:!1},Mt=bt?void 0:Ge.fields?.ContractDateUnknownIndicator,ms=Mt?.value===!0||String(Mt?.value).toLowerCase()==="true",cr=ta?.value==null?"":String(ta.value),Cn=ms?"Unknown":cr?(()=>{const Rn=/^(\d{4})-(\d{2})-(\d{2})$/.exec(cr);return Rn?`${Rn[2]}/${Rn[3]}/${Rn[1]}`:cr})():"",Ai=bt?`input-subject-addedrow-${w.id}`:`input-comp-addedrow-${w.id}-${Ge.id}`;return e.jsx("div",{className:Q("px-2 py-[5px]",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:bt?e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[Rt(!0,t.id),ta?.source&&e.jsx(Ji,{source:ta.source,userEdited:ta.userEdited,testId:`source-dot-subject-${w.id}`}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(NH,{getValue:()=>ta?.value,setValue:(Rn,hn)=>la("SalesContractDate",hn),allowUnknown:!1,testId:Ai,resolvedDisplay:!0})})]}):e.jsx(wW,{dateField:ta,unknownField:Mt,allowUnknown:!0,onSelect:(Rn,hn,Ml)=>r(Ge.id,Rn,hn,Ml),fieldKey:`${w.id}-${Ge.id}`,entityLabel:ra,children:e.jsxs("div",{role:"button",tabIndex:0,className:"flex min-h-[18px] w-full items-center gap-2 text-left","data-testid":Ai,children:[Rt(!1,Ge.id),ta?.source&&e.jsx(Ji,{source:ta.source,userEdited:ta.userEdited,testId:`source-dot-comp-${w.id}-${Ge.id}`}),e.jsx("span",{className:Ou,children:Cn})]})})})}return w.rowId!=="TotalSalesConcessionAmount"||!Xe?null:e.jsx("div",{className:Q("px-2 py-[5px]",bt?"border-l border-slate-200":Za?"border-l-2 border-l-slate-300":"border-l border-slate-200"),children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Rt(bt,Ge.i
39d),e.jsx(AH,{getValue:ta=>{const Mt=bt?Ge.fields?.[ta]:Ge.transferHistory?.[0]?.[ta]??Ge.fields?.[ta];return qp(Mt)?.value??Mt},onTransactionChange:bt?Ce?(ta,Mt)=>Ce(ta,Mt):void 0:St?(ta,Mt)=>St(Ge.id,"User",ta,Mt):void 0,setValue:(ta,Mt)=>r(Ge.id,ta,Mt,"User"),testId:bt?`input-subject-addedrow-${w.id}`:`input-comp-addedrow-${w.id}-${Ge.id}`})]})})},gt="Not applicable — homeowner is not responsible for exterior maintenance (UAD 1800.0364)",Ra=Xe?[...ab,...BI]:mb,fa=w.source==="custom"?lB(w.label,Ra):null,Is=Ge=>Xe&&(Ge.rowId==="FinancingType"||Ge.rowId==="MortgageType"||Ge.rowId==="ContractPrice"&&nx("contractPrice",An)),cs=cB(w.label,oi.filter(Ge=>Ge.id!==w.id&&!(Ve&&Ni&&xh.get(Ge.rowId??"")===Ni)&&!Is(Ge)).map(Ge=>Ge.label)),br=fa?.group?.trim()??"",zr=br.length>0&&br.toLocaleLowerCase()===(w.group?.trim()??"").toLocaleLowerCase(),_s=cs?`Duplicate row label — another added row is also named "${w.label}". Consider removing one so the grid reads cleanly.`:fa?zr?`This label looks similar to “${fa.label}” which is already captured in ${br}. Use the standard field if that’s what you mean; otherwise, keep this Additional Row.`:`This label looks similar to “${fa.label}”${br?` which belongs in the “${br}” section`:" which is already available as a standard field"}. If that’s what you mean, remove this Additional Row and use the standard field${br?" in that section":""}; otherwise, keep this Additional Row.`:GD(w.label),et=_s?`${w.id}:${_s}`:null,pa=et!=null&&!el.has(et),Gt=Xe&&!!w.rowId&&yU(w.rowId),hs=Xe&&!!La&&(La==="NoFinancingTransactionIndicator"?!0:w.rowId==="ContractPrice"||La==="TotalSalesConcessionAmount"||La==="SalesContractDate"?!(fs&&ps):!!La&&!bE(La,An.subject)),qr=w.rowId?SU[w.rowId]??"Not applicable to the subject":"Not applicable to the subject",ys=hs&&dT(Qs,Qs)?.subjectText.trim()?Kx(Qs,"subject"):"",yr=(()=>{if(ke){const Ge={...t,subjectProperty:qa,...Be?.site?{site:Be.site}:{}};return ke==="LotSizeAreaMeasure"?zE(aS(Ge,"LandOwnedInCommonIndicator"))?{isMissing:!1,semanticState:"em-dash"}:{isMissing:!Vh(qE(Ge).value)}:{isMissing:!Vh(aS(Ge,ke))}}if(tt&&Jr)return{isMissing:!ua.some(Ge=>Ge.category===Jr)};if(X){const Ge=Xy(ne)[X];return{isMissing:Jy(X,Ge,"subject")}}return null})(),Yr=Gl({fieldName:w.rowId??w.id,isMissing:yr?.isMissing??!Vh(Ca),semanticState:ys?"em-dash":Gt||hs?"gray":yr?.semanticState});return e.jsxs("div",{"data-testid":`added-row-${w.id}`,className:Q("grid border-b border-slate-200 transition-colors duration-100 hover:bg-blue-50/50",Xs?"bg-slate-50":"bg-white",im===w.id&&"ring-2 ring-inset ring-blue-400 bg-blue-50"),style:{gridTemplateColumns:Hn},children:[e.jsxs("div",{className:Q("px-3 flex items-center gap-1.5 w-[170px] min-w-[170px] group/customrow sticky left-0 z-[2]",Jr?"min-h-[18px] py-0 text-[11px] leading-4":"py-[5px]",ar&&!Xs&&"pl-7",Xs?"bg-slate-50":"bg-white"),children:[e.jsx("span",{className:Q("min-w-0 flex-1 font-semibold text-slate-700 truncate","text-[12px]"),children:w.rowId==="RenewableEnergyComponentType"&&"Renewable Energy Component"||w.rowId==="GreenCertificationName"&&"Building Certification"||w.rowId==="EfficiencyRatingName"&&"Efficiency Rating"||w.label}),it&&!nt&&w.source==="catalog"&&w.rowId&&!(sa&&sd.includes(w.rowId))&&!Ts&&!Jr&&!(Ve&&xh.has(w.rowId))&&e.jsx(Fs,{section:"salesGrid",fieldName:w.rowId}),pa&&e.jsx("button",{type:"button",title:_s??void 0,"aria-label":"Dismiss row hint",onClick:()=>Jn(Ge=>{const bt=new Set(Ge);return bt.add(et),bt}),className:"shrink-0 text-amber-500 hover:text-amber-700 transition-colors","data-testid":`row-hint-${w.id}`,children:e.jsx(on,{className:"w-3 h-3"})}),QW,Qr&&zn&&!hr&&w.rowId&&ac[w.rowId]&&(()=>{const Ge=w.rowId,bt=ac[Ge],Za=bt,ra=bt.allowFlatBasis?qn[Ge]??"perUnit":"perUnit",ta=_c===Ge;return e.jsxs(xn,{open:ta,onOpenChange:Mt=>bd(Mt?Ge:null),children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{type:"button","data-testid":`chip-auto-${Ge}`,title:`Auto-adjuster — apply one rate across all comps for ${w.label}`,className:Q("ml-auto shrink-0 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-semibold ring-1 transition-colors",ta?"bg-blue-600 text-white ring-blue-600":"bg-white text-blue-700 ring-blue-200 hover:bg-blue-50"),children:[e.jsx(Bx,{className:"w-3 h-3"}),Za.label]})}),e.jsx(yn,{align:"start",className:"w-64 p-3",sideOffset:4,collisionPadding:12,children:e.jsxs("div",{className:"space-y-2 text-left",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-slate-500",children:["Auto-adjuster · ",w.label]}),e.jsx("p",{className:"text-[10px] text-slate-500 leading-snug",children:Za.hint}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-[10px] font-medium text-slate-500",children:Za.rateLabel}),e.jsx(ze,{"data-testid":`input-auto-rate-${Ge}`,autoFocus:!0,value:go[Za.rateKey]??"",onChange:Mt=>Zd(ms=>({...ms,[Za.rateKey]:Mt.target.value})),placeholder:Za.ratePlaceholder,className:"h-7 w-full text-xs",inputMode:"decimal"})]}),bt.rate2Key&&e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-[10px] font-medium text-slate-500",children:bt.rate2Label}),e.jsx(ze,{"data-testid":`input-auto-rate2-${Ge}`,value:go[bt.rate2Key]??"",onChange:Mt=>Zd(ms=>({...ms,[bt.rate2Key]:Mt.target.value})),placeholder:bt.rate2Placeholder,className:"h-7 w-full text-xs",inputMode:"decimal"})]}),bt.thresholdUnit&&e.jsxs("div",{children:[e.jsxs("label",{className:"mb-1 block text-[10px] font-medium text-slate-500",children:["Threshold — only adjust when difference exceeds (",bt.thresholdUnit,")"]}),e.jsx(ze,{"data-testid":`input-auto-threshold-${Ge}`,value:Mu[Ge]??"",onChange:Mt=>hp(ms=>({...ms,[Ge]:Mt.target.value})),placeholder:"Optional, e.g. 100",className:"h-7 w-full text-xs",inputMode:"decimal"}),e.jsx("p",{className:"mt-1 text-[10px] text-slate-500 leading-snug",children:"Comps at or within the threshold get no adjustment; beyond it the full difference is adjusted."})]}),e.jsxs("div",{className:"flex items-start gap-1.5 rounded bg-slate-50 px-2 py-1 text-[10px] text-slate-500",children:[e.jsx(on,{className:"h-3 w-3 shrink-0 mt-0.5"}),"Overwrites every comp's adjustment on this line."]}),e.jsxs(De,{size:"sm",onClick:()=>{Bg(Ge,lc(go[Za.rateKey]??""),bt.rate2Key?lc(go[bt.rate2Key]??""):void 0,{basis:ra,threshold:bt.thresholdUnit?lc(Mu[Ge]??""):void 0}),bd(null)},className:"w-full h-7 gap-1 text-xs bg-blue-600 hover:bg-blue-700","data-testid":`button-auto-apply-${Ge}`,children:[e.jsx(Bs,{className:"h-3.5 w-3.5"})," Apply to all comps"]}),e.jsx(De,{variant:"outline",size:"sm",onClick:()=>{yl(Ge),bd(null)},className:"w-full h-7 text-xs text-slate-500","data-testid":`button-auto-clear-${Ge}`,children:"Reset to $0"})]})})]},`chip-popover-${Ge}`)})()]}),hr&&e.jsx("div",{className:Q("px-2 border-r border-slate-200 text-[10px] text-slate-300 flex items-center",Jr?"min-h-[18px] py-0":"py-[5px]"),children:e.jsx(kn,{state:"blank"})}),e.jsx("div",{className:Q("sticky z-[2] h-full min-h-8 self-stretch",Yr),style:{left:hr?"320px":"170px"},"data-testid":`subject-surface-addedrow-${w.id}`,children:Gt||hs||cn&&!yE(An.subject)?e.jsx("div",{className:Q("px-2 py-[5px] border-l border-slate-200 flex items-center",Gl({fieldName:w.rowId??w.id,isMissing:!1,semanticState:ys?"em-dash":"gray"})),title:ys||(Gt?qr:gt),"data-testid":ys?`dash-subject-addedrow-${w.id}`:`na-subject-addedrow-${w.id}
39`,"aria-disabled":"true",children:ys?e.jsx(kn,{state:"em-dash"}):null}):Jt(t,!0,!1,"Subject")??Bt(t,!0,!1)??Io(t,!0,!1)??dr(t,!0,!1)??Qi(t,!0,!1)??Ia(t,!0,!1)??_r(t,!0,!1)??e.jsx(FS,{value:Ca,enumOptions:Pt,optionLabel:Zr,isSubject:!0,onCommit:Ge=>{if(w.source==="custom"&&w.group==="Vehicle Storage"&&vt){Re?.("subject",w.id,Ge);return}r(t.id,ka,Ge,"User")},testId:`input-subject-addedrow-${w.id}`,emptyPlaceholder:ke||Ye?"":void 0,source:ke?Yt(t,!0).source:jt?xt?.[jt]?.source:Ye&&Ca?"user":void 0,userEdited:ke?Yt(t,!0).userEdited:jt?xt?.[jt]?.userEdited:Ye,inspectPill:Rt(!0,t.id)??ha(!0,t.id),required:dg.has(w.rowId??ka)})}),$a.map((Ge,bt)=>{const Za=cn&&!yE(An.comps[bt]),ra=Xe&&!!w.rowId&&sd.includes(w.rowId),ta=lr(Ge,"comparable"),Mt=!Za&&!ra&&Xe&&!!La&&(ta?ta.state==="em-dash":!bE(La,An.comps[bt])),ms=Mt?ta?.state==="em-dash"?Kx(Qs,"comp")||"Not applicable":dT(Qs,Qs)?.compText.trim()?Kx(Qs,"comp"):"":"";return e.jsxs(Mn.Fragment,{children:[Za||Mt?e.jsx("div",{className:Q("px-2 py-[5px] flex items-center text-slate-700",Gl({fieldName:w.rowId??w.id,isMissing:!1,semanticState:ms?"em-dash":"gray"}
39),bt===0?"border-l-2 border-l-slate-300":"border-l border-slate-200"),title:Za?gt:ms||"Not applicable","data-testid":`na-comp-addedrow-${w.id}-${Ge.id}`,children:ms?e.jsx(kn,{state:"em-dash"}):null}):Jt(Ge,!1,bt===0,`Comp ${bt+1}`)??Bt(Ge,!1,bt===0)??Io(Ge,!1,bt===0)??dr(Ge,!1,bt===0)??Qi(Ge,!1,bt===0)??Ia(Ge,!1,bt===0)??_r(Ge,!1,bt===0)??e.jsx(FS,{value:(()=>{const cr=String(w.source==="custom"&&w.group==="Vehicle Storage"&&vt?Ge.vehicleStorageCustomRows?.[w.id]??"":Ge.fields[ka]?.value??"");if(w.rowId==="SaleToListPriceRatioPercent"){const Cn=rV(Ge.fields,vW(Ge,bt+1,Z));return Cn==null?"":String(Cn)}return cr||!Ys?cr:Ms(Ge)})(),enumOptions:Pt,optionLabel:Zr,isFirstComp:bt===0,disabled:w.rowId==="SaleToListPriceRatioPercent",readOnlyDisplay:w.rowId==="SaleToListPriceRatioPercent",displaySuffix:w.rowId==="SaleToListPriceRatioPercent"?"%":void 0,onCommit:cr=>{if(w.source==="custom"&&w.group==="Vehicle Storage"&&vt){Re?.(Ge.id,w.id,cr);return}r(Ge.id,ka,cr,"User")},testId:`input-comp-addedrow-${w.id}-${Ge.id}`,emptyPlaceholder:ke||Ye?"":void 0,source:ke?Yt(Ge,!1).source:Ye&&Ge.vehicleStorageCustomRows?.[w.id]?"user":void 0,userEdited:ke?Yt(Ge,!1).userEdited:Ye,inspectPill:Rt(!1,Ge.id)??ha(!1,Ge.id),required:dg.has(w.rowId??ka)}),Qr&&(Ye?e.jsx("div",{className:"w-[60px] min-w-[60px]","aria-hidden":"true","data-testid":`vehicle-storage-custom-row-adjustment-spacer-${w.id}-${Ge.id}`}):xe?ca(Ge.id,Da)?e.jsx("div",{className:"px-1.5 py-[5px] w-[60px] min-w-[60px] flex items-center justify-start text-[10px] text-slate-500",title:"Saved adjustment — this row is reference-only per UAD 3.6 Appendix B-1","data-testid":`readonly-adjustment-${w.id}-${Ge.id}`,children:So(Pn(Ge.id,Da))}):e.jsx("div",{className:"w-[60px] min-w-[60px] self-stretch bg-slate-100",title:"Not adjustable for this row","data-testid":`na-adjustment-${w.id}-${Ge.id}`}):e.jsx(Ph,{propertyId:Ge.id,fieldName:Da,adjustment:Pn(Ge.id,Da),hasExplicitValue:ca(Ge.id,Da),onAdjustmentChange:wn,suggestion:null,salePrice:pn(Ge),isSacred:xr.current.has(`${Ge.id}:${Da}`),isPulsing:ec.has(`${Ge.id}:${Da}`),isJustFilled:rl.has(`${Ge.id}:${Da}`),onResetSacred:no,prereqsMet:F!==!1,compact:!!Jr}))]},Ge.id)})]},w.id)},di=e.jsx("div",{className:"px-4 py-10 text-center text-[12px] text-slate-400","data-testid":"grid-filter-empty",children:ds&&!Va&&!xs?"No rows need adjustment — every comparable that differs from the subject already has an adjustment.":xs&&!Va&&!ds?"No required data missing — all required fields are complete.":Va&&!xs&&!ds?"No conflicts found — sources agree on all displayed fields.":"No rows match the active filters."});if(h==="str"){const w=DP(),wt=Va||xs||ds?w.filter(Pt=>Pt===Rs||Va&&tc(Pt)||xs&&wi(Pt)||ds&&Rp(Pt)||ds&&ah(Pt)):w;return wt.length===0?di:e.jsx(e.Fragment,{children:wt.map((Pt,Ba)=>mt(Pt))})}const us=Va||xs||ds,ks=(w,wt)=>w==="dataSource"||w==="mlsNumber"?$?wt==="general":Xe?w==="dataSource"&&wt==="generalInfo":wt==="generalInfo":w==="financing"?!1:w==="listPrice"||w==="listingStatus"||w==="daysOnMarket"||w==="attachedDetached"?Xe:A&&w==="neighborhoodName"?!1:w==="proximity"?Xe:w==="priorSaleDate"||w==="priorSalePrice"||A&&(w==="location"||w==="site"||w==="view")?!1:!Xe||$&&(w==="aboveGrade"||w==="gla"||w==="salePricePerGLA"||w==="heatingCooling"||w==="garageCarport"||w==="porchPatioDeck")?!0:w==="salePricePerGLA"||w==="financingConcessions"||w==="heatingCooling"||w==="functionalUtility"?!1:w==="constructionMethod"?FA("ConstructionMethodType",An):w==="exteriorQuality"?Xe?!1:gE(An):w==="interiorQuality"&&Xe?!1:w==="qualityCondition"&&Xe?$:!(w==="porchPatioDeck"||w==="aboveGrade"||w==="belowGrade"||w==="gla"||w==="energyEfficient"),On=new Set(["saleType","financing","concessions"]),ui=w=>J.has(w)&&!(Xe&&On.has(w)),Xc=(w,wt)=>!$||BW(w)?!0:Pj.has(w)||wt?xa:Gs,Nc=(w,wt)=>!us&&!Xc(w,wt)?!1:!!(!us||w===Rs||Va&&tc(w)||xs&&wi(w)||!wt&&ds&&Rp(w)||!wt&&ds&&ah(w)||!wt&&ds&&du(w)),Pd=w=>w.some(wt=>{const Pt=xt?.[wt]?.value;return Pt!=null&&Pt!==""?!0:$a.some(Ba=>{const Ts=Ba.fields?.[wt]?.value;return Ts!=null&&Ts!==""})}),Dr=w=>{if(!$||us)return!0;const wt=Tu(w);return kb(wt)?xa:Gs},co=w=>{if(!w.optional)return!0;
39if(w.id==="project"&&Xe){const Ba=lP(nt?rt??{}:xt??{},$a.map(ia=>ia.fields)),Ts=$a.reduce((ia,Ca)=>({...ia,...mS(Ca.fields)}),{});return YG({automaticSection:Ba,automaticSpecialAssessment:$a.some(ia=>gx(ia.fields))||gx(rt??(nt?rt??{}:xt??{})),manualRelevance:Ts})}if(w.id==="energy"&&Ve)return Yi.some(Ba=>Ba.relevant!==!1);if(w.id==="amenities"&&tt)return ba.length>0;const wt=Tn[w.id];if(wt!==void 0)return wt;if(w.autoOnly&&oi.some(Ba=>Ba.rowId&&!wd(Ba)&&!To(Ba)&&Dh(Ba.rowId??"",og(Ba.rowId??""),A?"urar36":"legacy")===w.id))return!0;if(!xc)return!1;if(w.id==="energy"&&Ve&&Yi.some(Ba=>["RenewableEnergyComponentType","GreenCertificationName","EfficiencyRatingName"].includes(Ba.rowId))||oi.some(Ba=>!wd(Ba)&&Dh(Ba.rowId??"",og(Ba.rowId??""),A?"urar36":"legacy")===w.id))return!0;const Pt=[...w.fields,...(mn.get(w.id)??[]).map(Ba=>Ba.id)];return Pd(Pt)?!0:!!s?.[w.id]},Od=Wt.filter(w=>w.optional&&!w.autoOnly&&!(w.id==="energy"&&Ve&&co(w)&&au!=="add-section")&&!(w.id==="amenities"&&tt&&co(w)&&Fr!=="add-section")&&!(w.id==="project"&&co(w)&&Gi!=="add-section")),kl=Yc?e.jsxs(e.Fragment,{children:[to!==null&&!["siteInfo","vehicle","project","energy","amenities"].includes(to)&&e.jsx("button",{type:"button",className:"fixed inset-0 z-50 cursor-default bg-white/50","aria-label":"Close row picker","data-testid":"band-picker-grid-scrim",onMouseDown:()=>vn(!1)}),e.jsxs("div",{className:"relative z-[60] w-80 rounded-md bg-white text-left text-xs normal-case font-normal tracking-normal shadow-lg ring-1 ring-slate-200","data-testid":"menu-add-row",children:[!Mi&&e.jsx("p",{className:"px-3 py-2 text-[10px] font-semibold uppercase tracking-wide text-slate-400 border-b border-slate-200/60",children:"Schema rows — each brings its own input type"}),!Mi&&e.jsxs("div",{className:"relative border-b border-slate-200/60 px-3 py-2",children:[e.jsx(Eu,{className:"pointer-events-none absolute left-5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400"}),e.jsx("input",{type:"text",value:Gc,onChange:w=>$r(w.target.value),autoFocus:!0,placeholder:"Search rows…",className:"w-full rounded-md border border-slate-200 bg-white py-1.5 pl-7 pr-2 text-xs text-slate-700 placeholder:text-slate-400 focus:outline-none focus:ring-1 focus:ring-blue-400","data-testid":"input-picker-row-search"})]}),e.jsxs("div",{className:"max-h-72 overflow-y-auto py-1",children:[(()=>{if(!Xe||Mi&&Mi!=="dwelling")return null;const w=oi.map(Pt=>({rowId:Pt.id,kind:Pt.source==="catalog"?"optional":"custom",label:Pt.label}));if(cU(w))return null;const wt=Gc.trim().toLowerCase();return wt&&!ug.toLowerCase().includes(wt)&&!"unit count".includes(wt)?null:e.jsxs("div",{children:[e.jsx("div",{className:"px-3 pt-2 pb-1 text-[9px] font-semibold uppercase tracking-wide text-slate-400",children:sg}),e.jsxs("button",{type:"button",onClick:()=>{const Pt=`custom_${Date.now()}`;zc(Ba=>[...Ba,{id:Pt,label:ug,source:"custom",group:sg}]),vn(!1),Nn(null),Ad(Pt),window.setTimeout(()=>{document.querySelector(`[data-testid="added-row-${Pt}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},50),window.setTimeout(()=>Ad(Ba=>Ba===Pt?null:Ba),2500)},className:"flex w-full items-center justify-between gap-2 px-3 py-1.5 text-left text-xs text-slate-700 hover:bg-blue-50","data-testid":"button-pick-row-total-units",children:[e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"font-medium truncate",children:ug}),e.jsx("span",{className:"text-[10px] text-slate-400 truncate",children:"Per Fannie Mae: report a unit-count difference (and its adjustment) on this row inside Dwelling(s)."})]}),e.jsx("span",{className:"rounded bg-slate-100 px-1.5 py-0.5 text-[9px] font-medium uppercase text-slate-500 shrink-0",children:"suggested"})]})]})})(),(()=>{const w=new Set(oi.filter(La=>La.source==="catalog"&&La.rowId).map(La=>La.rowId));if(sa)for(const La of Xo)(La.rowId==="HazardZoneType"?La.relevant===!0:La.relevant!==!1)&&w.add(La.rowId);const wt=MD(Xe,!1,A),Pt=sa?sd.map(La=>({rowId:La,label:tS[La],group:"Site",inputType:La==="LotSizeAreaMeasure"?"number":"text"})):[],Ba=Array.from(new Map([...wt,...Pt].map(La=>[La.rowId,La])).values()).filter(La=>!$||!Oj(La.rowId)),Ts=La=>{const lr=fU(La),Ys=lr?nx(lr.gateId,An):!1;return{rule:lr,conditionApplies:Ys,locked:!!lr&&(!!lr.automaticOnly||Ys)}},ia=Mi?Ba.filter(La=>Dh(La.rowId,La.group,A?"urar36":"legacy")===Mi):Ba;if(Mi==="siteInfo"){const La=new Map(sd.map((lr,Ys)=>[lr,Ys]));ia.sort((lr,Ys)=>(La.get(lr.rowId??"")??Number.MAX_SAFE_INTEGER)-(La.get(Ys.rowId??"")??Number.MAX_SAFE_INTEGER))}if(Mi){if(ia.length===0)return null;const La=new Map;for(const lr of ia){const Ys=La.get(lr.group)??[];Ys.push(lr),La.set(lr.group,Ys)}return Array.from(La.entries()).map(([lr,Ys])=>e.jsxs("div",{children:[e.jsx("div",{className:"px-3 pt-2 pb-1",children:e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-wide text-slate-400",children:lr})}),Ys.map(Ms=>{const{rule:Zr,locked:cn}
39=Ts(Ms.rowId),Jr=cn,Wn=w.has(Ms.rowId)||Ms.rowId==="HazardZoneType"&&ls||Ms.rowId==="LotSizeAreaMeasure"&&Ps;return e.jsxs("label",{className:Q("flex w-full items-center gap-2 px-3 py-1.5 text-xs text-slate-700 hover:bg-blue-50 select-none",Jr?"cursor-not-allowed":"cursor-pointer"),"data-testid":`option-row-${Ms.rowId}`,onMouseDown:Dt=>Dt.stopPropagation(),children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 rounded border-slate-300 accent-blue-600 shrink-0 cursor-pointer",checked:Wn,disabled:Jr,onChange:Dt=>{if(!Jr){if(sa&&sd.includes(Ms.rowId)){const Da=Xo.filter(Ia=>Ia.rowId!==Ms.rowId);rm(Dt.target.checked?[...Da,{rowId:Ms.rowId,kind:"optional",label:Ms.label,group:"Site",relevant:!0}]:Da);return}if(Dt.target.checked){const Da=`catalog_${Ms.rowId}_${Date.now()}_${Math.random().toString(36).slice(2,6)}`;zc(Ia=>Ia.some(ar=>ar.source==="catalog"&&ar.rowId===Ms.rowId)?Ia:[...Ia,{id:Da,label:Ms.label,source:"catalog",rowId:Ms.rowId,group:Ms.group}])}else zc(Da=>Da.filter(Ia=>!(Ia.source==="catalog"&&Ia.rowId===Ms.rowId)))}}}),e.jsx("span",{className:"font-medium truncate",children:Ms.label}),Zr&&e.jsx(Lj,{rowId:Ms.rowId,label:Ms.label,ruleText:hE(Zr.gateId)?.text??"This row is included automatically when its UAD 3.6 condition applies.",outputRule:Zr.outputRule,showAutomaticInclusion:Zr.showAutomaticInclusion})]},Ms.rowId)})]},lr))}const Ca=ia.filter(La=>!w.has(La.rowId));if(Ca.length===0)return e.jsx("div",{className:"px-3 py-2 text-xs text-slate-500","data-testid":"text-catalog-empty",children:"All available rows have been added."});const Ls=Gc.trim().toLowerCase(),Qs=Ls?Ca.filter(La=>La.label.toLowerCase().includes(Ls)||La.group.toLowerCase().includes(Ls)):Ca;if(Qs.length===0)return e.jsxs("div",{className:"px-3 py-2 text-xs text-slate-500","data-testid":"text-catalog-no-match",children:['No fields match "',Gc.trim(),'".']});const Lt=new Map;for(const La of Qs){const lr=Lt.get(La.group)??[];lr.push(La),Lt.set(La.group,lr)}return Array.from(Lt.entries()).map(([La,lr])=>e.jsxs("div",{children:[e.jsxs("div",{className:"px-3 pt-2 pb-1 flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-wide text-slate-400",children:La}),su.size>0&&e.jsxs("button",{type:"button","data-testid":"button-picker-add-selected",className:"rounded bg-blue-600 px-2.5 py-0.5 text-[11px] font-semibold text-white hover:bg-blue-700 shrink-0",onClick:()=>{const Ys=[...su],Ms=sa?Ys.filter(Wn=>sd.includes(Wn)):[];if(Ms.length>0){const Wn=new Set(Ms),Dt=Xo.filter(Da=>!Wn.has(Da.rowId));rm([...Dt,...Ms.map(Da=>({rowId:Da,kind:"optional",label:tS[Da]??Da,group:"Site",relevant:!0}))])}const Zr=Ys.filter(Wn=>!Ms.includes(Wn)),cn=new Map(Ba.map(Wn=>[Wn.rowId,Wn]));let Jr="";zc(Wn=>{let Dt=[...Wn];for(const Da of Zr){if(Dt.some(ar=>ar.source==="catalog"&&ar.rowId===Da))continue;const Ia=`catalog_${Da}_${Date.now()}_${Math.random().toString(36).slice(2,6)}`;Jr=Ia,Dt=[...Dt,{id:Ia,label:cn.get(Da)?.label??Da,source:"catalog",rowId:Da,group:cn.get(Da)?.group??"General Information"}]}return Dt}),Ei(new Set),vn(!1),Nn(null),Jr&&(Ad(Jr),window.setTimeout(()=>{document.querySelector(`[data-testid="added-row-${Jr}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},50),window.setTimeout(()=>Ad(Wn=>Wn===Jr?null:Wn),2500))},children:["Add"," ",su.size===lr.length?"all":su.size]})]}),lr.map(Ys=>{const{rule:Ms,locked:Zr}=Ts(Ys.rowId),cn=Zr;return e.jsxs("label",{className:Q("flex w-full items-center gap-2 px-3 py-1.5 text-xs text-slate-700 hover:bg-blue-50",cn?"cursor-not-allowed":"cursor-pointer"),"data-testid":`option-row-${Ys.rowId}`,children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 rounded border-slate-300 accent-blue-600 shrink-0",checked:su.has(Ys.rowId)||Ys.rowId==="HazardZoneType"&&ls||Ys.rowId==="LotSizeAreaMeasure"&&Ps,disabled:cn,onChange:Jr=>{cn||Ei(Wn=>{const Dt=new Set(Wn);return Jr.target.checked?Dt.add(Ys.rowId):Dt.delete(Ys.rowId),Dt})}}),e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-1",children:[e.jsx("span",{className:"font-medium truncate",children:Ys.label}),Ms&&e.jsx(Lj,{rowId:Ys.rowId,label:Ys.label,ruleText:hE(Ms.gateId)?.text??"This row is included automatically when its UAD 3.6 condition applies.",outputRule:Ms.outputRule,showAutomaticInclusion:Ms.showAutomaticInclusion}),Xe&&!!NL[Ys.rowId]&&!FA(Ys.rowId,An)&&e.jsx("span",{className:"shrink-0 rounded bg-amber-50 px-1.5 py-0.5 text-[9px] font-medium text-amber-600",title:"This row's UAD 3.6 display condition isn't met by the subject or any comparable yet — it will be saved but stay hidden until it applies.","data-testid":`badge-row-gated-${Ys.rowId}`,children:"doesn't apply yet"})]})]},Ys.rowId)})]},La))})()]})]})]}):null,ih=fl?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"fixed inset-0 z-50 cursor-default bg-white/50","aria-label":"Close Project Information row selector","data-testid":"project-picker-grid-scrim",onMouseDown:()=>li(null)}),e.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-1 w-80 rounded-md bg-white p-2 text-left text-xs font-normal normal-case tracking-normal shadow-lg ring-1 ring-slate-200","data-testid":"project-row-picker",children:[e.jsx("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:"Project Information rows"}),yk.map(w=>{const wt=w==="ProjectName"||w==="AssociationSpecialAssessmentStatusType"&&(gx(rt??(nt?rt??{}:xt??{}))||$a.some(ia=>gx(ia.fields))),Pt=$a.some(ia=>mS(ia.fields)[w]===!0),Ba=w==="ProjectName"?"Project Name | Same Project as Subject":w==="AssociationChargeAmount"?"Monthly Fee":w==="ProjectCommonAmenityType"?"Common Amenities/Services":"Special Assessments",Ts=_G[w];return e.jsxs("label",{className:Q("flex items-center gap-2 rounded px-2 py-1.5 text-xs",wt?"cursor-not-allowed text-slate-400":"cursor-pointer text-slate-700 hover:bg-blue-50"),children:[e.jsx("input",{type:"checkbox","data-testid":`project-picker-${w}`,className:"h-3.5 w-3.5 accent-blue-600 disabled:cursor-not-allowed disabled:opacity-50",checked:Pt,disabled:wt,onChange:ia=>{const Ca=ia.target.checked;for(const Ls of $a){const Qs=mS(Ls.fields);r(Ls.id,Sk,JSON.stringify({...Qs,[w]:Ca}),"User")}Bn(Ls=>
39({...Ls,project:!0}))}}),e.jsx("span",{children:Ba}),Ts&&e.jsx(Lj,{rowId:w,label:Ba,ruleText:Ts})]},w)})]})]}):null,bm=e.jsx("div",{className:"border-b border-slate-200/40 bg-white",style:{width:"100%"},children:e.jsxs("div",{className:"px-3 py-2 w-max flex items-center gap-x-3 bg-white sticky left-0 z-[2]",children:[gl&&gl.bandId===null&&e.jsxs("div",{className:"w-full flex items-start justify-between gap-2 rounded-md bg-amber-50 border border-amber-200 px-3 py-1.5 text-[11px] text-amber-800","data-testid":"notice-hidden-added-row",children:[e.jsx("span",{children:gl.text}),e.jsx("button",{type:"button",onClick:()=>Nn(null),className:"shrink-0 font-semibold text-amber-600 hover:text-amber-800","data-testid":"button-dismiss-hidden-row-notice",children:"Dismiss"})]}),e.jsxs("div",{className:"relative inline-block",ref:_o,children:[!A&&!$&&e.jsxs("button",{onClick:()=>{tl(null),Ao(null),vn(w=>!w)},className:"flex items-center gap-2 rounded-md bg-blue-600 px-3 py-2 text-xs font-semibold text-white shadow-sm hover:bg-blue-700 transition-colors","data-testid":"button-add-row",children:[e.jsx(un,{className:"w-4 h-4"}),"Add additional row"]}),!A&&!$&&Yc&&to===null&&e.jsx("div",{className:"absolute left-0 z-30 mt-1",children:kl})]}),!$&&Od.length>0&&e.jsxs("div",{className:Q("relative flex flex-wrap items-center gap-1.5",(au==="add-section"||fl)&&"z-50"),"data-testid":"b1-optional-section-strip",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-400 mr-1",children:"Add section:"}),Od.map(w=>{const wt=co(w);return e.jsxs("div",{className:Q("relative inline-flex",(w.id==="energy"&&au==="add-section"||w.id==="project"&&fl)&&"z-50"),children:[e.jsxs("button",{type:"button",onClick:Pt=>{if(w.id==="project"){Pt.stopPropagation(),li("add-section");return}if(w.id==="energy"&&Ve){Tr("add-section");return}if(w.id==="amenities"&&A){Zl("add-section");return}const Ba=Pt.currentTarget.closest('[data-testid="sales-comparison-grid"]');Bn(Ts=>({...Ts,[w.id]:!wt})),Ee(Ts=>wt?Ts.filter(ia=>ia!==w.id):Ts.includes(w.id)?Ts:[...Ts,w.id]),wt||window.setTimeout(()=>{(Ba??document).querySelector(`[data-testid="band-header-${w.id}"]`)?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)},className:Q("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium ring-1 transition-colors",wt?"bg-blue-600 text-white ring-blue-600":"bg-white text-slate-500 ring-slate-200 hover:bg-slate-50"),"data-testid":`toggle-band-${w.id}`,children:[wt?e.jsx(Bs,{className:"h-3 w-3"}):e.jsx(un,{className:"h-3 w-3"}),w.title,s?.[w.id]&&e.jsxs("span",{className:Q("text-[9px] font-medium normal-case",wt?"text-blue-100":"text-emerald-600"),title:s[w.id].reason,"data-testid":`detected-cue-${w.id}`,children:["·"," ",VD(s[w.id])]})]}),w.id==="project"&&Gi==="add-section"&&ih,Ve&&w.id==="energy"&&au==="add-section"&&e.jsx(IP,{entries:Yi,placement:"above",dimBackground:!0,onClose:()=>Tr(null),onApply:Pt=>{sm(Pt)}}),A&&w.id==="amenities"&&Fr==="add-section"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"fixed inset-0 z-50 cursor-default bg-white/50","aria-label":"Close Property Amenities row selector","data-testid":"amenities-picker-grid-scrim",onMouseDown:()=>Zl(null)}),e.jsxs("div",{ref:qc,className:"absolute bottom-full left-0 z-[60] mb-1 w-80 rounded-md bg-white text-left text-xs font-normal normal-case tracking-normal shadow-lg ring-1 ring-slate-200","data-testid":"amenities-row-picker",children:[e.jsx("div",{className:"px-3 pb-1 pt-2",children:e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-wide text-slate-400",children:"Property Amenities"})}),e.jsx("div",{className:"max-h-72 overflow-y-auto py-1",children:cd.map(Pt=>{const Ba=ba.includes(Pt);return e.jsxs("label",{className:"flex w-full cursor-pointer select-none items-center gap-2 px-3 py-1.5 text-xs text-slate-700 hover:bg-blue-50",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 shrink-0 cursor-pointer rounded border-slate-300 accent-blue-600",checked:Ba,onChange:Ts=>{const ia=new Set(ba);Ts.target.checked?ia.add(Pt):ia.delete(Pt),bf(cd.filter(Ca=>ia.has(Ca)))}}),e.jsx("span",{className:"truncate font-medium",children:rg[Pt]})]},Pt)})})]})]})]},w.id)})]})]})}),qg=Wt.some(w=>[...w.fields,...w.id==="units"?ts:[]].some(wt=>!ui(wt)&&ks(wt,w.id)&&Nc(wt,!1)))||(ds||xs)&&Wt.some(w=>(!w.optional||co(w))&&(mn.get(w.id)??[]).some(wt=>!kb(Tu(wt))&&nl(wt)&&Ku(wt)&&(xs?wi(wt.rowId??Tu(wt)??wt.id):Nc(wt.id,!1))))||Xe&&!$&&xs&&["OverallQualityRatingCode","OverallConditionRatingCode"].some(w=>wi(w))||Xe&&xs&&["SiteInfluenceType","ViewType"].some(w=>wi(w));if(us&&!qg)return e.jsxs(e.Fragment,{children:[di,bm]});const If=w=>{if(!(vc(w)||nc(w)))return!w.rowId&&w.group===sg?"dwelling":!w.rowId&&w.group==="Vehicle Storage"?"vehicle":Dh(w.rowId,w.group??og(w.rowId??""),A?"urar36":"legacy")},ym=new Map(sd.map((w,wt)=>[w,wt])),Yg=Xo.filter(w=>w.rowId==="HazardZoneType"?w.relevant===!0||ls:w.relevant!==!1).sort((w,wt)=>
39(ym.get(w.rowId)??Number.MAX_SAFE_INTEGER)-(ym.get(wt.rowId)??Number.MAX_SAFE_INTEGER)),xu=w=>{const wt=w==="siteInfo"&&sa?Yg.map(Pt=>({id:Pt.rowId,label:tS[Pt.rowId]??Pt.label?.trim()??Pt.rowId,source:"catalog",rowId:Pt.rowId,group:"Site",relevant:!0})):w==="energy"&&Ve?Array.from(new Map(Yi.filter(Pt=>Pt.relevant!==!1&&xh.has(Pt.rowId)).map(Pt=>[xh.get(Pt.rowId),Pt])).entries()).map(([Pt])=>({id:Pt,label:Pt==="RenewableEnergyComponentType"?"Renewable Energy Component":Pt==="GreenCertificationName"?"Building Certification":"Efficiency Rating",source:"catalog",rowId:Pt,relevant:!0})):w==="vehicle"&&vt?am.filter(Pt=>Pt.kind==="custom"&&Pt.group==="Vehicle Storage"&&Pt.relevant!==!1&&typeof Pt.customId=="string").map(Pt=>({id:Pt.customId,label:Pt.label?.trim()||"Additional Row",source:"custom",group:"Vehicle Storage",relevant:!0})):oi.filter(Pt=>If(Pt)===w&&!(Ve&&w==="energy")&&!wd(Pt)&&!vc(Pt)&&!nc(Pt)&&nl(Pt));if(w==="outbuilding"){const Pt=new Map(gU(wt.map(Ba=>Ba.rowId??"")).map((Ba,Ts)=>[Ba,Ts]));return[...wt].sort((Ba,Ts)=>(Pt.get(Ba.rowId??"")??0)-(Pt.get(Ts.rowId??"")??0))}if(w==="energy"){const Pt=["RenewableEnergyComponentType","GreenCertificationName","EfficiencyRatingName"],Ba=Ts=>{const ia=Ts.rowId?Pt.indexOf(Ts.rowId):-1;return ia===-1?Pt.length:ia};return[...wt].sort((Ts,ia)=>Ba(Ts)-Ba(ia))}return wt},vi=[],Gg=new Map(Wt.map((w,wt)=>[w.id,wt])),Ld=[...Wt.filter(w=>!w.optional&&(!w.uad36Only||Xe)),...Wt.filter(w=>w.optional&&(!w.uad36Only||Xe)).sort((w,wt)=>{const Pt=Ka.indexOf(w.id),Ba=Ka.indexOf(wt.id);return Pt!==-1&&Ba!==-1?Pt-Ba:Pt!==Ba?Pt===-1?-1:1:(Gg.get(w.id)??0)-(Gg.get(wt.id)??0)})];for(const w of Ld){if($&&w.id==="quality")continue;const wt=xu(w.id).filter(Dr).filter(Dt=>{if(!us)return!0;const Da=Dt.rowId??Tu(Dt)??Dt.id;return Va&&tc(Da)||xs&&wi(Da)||ds&&Nc(Da,kb(Tu(Dt)))}),Pt=w.id==="overallQc"&&Xe&&!$&&["OverallQualityRatingCode","OverallConditionRatingCode"].some(Dt=>wi(Dt));if(w.optional&&!co(w)&&!Pt)continue;const Ba=w.id==="units"&&ts.length>0?w.fields.flatMap(Dt=>Dt==="basement"?[Dt,...ts]:[Dt]):w.fields;if(w.id==="siteInfo"){const Dt=new Map;for(const Ia of Yg)us&&!(xs&&wi(Ia.rowId))||Dt.set(Ia.rowId,{id:Ia.rowId,label:tS[Ia.rowId]??Ia.label?.trim()??Ia.rowId,source:"catalog",rowId:Ia.rowId,group:"Site",relevant:!0});for(const Ia of(mn.get("siteInfo")??[]).filter(nl).filter(Dr).filter(ar=>!us||xs&&wi(ar.rowId??Tu(ar)??ar.id)))Ia.rowId&&!Dt.has(Ia.rowId)&&Dt.set(Ia.rowId,Ia);const Da=Array.from(Dt.values()).sort((Ia,ar)=>(ym.get(Ia.rowId??"")??Number.MAX_SAFE_INTEGER)-(ym.get(ar.rowId??"")??Number.MAX_SAFE_INTEGER));vi.push(e.jsx(eK,{subject:t,comps:$a,subjectSiteInfo:Be,gridTemplateColumns:Hn,showMasterRateColumn:hr,effectiveShowAdjustments:Qr,getAdjustment:Pn,hasAdjustment:ca,onAdjustmentChange:wn,onSubjectSiteInfoChange:He,onComparableSiteInfoChange:Ie,canonicalRows:Da.map(Ia=>wa(Ia,{canonical:!0})),showMissingOnly:xs,isRequiredSiteRowMissing:Ia=>wi(Ia),isRequiredSiteRowMissingForProperty:(Ia,ar)=>yc(Ia,ar),sitePickerOpen:Yc&&to==="siteInfo",onSitePickerClose:()=>vn(!1),sitePicker:Xe&&!$&&!us?e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>{tl("siteInfo"),Ao("siteInfo"),vn(!0)},className:"shrink-0 whitespace-nowrap rounded px-1.5 py-0.5 text-[9px] font-semibold normal-case tracking-normal text-slate-200 hover:bg-slate-600 hover:text-white transition-colors","data-testid":"button-band-add-row-siteInfo",children:"+ Additional row"}),Yc&&to==="siteInfo"&&e.jsx("div",{ref:mr,className:"absolute left-0 top-full z-30 mt-1",children:kl})]}):null},"band-siteInfo"));continue}const Ts=Array.from(new Set(Ba)).filter(Dt=>ks(Dt,w.id)&&Nc(Dt,ui(Dt))),Ca=[...mn.get(w.id)??[]].filter(nl).filter(Ku).filter(Dr).filter(Dt=>!us||xs&&wi(Dt.rowId??Tu(Dt)??Dt.id)||ds&&Nc(Dt.id,kb(Tu(Dt))));if(w.id==="quality"&&Xe&&!us&&!A){const Dt=xt?.SubjectStructures?.value,Da=yj(Dt),Ia=Math.max(Sx(Da).length,1),ar=Math.max(vx(Da).length,1),Xs=Nx(Da).length,Fa=$a.reduce((dr,_r)=>{const Ni=Jb(_r.fields);return Math.max(dr,Sx(Ni).length)},0),is=$a.reduce((dr,_r)=>{const Ni=Jb(_r.fields);return Math.max(dr,vx(Ni).length)},0),Cr=$a.reduce((dr,_r)=>{const Ni=Jb(_r.fields);return Math.max(dr,Nx(Ni).length)},0),Io=Math.max(Ia,Fa),Qi=Math.max(ar,is),ic=Math.max(Xs,Cr);for(let dr=0;dr<Io;dr++){const _r=dr+1,Ni=dr===0?"exteriorQuality":`Dwelling${_r}
39_ExteriorQualityRatingCode`,P=dr===0?"exteriorCondition":`Dwelling${_r}_ExteriorConditionRatingCode`,X=`Structure ${_r}`;Io>1&&Ca.push({id:`wizard_qc_struct_hdr_d${_r}`,label:X,source:"catalog",rowId:`StructureIdentifier_d${_r}`,auto:!0}),Ca.push({id:`wizard_qc_ext_qual_hdr_d${_r}`,label:"Exterior Quality",source:"catalog",rowId:Ni,auto:!0}),Ca.push({id:`wizard_qc_ext_cond_hdr_d${_r}`,label:"Exterior Condition",source:"catalog",rowId:P,auto:!0})}for(let dr=0;dr<Qi;dr++){const _r=dr+1,Ni=dr===0?"interiorQuality":`Unit${_r}_InteriorQualityRatingCode`,P=dr===0?"interiorCondition":`Unit${_r}_InteriorConditionRatingCode`;Qi>1&&Ca.push({id:`wizard_qc_unit_hdr_u${_r}`,label:`Unit ${_r}`,source:"catalog",rowId:`UnitIdentifier_u${_r}`,auto:!0}),Ca.push({id:`wizard_qc_int_qual_hdr_u${_r}`,label:"Interior Quality",source:"catalog",rowId:Ni,auto:!0}),Ca.push({id:`wizard_qc_int_cond_hdr_u${_r}`,label:"Interior Condition",source:"catalog",rowId:P,auto:!0})}for(let dr=0;dr<ic;dr++){const _r=dr+1;Ca.push({id:`wizard_qc_adu_hdr_a${_r}`,label:`ADU ${_r}`,source:"catalog",rowId:`AduIdentifier_a${_r}`,auto:!0}),Ca.push({id:`wizard_qc_adu_qual_hdr_a${_r}`,label:"Interior Quality",source:"catalog",rowId:`Adu${_r}_InteriorQualityRatingCode`,auto:!0}),Ca.push({id:`wizard_qc_adu_cond_hdr_a${_r}`,label:"Interior Condition",source:"catalog",rowId:`Adu${_r}_InteriorConditionRatingCode`,auto:!0})}}if(w.id==="overallQc"&&Xe&&!$){const Dt=[{id:"wizard_qc_overall_qual",label:"Quality",source:"catalog",rowId:"OverallQualityRatingCode",auto:!0},{id:"wizard_qc_overall_cond",label:"Condition",source:"catalog",rowId:"OverallConditionRatingCode",auto:!0}];Ca.push(...Dt.filter(Da=>!us||xs&&wi(Da.rowId)))}if(us&&Ts.length===0&&Ca.length===0&&wt.length===0||$&&!us&&Ts.length===0&&Ca.length===0&&wt.length===0||(vi.push(e.jsxs("div",{className:Q("relative bg-slate-700 border-y border-slate-300",w.id==="energy"&&au==="section-header"&&"z-50",w.id==="project"&&fl&&"z-50",(w.id==="vehicle"||w.id==="project"||w.id==="energy"&&Ve)&&Xe&&Qr&&"grid"),style:(w.id==="vehicle"||w.id==="project"||w.id==="energy"&&Ve)&&Xe&&Qr?{gridTemplateColumns:Hn}:void 0,children:[e.jsxs("div",{className:Q("relative px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-white flex items-center gap-2 sticky left-0",(w.id==="vehicle"||w.id==="project"||w.id==="energy"&&Ve)&&Xe&&Qr?"w-auto min-w-0 gap-1.5 px-2 bg-slate-700":"w-max",Yc&&to===w.id||w.id==="project"&&fl||w.id==="energy"&&au==="section-header"||w.id==="amenities"&&Fr==="section-header"?"z-50":"z-[2]"),style:(w.id==="vehicle"||w.id==="project"||w.id==="energy"&&Ve)&&Xe&&Qr?{gridColumn:"1 / span 2"}:void 0,"data-testid":`band-header-${w.id}`,children:[!us&&e.jsx("button",{type:"button",onClick:()=>ot(Dt=>{const Da=new Set(Dt);return Da.has(w.id)?Da.delete(w.id):Da.add(w.id),Da}),className:"shrink-0 rounded p-0.5 text-slate-300 hover:bg-slate-600 hover:text-white transition-colors","data-testid":`button-band-collapse-${w.id}`,title:dt.has(w.id)?"Expand section":"Collapse section",children:dt.has(w.id)?e.jsx(fo,{className:"w-3.5 h-3.5"}):e.jsx(Rr,{className:"w-3.5 h-3.5"})}),e.jsx("span",{className:w.id==="vehicle"?"shrink-0 whitespace-nowrap text-[10px] tracking-wide":void 0,children:$&&w.id==="overallQc"?"Quality and Condition":w.title}),Xe&&!$&&!us&&w.id!=="siteInfo"&&w.id!=="overallQc"&&w.id!=="energy"&&w.id!=="amenities"&&e.jsxs("div",{className:w.id==="project"?"relative":"contents",children:[e.jsx("button",{type:"button",onClick:()=>{if(w.id==="project"){li(Dt=>Dt==="section-header"?null:"section-header");return}tl(w.id),Ao(w.id),vn(!0)},className:Q("shrink-0 whitespace-nowrap rounded py-0.5 font-semibold normal-case tracking-normal text-slate-200 hover:bg-slate-600 hover:text-white transition-colors",w.id==="vehicle"?"px-1 text-[8px]":"px-1.5 text-[9px]"),"data-testid":`button-band-add-row-${w.id}`,"data-vehicle-storage-picker-trigger":w.id==="vehicle"?!0:void 0,children:"+ Additional row"}),w.id==="project"&&Gi==="section-header"&&ih]}),Xe&&!$&&!us&&w.id==="energy"&&Ve&&e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>Tr(Dt=>Dt==="section-header"?null:"section-header"),className:"shrink-0 whitespace-nowrap rounded px-1.5 py-0.5 text-[9px] font-semibold normal-case tracking-normal text-slate-200 hover:bg-slate-600 hover:text-white","data-testid":"open-energy-row-picker",children:"+ Additional row"}
39),au==="section-header"&&e.jsx(IP,{entries:Yi,dimBackground:!0,onClose:()=>Tr(null),onApply:Dt=>{sm(Dt)}})]}),Xe&&A&&!$&&!us&&w.id==="amenities"&&e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>Zl(Dt=>Dt==="section-header"?null:"section-header"),className:"shrink-0 whitespace-nowrap rounded px-1.5 py-0.5 text-[9px] font-semibold normal-case tracking-normal text-slate-200 hover:bg-slate-600 hover:text-white","data-testid":"open-amenities-row-picker",children:"+ Additional row"}),Fr==="section-header"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"fixed inset-0 z-50 cursor-default bg-white/50","aria-label":"Close Property Amenities row selector","data-testid":"amenities-picker-grid-scrim",onMouseDown:()=>Zl(null)}),e.jsxs("div",{ref:qc,className:"absolute left-0 top-full z-[60] mt-1 w-80 rounded-md bg-white text-left text-xs font-normal normal-case tracking-normal shadow-lg ring-1 ring-slate-200","data-testid":"amenities-row-picker",children:[e.jsx("div",{className:"px-3 pb-1 pt-2",children:e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-wide text-slate-400",children:"Property Amenities"})}),e.jsx("div",{className:"max-h-72 overflow-y-auto py-1",children:cd.map(Dt=>{const Da=ba.includes(Dt);return e.jsxs("label",{className:"flex w-full cursor-pointer select-none items-center gap-2 px-3 py-1.5 text-xs text-slate-700 hover:bg-blue-50",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 shrink-0 cursor-pointer rounded border-slate-300 accent-blue-600",checked:Da,onChange:Ia=>{const ar=new Set(ba);Ia.target.checked?ar.add(Dt):ar.delete(Dt),bf(cd.filter(Xs=>ar.has(Xs)))}}),e.jsx("span",{className:"truncate font-medium",children:rg[Dt]})]},Dt)})})]})]})]}),!$&&Yc&&to===w.id&&w.id!=="vehicle"&&e.jsx("div",{ref:mr,className:"absolute left-2 top-full z-30 mt-1",children:kl}),!$&&w.id==="vehicle"&&e.jsx(sB,{open:Yc&&to==="vehicle",onOpenChange:Dt=>{vn(Dt),Dt||(Ao(null),tl(null))},existingRowIds:new Set,onAdd:()=>{},vehicleStorageMode:!0,vehicleStorageEntries:vt?am:oi.filter(Dt=>Dt.source==="custom"&&Dt.group==="Vehicle Storage").map(Dt=>({rowId:Dt.id,kind:"custom",customId:Dt.id,label:Dt.label,group:"Vehicle Storage",relevant:Dt.relevant!==!1})),onApplyVehicleStorage:Dt=>{if(vt&&We){yf(Dt);return}zc(Da=>[...Da.filter(Ia=>!(Ia.source==="custom"&&Ia.group==="Vehicle Storage")),...Dt.filter(Ia=>Ia.kind==="custom"&&Ia.group==="Vehicle Storage"&&typeof Ia.customId=="string").map(Ia=>({id:Ia.customId,label:Ia.label?.trim()||"Additional Row",source:"custom",group:"Vehicle Storage",relevant:Ia.relevant!==!1}))])},onDeleteVehicleStorage:Dt=>{if(vt&&We)return yf(am.filter(Da=>Da.customId!==Dt),Dt).then(()=>{});zc(Da=>Da.filter(Ia=>!(Ia.source==="custom"&&Ia.group==="Vehicle Storage"&&Ia.id===Dt)))}})]}),(w.id==="vehicle"||w.id==="project"||w.id==="energy"&&Ve)&&Xe&&Qr&&e.jsxs(e.Fragment,{children:[hr&&e.jsx("div",{className:"sticky z-[2] border-l border-slate-600 bg-slate-700",style:{left:"320px"},"aria-hidden":"true"}),$a.map((Dt,Da)=>e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:Q("bg-slate-700",Da===0?"border-l-2 border-l-slate-500":"border-l border-slate-600"),"aria-hidden":"true"}),e.jsx("div",{className:"flex items-center justify-center bg-slate-700","data-testid":w.id==="vehicle"?`vehicle-storage-section-adjustment-${Dt.id}`:w.id==="project"?`project-information-section-adjustment-${Dt.id}`:`energy-section-adjustment-${Dt.id}`,title:w.id==="vehicle"?"Vehicle Storage section adjustment (UAD 3.6, B-1 §22.13.04)":w.id==="project"?`Project Information section adjustment (UAD 3.6, B-1 §${kG})`:"Energy Efficient and Green Features section adjustment (UAD 3.6, B-1 §22.06.04)",children:e.jsx(Ph,{propertyId:Dt.id,fieldName:w.id==="vehicle"?"VehicleStorage":w.id==="project"?fx:"EnergyEfficientAndGreenFeatures",adjustment:Pn(Dt.id,w.id==="vehicle"?"VehicleStorage":w.id==="project"?fx:"EnergyEfficientAndGreenFeatures"),hasExplicitValue:ca(Dt.id,w.id==="vehicle"?"VehicleStorage":w.id==="project"?fx:"EnergyEfficientAndGreenFeatures"),onAdjustmentChange:wn,suggestion:null,salePrice:pn(Dt),isSacred:xr.current.has(`${Dt.id}:${w.id==="vehicle"?"VehicleStorage":w.id==="project"?fx:"EnergyEfficientAndGreenFeatures"}`),isPulsing:ec.has(`${Dt.id}:${w.id==="vehicle"?"VehicleStorage":w.id==="project"?fx:"EnergyEfficientAndGreenFeatures"}`),isJustFilled:rl.has(`${Dt.id}:${w.id==="vehicle"?"VehicleStorage":w.id==="project"?fx:"EnergyEfficientAndGreenFeatures"}
39`),onResetSacred:no,prereqsMet:F!==!1,compact:!0})})]},Dt.id))]})]},w.id==="siteInfo"?"band-siteInfo-canonical":`band-${w.id}`)),dt.has(w.id)&&!us))continue;const Ls=w.optional?s?.[w.id]:void 0;if(Ls&&!us&&vi.push(e.jsx("div",{className:"bg-emerald-50/60 border-b border-slate-200",children:e.jsx("div",{className:"w-max px-3 py-1 text-[10px] text-emerald-700 sticky left-0 z-[2]","data-testid":`band-detection-note-${w.id}`,children:$D(Ls)})},`band-${w.id}-detection-note`)),w.id==="energy"&&Xe&&!Ve&&!us&&Qr){const Dt=new Set(["RenewableEnergyComponentType","GreenCertificationName","EfficiencyRatingName"]);wt.some(Ia=>Ia.rowId&&Dt.has(Ia.rowId))&&vi.push(e.jsxs("div",{className:"grid border-b border-slate-200 bg-white transition-colors duration-100 hover:bg-blue-50/50",style:{gridTemplateColumns:Hn},"data-testid":"row-energy-section-adjustment",children:[e.jsx("div",{className:"px-3 py-[5px] flex items-center gap-1.5 w-[170px] min-w-[170px] bg-white sticky left-0 z-[2]",children:e.jsx("span",{className:"min-w-0 flex-1 text-[12px] font-medium text-slate-700 truncate",title:"Energy Efficient and Green Features — section-level adjustment (UAD 3.6, B-1 §22.06.04)",children:"Section Adjustment"})}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200 text-[10px] text-slate-300 flex items-center",children:e.jsx(kn,{state:"blank"})}),e.jsx("div",{className:"sticky z-[2] self-stretch border-l border-amber-200 bg-amber-100/60",style:{left:hr?"320px":"170px"}}),$a.map((Ia,ar)=>e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:Q("self-stretch bg-slate-100",ar===0?"border-l-2 border-l-slate-300":"border-l border-slate-200")}),e.jsx(Ph,{propertyId:Ia.id,fieldName:"EnergyEfficientAndGreenFeatures",adjustment:Pn(Ia.id,"EnergyEfficientAndGreenFeatures"),hasExplicitValue:ca(Ia.id,"EnergyEfficientAndGreenFeatures"),onAdjustmentChange:wn,suggestion:x?.[Ia.id]?.EnergyEfficientAndGreenFeatures||x?.[Ia.snapshotId]?.EnergyEfficientAndGreenFeatures||null,salePrice:pn(Ia),isSacred:xr.current.has(`${Ia.id}:EnergyEfficientAndGreenFeatures`),isPulsing:ec.has(`${Ia.id}:EnergyEfficientAndGreenFeatures`),isJustFilled:rl.has(`${Ia.id}:EnergyEfficientAndGreenFeatures`),onResetSacred:no,chipDerivations:Kc.current.get(`${Ia.id}:EnergyEfficientAndGreenFeatures`)??null,prereqsMet:F!==!1})]},Ia.id))]},"row-energy-section-adjustment"))}if(gl&&gl.bandId===w.id&&!us&&vi.push(e.jsx("div",{className:"bg-amber-50 border-b border-amber-200",children:e.jsxs("div",{className:"w-max flex items-start gap-2 px-3 py-1.5 text-[11px] text-amber-800 sticky left-0 z-[2]","data-testid":"notice-hidden-added-row",children:[e.jsx("span",{children:gl.text}),e.jsx("button",{type:"button",onClick:()=>Nn(null),className:"shrink-0 font-semibold text-amber-600 hover:text-amber-800","data-testid":"button-dismiss-hidden-row-notice",children:"Dismiss"})]})},`band-${w.id}-hidden-notice`)),w.id==="project"&&Xe&&!us){const Dt=rt??(nt?rt??{}:xt??{}),Da=JI(Dt),Ia=(Fa,is,Cr,Io)=>{const Qi=Cr?Dt:Fa.fields??{},ic=is==="ProjectName"?"ProjectName":is==="AssociationChargeAmount"?"AssociationDuesAmount":is==="ProjectCommonAmenityType"?"AmenityTypes":"SpecialAssessmentCharges",dr=is==="AssociationChargeAmount"?"AssociationChargeAmount":is==="ProjectCommonAmenityType"?"ProjectCommonAmenityType":is==="AssociationSpecialAssessmentStatusType"?"AssociationSpecialAssessmentStatusType":"ProjectName",_r=is==="AssociationChargeAmount"?"AssociationDuesAmount":is==="ProjectCommonAmenityType"?"AmenityTypes":is==="AssociationSpecialAssessmentStatusType"?"SpecialAssessmentCharges":"ProjectName",Ni=Qi[Cr?_r:ic],P=Ni&&typeof Ni=="object"&&typeof Ni.source=="string"?String(Ni.source):void 0,X=Ni&&typeof Ni=="object"&&Ni.userEdited===!0,xe=Cr?"projectInformation":"salesComparison",Ye=Cr?_r:Zi(Fa.id,`fields.${ic}`);if(zG(is,Qi,Io))return e.jsxs("div",{className:"flex min-h-[32px] items-center gap-1 px-2 text-[11px] text-slate-400 placeholder-hint","data-testid":`project-display-${Cr?"subject":Fa.id}-${is}`,children:[it&&e.jsx(Fs,{section:xe,fieldName:Ye,displayLabel:Cr?`Subject · ${_r}`:`${Fa.address} · ${ic}`}),e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("span",{className:"cursor-help",title:"This property is not in a project","aria-label":"This property is not in a project","data-testid":`project-not-in-project-${Cr?"subject":Fa.id}-${is}
39`,children:e.jsx(kn,{state:"em-dash"})})}),e.jsx(Wa,{side:"top",children:"This property is not in a project"})]})]});const ke=is==="ProjectName"?sp(Qi,"ProjectName"):is==="AssociationChargeAmount"?sp(Qi,"AssociationChargeAmount"):is==="ProjectCommonAmenityType"?sp(Qi,"ProjectCommonAmenityType"):sp(Qi,"AssociationSpecialAssessmentStatusType"),jt=Array.isArray(ke)?ke.map(Jt=>String(Jt)).filter(Boolean):ke==null||ke===""?[]:[String(ke)],Et=jt.join(" | "),ka=is==="ProjectName"&&!Cr?sp(Qi,"SameProjectAsSubjectIndicator"):void 0,Yt=is==="ProjectCommonAmenityType"||is==="AssociationSpecialAssessmentStatusType"?jt.map(Jt=>Hs(is==="ProjectCommonAmenityType"?"AmenityType":"AssociationSpecialAssessmentStatusType",Jt)):jt,ha=is==="ProjectName"?[Et,!Cr&&ka!==void 0&&ka!==null&&ka!==""?Bv(ka)?"Yes":"No":""].filter(Boolean).join(" | "):is==="AssociationChargeAmount"?Et?`$${Et}`:"":Yt.join(" | "),Rt=Jt=>r(Cr?"subject":Fa.id,dr,Jt,"User"),Bt=Jt=>{const gt=Jt.includes("None")?jt.includes("None")?Jt.filter(Ra=>Ra!=="None"):["None"]:Jt;Rt(gt.join("|"))};return e.jsxs(xn,{children:[e.jsx(bn,{asChild:!0,children:e.jsxs("div",{role:"button",tabIndex:0,"aria-label":`Edit ${is}`,"data-testid":`project-display-${Cr?"subject":Fa.id}-${is}`,className:"group relative flex min-h-[32px] cursor-pointer items-center justify-start rounded px-6 py-1 text-left text-[11px] leading-4 text-slate-700 transition-colors hover:bg-slate-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-blue-500",children:[P&&ha&&e.jsx("span",{className:"absolute left-1.5 top-1/2 -translate-y-1/2",children:e.jsx(Ji,{source:P,userEdited:X,testId:`source-dot-project-${Cr?"subject":Fa.id}-${is}`})}),it&&e.jsx(Fs,{section:xe,fieldName:Ye,displayLabel:Cr?`Subject · ${_r}`:`${Fa.address} · ${ic}`}),e.jsx("span",{className:Q("min-w-0 whitespace-normal",!ha&&"text-slate-300"),children:ha})]})}),e.jsxs(yn,{align:"center",sideOffset:4,collisionPadding:8,className:"z-50 w-72 border-slate-300 p-3 shadow-xl",children:[e.jsx("div",{className:"mb-2 text-[10px] font-semibold uppercase tracking-wide text-slate-500",children:is==="ProjectName"?"Project Name | Same Project as Subject":is==="AssociationChargeAmount"?"Monthly Fee":is==="ProjectCommonAmenityType"?"Common Amenities/Services":"Special Assessments"}),e.jsxs("div",{className:"flex items-center gap-1",children:[is==="AssociationChargeAmount"&&e.jsx("span",{className:"shrink-0 text-[11px] text-slate-500","aria-hidden":"true","data-testid":`project-currency-${Cr?"subject":Fa.id}-${is}`,children:"$"}),is==="ProjectCommonAmenityType"?e.jsx(qx,{label:"Common Amenities/Services",hideLabel:!0,values:jt,options:NU.map(Jt=>({value:Jt,label:Hs("AmenityType",Jt)})),maxLength:SE,maxEntries:vU,onChange:Bt,testId:`project-cell-${Cr?"subject":Fa.id}-${is}`,allowCustom:!0,compact:!0,ariaLabel:"Common Amenities/Services",className:"min-w-0 flex-1",controlClassName:"min-h-7 border-transparent px-1 py-0 hover:border-slate-200"}):is==="AssociationSpecialAssessmentStatusType"?e.jsx(qx,{label:"Special Assessments",hideLabel:!0,values:jt,options:AU.map(Jt=>({value:Jt,label:Hs("AssociationSpecialAssessmentStatusType",Jt)})),maxLength:SE,maxEntries:2,onChange:Bt,testId:`project-cell-${Cr?"subject":Fa.id}-${is}`,allowCustom:!1,compact:!0,ariaLabel:"Special Assessments",className:"min-w-0 flex-1",controlClassName:"min-h-7 border-transparent px-1 py-0 hover:border-slate-200"}):e.jsx("input",{className:"min-w-0 flex-1 rounded border border-transparent bg-transparent px-1 py-0.5 text-[11px] outline-none hover:border-slate-200 focus:border-blue-400 placeholder-hint",value:Et,placeholder:"Enter value","aria-label":is,"data-testid":`project-cell-${Cr?"subject":Fa.id}-${is}`,onChange:Jt=>Rt(Jt.target.value)}),is==="ProjectName"&&!Cr&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[11px] text-slate-700","aria-hidden":"true",children:"|"}),it&&e.jsx(Fs,{section:"salesComparison",fieldName:Zi(Fa.id,"fields.SameProjectAsSubjectIndicator"),displayLabel:`${Fa.address} · SameProjectAsSubjectIndicator`}),e.jsx(cy,{value:sp(Qi,"SameProjectAsSubjectIndicator")===void 0?void 0:!!Bv(sp(Qi,"SameProjectAsSubjectIndicator")),onChange:Jt=>{Jt!==null&&r(Fa.id,"SameProjectAsSubjectIndicator",Jt?"true":"false","User")},testId:`project-same-project-${Fa.id}`,allowClear:!1,className:"shrink-0"})]})]})]})]})},ar=lP(Dt,$a.map(Fa=>Fa.fields)),Xs=[{id:"ProjectName",label:"Project Name | Same Project as Subject"},{id:"AssociationChargeAmount",label:"Monthly Fee"},{id:"ProjectCommonAmenityType",label:"Common Amenities/Services"},{id:"AssociationSpecialAssessmentStatusType",label:"Special Assessments"}];
39for(const Fa of Xs){const is=Fa.id==="AssociationSpecialAssessmentStatusType"&&(gx(Dt)||$a.some(Io=>gx(Io.fields))),Cr=$a.some(Io=>mS(Io.fields)[Fa.id]===!0);BG(Fa.id,{propertyInProject:ar||Da,automaticSpecialAssessment:is,manuallyRelevant:Cr})&&vi.push(e.jsxs("div",{className:"grid min-h-[34px] border-b border-slate-200 bg-white",style:{gridTemplateColumns:Hn},"data-testid":`project-information-row-${Fa.id}`,children:[e.jsx("div",{className:"sticky left-0 z-[2] flex min-h-[34px] items-center bg-white px-3 text-[11px] font-medium text-slate-700",children:Fa.label}),hr&&e.jsx("div",{className:"flex items-center border-r border-slate-200 px-2 text-[10px] text-slate-300",children:e.jsx(kn,{state:"blank"})}),e.jsx("div",{className:"sticky z-[2] border-r border-slate-200 bg-white",style:{left:hr?"320px":"170px"},children:Ia(t,Fa.id,!0,Cr)}),$a.map((Io,Qi)=>e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:Q("col-span-2 border-r border-slate-200 bg-white",Qi===0&&"border-l-2 border-l-slate-300"),style:{gridColumn:"span 2"},children:Ia(Io,Fa.id,!1,Cr)}),Qr&&Fa.id==="ProjectName"&&Qi===0&&null]},Io.id))]},`project-row-${Fa.id}`))}}const Qs=w.id==="units"&&Xe,Lt=Xe&&!us;if(Qs){const Dt=Ca.filter(Xs=>ag.includes(Xs.rowId??"")),Da=Dt.filter(Xs=>Xs.rowId==="BedroomCount"),Ia=Dt.filter(Xs=>Xs.rowId==="FullBathroomCount"||Xs.rowId==="HalfBathroomCount"),ar=Ca.filter(Xs=>!Dt.includes(Xs));for(const Xs of Da)vi.push(wa(Xs));if(Lt&&Ia.length>=2)if(ou.has(dv.id)){vi.push(Ke(dv));for(const Xs of Ia)vi.push(wa(Xs))}else vi.push(ft(Ia));else for(const Xs of Ia)vi.push(wa(Xs));for(const Xs of ar)vi.push(wa(Xs))}const La=w.id==="generalInfo"?{listPrice:["ContractPrice"],saleType:["NoFinancingTransactionIndicator","MortgageType","TotalSalesConcessionAmount","SalesContractDate","ContractDateUnknownIndicator"],attachedDetached:["SaleToListPriceRatioPercent","PropertyEstateType","SameBuilderAsSubjectIndicator"]}:{listingStatus:["ContractPrice"],concessions:["SalesContractDate"]},lr=w.id==="generalInfo"?{listPrice:["ContractPrice"],attachedDetached:["SaleToListPriceRatioPercent"]}:{},Ys=new Set,Ms=new Set,Zr=new Set,cn=Dt=>{const Da=Dt.rowId??Dt.id;return Zr.has(Da)?null:(Zr.add(Da),wa(Dt,{canonical:Ox.has(Dt.rowId??"")}))},Jr=new Set;for(const Dt of Ts){if(Jr.has(Dt)||nt&&(Dt==="listingStatus"||Dt==="daysOnMarket")||(nt&&Dt==="listPrice"&&(Jr.add("listPrice"),Jr.add("listingStatus"),Jr.add("daysOnMarket")),Qs&&ag.includes(Dt)))continue;const Da=Lt?O3[Dt]:void 0;if(Da){const Ia=Da.fields.filter(ar=>Ts.includes(ar));if(Ia.length>=2){for(const ar of Ia)Jr.add(ar);if(ou.has(Da.id)){vi.push(Ke(Da));for(const ar of Ia)vi.push(ui(ar)?he(ar):mt(ar))}else vi.push(Ae(Da,Ia));continue}}if(vi.push(ui(Dt)?he(Dt):mt(Dt)),(w.id==="general"||w.id==="generalInfo")&&Xe&&!Qs){const Ia=La[Dt]??[];for(const Xs of Ia){const Fa=Ca.find(is=>is.rowId===Xs&&!Ys.has(Xs));Fa&&nl(Fa)&&(vi.push(cn(Fa)),Ys.add(Xs))}const ar=w.id==="generalInfo"?lr[Dt]??[]:[];for(const Xs of ar)for(const Fa of wt)Fa.rowId===Xs&&!Ms.has(Fa.id)&&(vi.push(wa(Fa)),Ms.add(Fa.id))}}if(!Qs)for(const Dt of Ca)Ys.has(Dt.rowId??"")||vi.push(cn(Dt));for(const Dt of wt)Qs&&Dt.rowId&&ag.includes(Dt.rowId)||Ms.has(Dt.id)||vi.push(wa(Dt));let Wn=!1;if(!A&&w.id==="outbuilding"&&Xe&&!us){Wn=!0;const Dt=oi.map(Ia=>Ia.rowId??"").filter(Boolean),Da=dU(Dt);vi.push(e.jsx("div",{className:"grid",style:{gridTemplateColumns:Hn},children:e.jsxs("div",{style:{gridColumn:"1 / -1"},className:"px-4 py-1.5 bg-white border-b border-slate-200/60 flex flex-wrap items-center gap-2",children:[e.jsx("button",{type:"button",className:"h-7 rounded-md border border-slate-200 bg-white px-2 text-[11px] text-slate-500 hover:border-slate-300",onClick:()=>{const Ia=uU(Dt),ar=SL(Ia);zc(Xs=>[...Xs,{id:`catalog_${ar}_${Date.now()}`,label:`Outbuilding ${Ia} — Type`,source:"catalog",rowId:ar}])},"data-testid":"button-add-outbuilding",children:"+ Add outbuilding…"}),Da.map(Ia=>{const ar=pU.filter(Xs=>!oi.some(Fa=>Fa.rowId===fE(Ia,Xs.key)));return ar.length===0?null:e.jsxs("select",{className:"h-7 rounded-md border border-slate-200 bg-white px-2 text-[11px] text-slate-500 hover:border-slate-300",value:"",onChange:Xs=>{const Fa=Xs.target.value;if(!Fa)return;const is=mU(Fa);if(!is)return;const Cr=fE(Ia,Fa);zc(Io=>[...Io,{id:`catalog_${Cr}_${Date.now()}`,label:is.label,source:"catalog",rowId:Cr}])},"aria-label":`Add outbuilding ${Ia} detail`,"data-testid":`select-add-outbuilding-detail-${Ia}`,children:[e.jsxs("option",{value:"",children:["+ Outbuilding ",Ia," detail…"]}),ar.map(Xs=>e.jsx("option",{value:Xs.key,children:Xs.label},Xs.key))]},Ia)})]})},"band-outbuilding-add"))}
39w.optional&&w.id!=="project"&&Ts.length===0&&Ca.length===0&&wt.length===0&&!Wn&&!us&&vi.push(e.jsx("div",{className:"grid",style:{gridTemplateColumns:Hn},children:e.jsx("div",{style:{gridColumn:"1 / -1"},className:"px-4 py-2 text-[11px] text-slate-400 bg-white border-b border-slate-200/60",children:w.id==="water"?e.jsxs("span",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{children:"Water Frontage rows appear once a column’s Site Influence (Location) includes “Body of Water”."}),e.jsx("button",{type:"button",className:"text-blue-600 underline underline-offset-2 hover:text-blue-800 font-medium","data-testid":"button-water-hint-set-site-influence",onClick:()=>{const Dt=document.querySelector('[data-testid="cell-subject-location"]');Dt&&(Dt.scrollIntoView({behavior:"smooth",block:"center"}),Dt.click())},children:"Set the subject’s Site Influence"})]}):"Use the “+ Additional row” to add features"})},`band-empty-${w.id}`))}return e.jsxs(e.Fragment,{children:[vi,oi.filter(w=>If(w)===void 0).filter(w=>!wd(w)).filter(w=>!vc(w)).filter(w=>!nc(w)).filter(nl).filter(Dr).map(wa),$&&!us&&V&&e.jsx(I7,{factors:z,compIds:$a.map(w=>{const wt=w.fields.mlsNumber?.value;return wt==null||String(wt).trim()===""?w.id:String(wt)}),gridTemplateColumns:Hn,showMasterRateColumn:hr,showAdjustments:Qr,onChange:V}),bm]})})(),h!=="str"&&YH().filter(J=>!(nt&&J==="grossAdjustment")).map((J,he)=>e.jsxs("div",{className:Q("grid border-b border-slate-200/60 bg-slate-100/80 transition-colors duration-100 hover:bg-blue-100/40",he===0&&"border-t-2 border-t-slate-300"),style:{gridTemplateColumns:Hn},children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-center gap-1.5 w-[170px] min-w-[170px] bg-slate-800 sticky left-0 z-[2]",children:[e.jsx("span",{className:"text-[12px] font-semibold text-white whitespace-nowrap",children:Ah(J,h,nt)}),it&&!nt&&e.jsx(Fs,{section:"salesGrid",fieldName:J}),J==="netAdjustment"&&e.jsx("span",{className:"text-rose-300",title:"Required by UAD",children:"*"})]}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200"}),e.jsx("div",{className:"sticky z-[2] bg-slate-100",style:{left:hr?"320px":"170px"},children:e.jsx(jh,{property:t,fieldName:J,onUpdate:(Ae,Ke)=>
39r(t.id,J,Ae,Ke),onFieldUpdate:r,onSetPreference:oo,preferredSource:Zo(J),gridMode:h,activeScenario:f,siteDisplayUnits:J==="site"?bo:void 0,highlightConflicts:Va,uad36:nt})}),$a.map((Ae,Ke)=>e.jsxs(Mn.Fragment,{children:[e.jsx(jh,{property:Ae,fieldName:J,isFirstComp:Ke===0,comparableSequence:Ke+1,onUpdate:(ft,mt)=>r(Ae.id,J,ft,mt),onFieldUpdate:r,onCopyToAllComps:(ft,mt)=>_i(J,ft,mt),onCopyCompanionToAllComps:Af,onSetPreference:oo,preferredSource:Zo(J),gridMode:h,siteDisplayUnits:J==="site"?bo:void 0,highlightConflicts:Va,uad36:nt}),Qr&&e.jsx("div",{className:"px-1.5 py-[5px] w-[60px] min-w-[60px]"})]},Ae.id))]},J)),nt&&h!=="str"&&(()=>{const J=mt=>Xe=>{const _t=oa=>mt.fields?.[oa]?.value;switch(Xe){case"SalePrice":return _t("salePrice");case"FinalListPriceAmount":return _t("listPrice");case"ListingStatusType":return _t("listingStatus");case"BedroomCount":return Rj(_t("aboveGrade")).bedrooms;case"TotalFinishedAreaOfAllLivingUnitsIncludingADUAreaMeasure":case"UnitStandardAboveGradeFinishedAreaMeasure":return _t("gla");default:return}},he=mt=>{const Xe=mt.fields?.netAdjustment?.value,_t=typeof Xe=="number"?Xe:parseFloat(String(Xe??"").replace(/[^0-9.-]/g,""));return Number.isFinite(_t)?_t:0},Ae=JP(J(t),he(t)),Ke=$a.map(mt=>JP(J(mt),he(mt)));return dW.filter(mt=>pW(mt,Ae,Ke)).map(mt=>e.jsxs("div",{className:"grid border-b border-slate-200/60 bg-slate-100/80",style:{gridTemplateColumns:Hn},"data-testid":`row-b1-summary-${mt.id}`,children:[e.jsx("div",{className:"px-3 py-[5px] flex items-center gap-1.5 w-[170px] min-w-[170px] bg-slate-800 sticky left-0 z-[2]",children:e.jsx("span",{className:"text-[12px] font-semibold text-white whitespace-nowrap",children:mt.label})}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200"}),(()=>{const Xe=XP(mt,Ae);return e.jsx("div",{className:"sticky z-[2] bg-slate-100 px-3 py-[5px] flex items-center text-[12px] text-slate-500",style:{left:hr?"320px":"170px"},"data-testid":`cell-b1-summary-${mt.id}-subject`,children:Xe.kind==="value"?e1(Xe.amount,ng):Xe.kind==="em-dash"?e.jsx(kn,{state:"em-dash"}):""})})(),$a.map((Xe,_t)=>{const oa=XP(mt,Ke[_t]);return e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:Q("px-3 py-[5px] flex items-center text-[12px]",_t===0?"border-l-2 border-l-slate-300":"border-l border-slate-200",oa.kind==="em-dash"?"text-slate-400":"text-slate-900"),"data-testid":`cell-b1-summary-${mt.id}-comp${_t+1}`,children:oa.kind==="value"?e1(oa.amount,ng):oa.kind==="em-dash"?e.jsx(kn,{state:"em-dash"}):""}),Qr&&e.jsx("div",{className:"px-1.5 py-[5px] w-[60px] min-w-[60px]"})]},Xe.id)})]},`b1-summary-${mt.id}`))})(),h!=="str"&&e.jsxs("div",{className:"grid border-b border-slate-200/60 bg-slate-100/80",style:{gridTemplateColumns:Hn},children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-center gap-1.5 w-[170px] min-w-[170px] bg-slate-700 sticky left-0 z-[2]",children:[e.jsx("span",{className:"text-[12px] font-semibold text-white whitespace-nowrap",children:"Comparable Weight"}),it&&!nt&&e.jsx(Fs,{section:"salesGrid",fieldName:"weights[]"}),e.jsx(Xx,{className:"w-3 h-3 text-slate-300"})]}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200"}),e.jsx("div",{className:"px-3 py-[5px] flex items-center text-[12px] text-slate-400 sticky z-[2] bg-slate-100",style:{left:hr?"320px":"170px"},children:e.jsx(kn,{state:"gray"})}),$a.map(J=>{const he=Zf(Jo[J.id]);return e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:"px-3 py-[5px] flex items-center gap-1",children:e7.map(Ae=>{const Ke=he===Ae,ft=Ke?Ae==="Most"?"bg-blue-100 text-blue-700 ring-blue-300":Ae==="Less"?"bg-amber-100 text-amber-700 ring-amber-300":"bg-rose-100 text-rose-700 line-through ring-rose-300":"bg-white text-slate-500 ring-slate-200 hover:ring-slate-300";return e.jsx("button",{type:"button",onClick:()=>Ll(mt=>({...mt,[J.id]:t7(Zf(mt[J.id]),Ae)})),"aria-pressed":Ke,title:Ke?"Click again to clear back to Auto (UAD 3.6 ComparableWeightType). Feeds the Value Range bar below.":`Set this comparable to ${VT[Ae]} (UAD 3.6 ComparableWeightType). Feeds the Value Range bar below.`,className:Q("rounded px-1.5 py-0.5 text-[11px] font-semibold ring-1 transition-colors whitespace-nowrap",ft),"data-testid":`weight-${J.id}-${Ae.toLowerCase()}`,children:VT[Ae]},Ae)})}),Qr&&e.jsx("div",{className:"px-1.5 py-[5px] w-[60px] min-w-[60px]"})]},J.id)})]}),h!=="str"&&(!xs||$a.some(he=>{const Ae=he.fields;for(let Ke=0;Ke<=Vm;
39Ke++){const ft=Ae[`saleHistory${Ke}_OwnershipTransferDate`]?.value,mt=Ae[`saleHistory${Ke}_OwnershipTransferTransactionType`]?.value,Xe=Ae[`saleHistory${Ke}_SaleType`]?.value;if(ft&&String(ft).trim()!==""&&mt==="Sale"&&(!Xe||String(Xe).trim()===""))return!0}return!1}))?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-2 bg-white border-b border-slate-100"}),e.jsx("div",{className:"grid border-b border-slate-200/60",style:{gridTemplateColumns:Hn},children:e.jsx("div",{className:"relative bg-slate-700 px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-white border-y border-slate-300 flex items-center gap-2",style:{gridColumn:"1 / -1"},"data-testid":"band-header-salehistory",children:e.jsx("span",{children:"Sale History"})})}),e.jsxs("div",{className:"grid border-b border-slate-200/60",style:{gridTemplateColumns:Hn},children:[e.jsxs("div",{className:"px-3 py-[5px] flex items-start w-[170px] min-w-[170px]",children:[e.jsx("span",{className:"text-[12px] font-medium text-slate-700 whitespace-nowrap",children:"Sale History"}),it&&!nt&&e.jsx(Fs,{section:"salesGrid",fieldName:"saleHistory[]"})]}),hr&&e.jsx("div",{className:"px-2 py-[5px] border-r border-slate-200"}),e.jsx("div",{className:"px-3 py-[5px] text-[11px] text-slate-400 italic","data-testid":"cell-subject-salehistory",children:"Subject 3-yr history — managed in the report panel (Prior Sale / Transfer History)"}),$a.map((he,Ae)=>{const Ke=Ae+1,ft=`Comp${Ke}`,mt={SalePrice:"salePrice",SaleDate:"dateOfSale",SaleType:"saleType",PriorSalesOrTransfersIndicator:"priorSalesOrTransfersIndicator"},Xe=_t=>{const oa=_t.startsWith(ft)?_t.slice(ft.length):_t;if(oa==="SaleHistoryDataSource")return"saleHistoryDataSource";const ls=oa.match(/^SaleHistory(\d+)_([A-Za-z0-9]+)$/);return ls?`saleHistory${ls[1]}_${ls[2]}`:mt[oa]??null};return e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:"px-2 py-[5px]","data-testid":`cell-salehistory-comp${Ke}`,children:e.jsx(y7,{compNumber:Ke,getValue:Z?_t=>Z(_t):_t=>{const oa=Xe(_t);if(oa)return he.fields?.[oa]?.value},getSource:pe?_t=>pe(_t):_t=>{const oa=Xe(_t);if(oa)return he.fields?.[oa]?.source},setValue:se?(_t,oa)=>se(_t,oa):(_t,oa)=>{const ls=Xe(_t);ls&&r(he.id,ls,oa??"","user")},setValueWithSource:se?void 0:(_t,oa,ls)=>{const Ps=Xe(_t);Ps&&r(he.id,Ps,oa??"",ls??"user")}})}),Qr&&e.jsx("div",{className:"px-1.5 py-[5px] w-[60px] min-w-[60px]"})]},he.id)})]})]}):null,h==="str"&&e.jsxs("div",{className:"grid border-t-2 border-slate-300 bg-slate-50",style:{gridTemplateColumns:Hn},children:[e.jsx("div",{className:"px-3 py-3 flex items-center",children:e.jsx("span",{className:"text-xs font-semibold text-slate-700 uppercase tracking-wide",children:"STR Comparability"})}),e.jsx("div",{className:"px-3 py-3 border-l border-slate-200 bg-amber-50/50"}),$a.map(J=>e.jsx("div",{className:"px-2 py-2 border-l border-slate-200 flex items-center justify-center",children:e.jsx("div",{className:"flex gap-1",children:["Superior","Similar","Inferior"].map(he=>{const Ae=$u[J.id]===he,Ke={Superior:Ae?"bg-green-100 border-green-500 text-green-700":"bg-white border-slate-200 text-slate-500 hover:border-green-300",Similar:Ae?"bg-blue-100 border-blue-500 text-blue-700":"bg-white border-slate-200 text-slate-500 hover:border-blue-300",Inferior:Ae?"bg-orange-100 border-orange-500 text-orange-700":"bg-white border-slate-200 text-slate-500 hover:border-orange-300"};return e.jsx("button",{onClick:()=>Wu(J.id,Ae?null:he),className:Q("px-3 py-1.5 text-[10px] font-medium border rounded transition-colors",Ke[he]),"data-testid":`comparability-${J.id}-${he.toLowerCase()}`,children:he},he)})})},J.id))]}),h!=="str"&&$a.length>0&&(()=>{const J=vr=>{const tn=vr.fields.salePrice?.value;return tn==null?null:typeof tn=="number"?tn:parseFloat(String(tn).replace(/[^0-9.-]/g,""))},he=vr=>{const tn=vr.fields.adjustedSalePrice?.value;return tn==null?null:typeof tn=="number"?tn:parseFloat(String(tn).replace(/[^0-9.-]/g,""))},Ae=$a.map(J).filter(vr=>vr!=null&&!isNaN(vr)),Ke=$a.map(he).filter(vr=>vr!=null&&!isNaN(vr)&&vr>0);if(Ae.length<2)return null;const ft=$a.map(vr=>{const tn=he(vr),An=tn!=null&&!isNaN(tn)&&tn>0?tn:J(vr);return An==null||isNaN(An)?null:{value:An,weight:Zf(Jo[vr.id])}}).filter(vr=>vr!=null),mt=Math.min(...Ae),Xe=Math.max(...Ae),_t=Ke.length>=2,oa=_t?Math.min(...Ke):mt,ls=_t?Math.max(...Ke):Xe,Ps=ls-oa,Er=oa>0?Math.round(Ps/oa*100):0,mn=vr=>
39`$${Math.round(vr).toLocaleString()}`;return e.jsx(H7,{unadjMin:mt,unadjMax:Xe,unadjPrices:Ae,adjMin:oa,adjMax:ls,adjPrices:Ke,hasAdj:_t,adjSpread:Ps,adjPct:Er,automaticValue:eo?yo:void 0,indicatedValue:$c,setIndicatedValue:Kr,opinionOfMarketValue:_u,setOpinionOfMarketValue:xf,marketValueCondition:No,toggleMarketValueCondition:Pg,effectiveDate:xp,setEffectiveDate:wg,fmtCur:mn,weightedDots:ft,weightedSuggested:Wc,valueMode:Bc,onUseAutomatic:eo?cu:void 0,onUseSuggested:eo?void 0:cu,inspectSection:eo?"reconciliation":"salesGrid",inspectFieldName:eo?"SalesComparisonValue":"indicatedValue"})})(),h!=="str"&&j&&e.jsx(t8,{orderId:j,availableSlots:Math.max(0,24-jo.length-ea-ir-$e)}),A&&j&&h!=="str"&&e.jsx("div",{className:"mx-4 max-w-6xl",children:e.jsx(hU,{orderId:j,sectionId:"salesComparison",commentFieldName:"SalesComparisonCommentDescription",commentLabel:"Reconciliation of Sales Comparison Approach",commentRequired:!0,title:"Sales Comparison Commentary & Exhibits",commentPlaceholder:"Additional details and analysis to support conclusions, including how Comparable Weight was determined.",hidePhotos:!0,prefixContent:({getFieldValue:J,updateField:he})=>{const Ke=String(J("saleHistoryAnalysis","ValuationCommentText")??""),ft=!Ke.trim();return e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-3",children:e.jsxs(ko,{className:"text-sm",children:["Analysis of Prior Sale and Transfer History of Comparable Sales",it&&e.jsx(Fs,{section:"saleHistoryAnalysis",fieldName:"ValuationCommentText"}),e.jsx("span",{className:"text-red-500 ml-0.5",children:"*"})]})}),e.jsxs(Ta,{children:[e.jsx(yi,{value:Ke,onChange:mt=>he("saleHistoryAnalysis","ValuationCommentText",mt.target.value),placeholder:"Analyze and discuss the prior sale and transfer history for each comparable, noting any relevant patterns, significant price changes, or other concerns...",rows:3,className:ft?"placeholder-hint border-red-400 bg-red-50/40 focus-visible:ring-red-400":"placeholder-hint","data-field-name":"ValuationCommentText","data-testid":"textarea-section-comments-saleHistoryAnalysis"}),e.jsx("div",{className:"flex justify-end mt-1",children:e.jsxs("span",{className:`text-xs ${Ke.length>5e3?"text-destructive font-medium":"text-muted-foreground"}`,children:[Ke.length," / ",5e3]})})]})]})},extraContent:({getFieldValue:J,updateField:he})=>{const Ae=J("salesComparisonGrid","exhibitPhotos"),Ke=Array.isArray(Ae)?Ae:[];return e.jsx(mD,{items:Ke,onChange:ft=>he("salesComparisonGrid","exhibitPhotos",ft),otherReportImageCount:RL(J)-EL(Ke),mapCaption:"Map of Sales Comparables",mapImageType:"SalesComparableMap",mapRequired:!0,idPrefix:"sales-exhibits",testIdBase:"sales-exhibits"})}})})]})})}),ni&&e.jsx(LW,{isOpen:!!ni,onClose:()=>ki(null),photos:ni.photos,address:ni.address,compSnapshotId:ni.compSnapshotId,orderId:ni.orderId,isSubject:ni.isSubject,coverPhotoUrl:ni.coverPhotoUrl,onCoverChange:J=>{const he=ni.isSubject?t.id:$a.find(Ae=>Ae.snapshotId===ni.compSnapshotId)?.id||"";he&&Ol(Ae=>({...Ae,[he]:J})),ki(Ae=>Ae?{...Ae,coverPhotoUrl:J}:null)},onPhotosChange:ni.compSnapshotId?J=>{const he=ni.compSnapshotId;Cg(Ae=>({...Ae,[he]:[...Ae[he]||[],J]}))}:void 0}),Xn&&e.jsx(xi,{open:!!Xn,onOpenChange:J=>{if(!J){const he=Xn.fromChipCascade;Bu(null),he||Vo.current?.()}},children:e.jsxs(bi,{className:"max-w-lg","data-testid":"dialog-overwrite-confirm",children:[e.jsx($i,{children:e.jsxs(si,{className:"flex items-center gap-2",children:[e.jsx(Ns,{className:"w-5 h-5 text-amber-500"}),"Overwrite manual adjustments?"]})}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("p",{children:["This apply will overwrite"," ",e.jsx("strong",{children:Xn.conflicts.length})," ","manually-edited cell",Xn.conflicts.length===1?"":"s",". The new (multi-method) values will replace the existing manual entries."]}),e.jsxs("ul",{className:"max-h-48 overflow-y-auto rounded border border-slate-200 p-2 text-xs space-y-1",children:[Xn.conflicts.slice(0,12).map((J,he)=>e.jsxs("li",{className:"font-mono",children:[J.field,": ",J.existing.toLocaleString()," →"," ",J.incoming.toLocaleString()]},`${J.effectiveId}-${J.field}-${he}`)),Xn.conflicts.length>12&&e.jsxs("li",{className:"text-slate-500",children:["…and ",Xn.conflicts.length-12," more."]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(De,{variant:"outline",onClick:()=>{const J=Xn.fromChipCascade;Bu(null),J||Vo.current?.()},"data-testid":"button-overwrite-cancel",children:"Cancel"}),e.jsxs(De,{variant:"destructive",onClick:()=>{Ea(Xn.resolved,Xn.forceOverwriteFields);const J=Xn.fromChipCascade;Bu(null),J||Vo.current?.()},"data-testid":"button-overwrite-confirm",children:["Overwrite ",Xn.conflicts.length," cell",Xn.conflicts.length===1?"":"s"]})]})]})}),gf&&e.jsx(xi,{open:gf,onOpenChange:Gn,children:e.jsxs(bi,{className:"max-w-lg",children:[e.jsx($i,{children:e.jsxs(si,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"w-5 h-5 text-blue-500"}),"How to Use This Grid"]})}),e.jsxs("div",{className:"space-y-4 text-sm text-slate-600",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-800 mb-1",children:"Purpose"}),e.jsx("p",{children:"This grid is used to compare short-term rental performance across similar properties to support a stabilized income analysis. It is not a traditional adjustment grid."})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-800 mb-1",children:"Missing Data Is Normal"}),e.jsx("p",{children:"“Unknown” values are expected. Short-term rental platforms do not consistently publish all physical or qualitative property details. Missing data does not invalidate the analysis. Focus on reliable performance metrics such as ADR, occupancy, distance, and market relevance."})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-800 mb-1",children:"Comparability Ratings"}),e.jsx("p",{children:"Use the Superior / Similar / Inferior selector to rate each comparable’s overall STR comparability to the subject. Not every individual difference requires a rating. Apply professional judgment."})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-800 mb-1",children:"Key Metrics"}),e.jsxs("ul",{className:"list-disc list-inside space-y-1 ml-2",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Nightly Rate (ADR):"})," Average daily rental rate supported by market data"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Occupancy Rate:"})," Percentage of nights rented annually"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Gross Monthly Income:"})," (ADR × Annual Nights Occupied) ÷ 12"]})]})]})]})]})})]})})}function tK(t,a){if(a.uad36&&t==="proximity")return"";if(a.uad36&&Qp.has(t)){if(!a.isSubject)return t==="listPrice"?"$":"";const s=NN(a.subjectListedWithinPreviousYear);return s==="dash"||s==="blank"?"":t==="listPrice"?"$":""}return a.uad36?"":a.gridMode==="str"?"Unknown":"–"}function aK(t,a){return!a.b1GatingActive||a.isEvalPricePerSf||Qp.has(t)}function rI({value:t,onChange:a,ariaLabel:s,testId:r,includeSettledSale:n=!0,blendWithCellSurface:i=!1}){return e.jsxs("div",{className:"group/listing-status relative w-full",children:[e.jsxs("select",{"aria-label":s,value:t,onChange:l=>a(l.target.value),className:Q("placeholder-hint h-7 w-full min-w-0 appearance-none rounded border border-transparent px-2 pr-7 text-[11px] outline-none transition-colors hover:border-slate-200 focus:border-sky-400 focus:ring-1 focus:ring-sky-200",i?"bg-transparent":"bg-white",t?"text-slate-900":"text-slate-400"),"data-testid":r,children:[e.jsx("option",{value:"",children:"Select..."}),ZW.filter(l=>n||l.value!=="SettledSale").map(l=>e.jsx("option",{value:l.value,children:l.label},l.value))]}),e.jsx(Rr,{"aria-hidden":"true",className:"pointer-events-none absolute right-2 top-1/2 h-3 w-3 -translate-y-1/2 text-slate-400 opacity-0 transition-opacity group-hover/listing-status:opacity-100 group-focus-within/listing-status:opacity-100"})]})}function sK({value:t,otherDescription:a,meta:s,isSubject:r,isFirstComp:n,onValueChange:i,onOtherDescriptionChange:l,inspectSection:c,inspectField:d,inspectLabel:p,inspecting:u,testId:m,emDash:h=!1,resolvedDisplay:f=!1}){const v=Q("flex items-center justify-start gap-2 px-2 py-[5px] text-left",r?"border-l border-slate-200":n?"border-l-2 border-l-slate-300":"border-l border-slate-200");if(h)return e.jsx("div",{className:v,"aria-label":"Not applicable for a Cooperative property","data-testid":`${m}
39-em-dash`,children:e.jsx(kn,{state:"em-dash"})});const S=vE(t),N=S.type==="Other"?a||S.other||"Other":S.type==="FeeSimple"?"Fee Simple":S.type==="Leasehold"?"Leasehold":"",x=y=>{const b=vE(y);b.type?b.type==="FeeSimple"?(i("FeeSimple"),l(null)):b.type==="Leasehold"?(i("Leasehold"),l(null)):(i("Other"),l(b.other??null)):(i(null),l(null))};return e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:v,children:[s?.source&&e.jsx(Ji,{source:s.source,userEdited:s.userEdited,testId:`${m}-source`}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(Kd,{value:N,onChange:x,suggestions:CU,compact:!0,placeholder:"Select or type…",maxLength:33,ariaLabel:p,inputClassName:"placeholder-hint h-[18px] w-full px-1 py-0 text-[11px] md:text-[11px] leading-4 border border-transparent hover:border-slate-200 focus:border-slate-300 rounded bg-transparent focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-300",testId:m,resolvedDisplay:f})}),u&&e.jsx(Fs,{section:c,fieldName:d,displayLabel:p})]})})}function dC(t){if(t==null)return"";const a=String(t).trim();return a===""||jW.test(a)?"":a}function Xb(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){const a=Number(t.replace(/[$,%\s,]/g,""));return Number.isFinite(a)?a:null}return null}function aN(t){if(typeof t!="string")return null;const a=/^(\d{4})-(\d{2})$/.exec(t.trim());if(!a)return null;const s=Number(a[2]);return s>=1&&s<=12?`${a[1]}-${a[2]}`:null}function rte(t){if(!Array.isArray(t))return[];const a=new Map;for(const s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;const r=s,n=aN(r.period??r.month);if(!n)continue;const i=Xb(r.saleToListRatio??r.avgSoldToListRatio),l=i===null||i<=0?null:i>2?i<=200?i/100:null:i,c={period:n,medianPrice:Xb(r.medianPrice??r.medianSalePrice),dom:Xb(r.dom??r.avgDOM??r.medianDOM),saleToListRatio:l,rentalRate:Xb(r.rentalRate),rentalInventory:Xb(r.rentalInventory)},d=a.get(n);if(!d){a.set(n,c);continue}a.set(n,{period:n,medianPrice:c.medianPrice??d.medianPrice,dom:c.dom??d.dom,saleToListRatio:c.saleToListRatio??d.saleToListRatio,rentalRate:c.rentalRate??d.rentalRate,rentalInventory:c.rentalInventory??d.rentalInventory})}return Array.from(a.values()).sort((s,r)=>s.period.localeCompare(r.period))}function rK(t){const a=[...t].sort((r,n)=>r-n),s=Math.floor(a.length/2);return a.length%2===0?(a[s-1]+a[s])/2:a[s]}function nte(t){const a=new Map;for(const s of t){if(s.medianPrice===null||s.medianPrice<=0)continue;const r=aN(s.period);if(!r)continue;const n=Number(r.slice(0,4)),i=a.get(n)??[];i.push(s.medianPrice),a.set(n,i)}return a.size<2?[]:Array.from(a.entries()).sort(([s],[r])=>s-r).map(([s,r])=>({year:s,medianPrice:Math.round(rK(r))}))}function nK(t){if(t.length===0)return{locationType:null,builtUp:null,growth:null,propertyValueTrend:null,demandSupply:null,marketingTime:null,priceRange:null,ageRange:null,landUse:null};const a=t.map(j=>j.price).filter(j=>j>0).sort((j,T)=>j-T),s=t.map(j=>j.yearBuilt).filter(j=>j>1800).sort((j,T)=>j-T),r=t.map(j=>j.dom||0).filter(j=>j>=0),n=r.length>0?r.reduce((j,T)=>j+T,0)/r.length:0,i=a.length>0?a[Math.floor(a.length/2)]:0;let l="Under3";n>180?l="Over6":n>90&&(l="3to6");let c="InBalance";n<30?c="Shortage":n>120&&(c="OverSupply");const d=t.filter(j=>["CLSD","Sold"].includes(j.status)),p=new Date,u=new Date(p.getTime()-2160*60*60*1e3),m=d.filter(j=>j.saleDate&&new Date(j.saleDate)>=u),h=d.filter(j=>j.saleDate&&new Date(j.saleDate)<u),f=m.length>0?m.map(j=>j.price).sort((j,T)=>j-T)[Math.floor(m.length/2)]:null,v=h.length>0?h.map(j=>j.price).sort((j,T)=>j-T)[Math.floor(h.length/2)]:null;let S="Stable";if(f&&v){const j=(f-v)/v;j>.03?S="Increasing":j<-.03&&(S="Declining")}const N=t.filter(j=>j.propertyType?.toLowerCase().includes("single")||j.propertyType?.toLowerCase().includes("sfr")||j.propertyType?.toLowerCase().includes("detached")).length,x=t.filter(j=>j.propertyType?.toLowerCase().includes("multi")||j.propertyType?.toLowerCase().includes("duplex")||j.propertyType?.toLowerCase().includes("triplex")).length,y=t.filter(j=>j.propertyType?.toLowerCase().includes("condo")||j.propertyType?.toLowerCase().includes("townhouse")).length,b=t.length;return{locationType:"Suburban",builtUp:t.length>50?"Over75":t.length>20?"25to75":"Under25",growth:"Stable",propertyValueTrend:S,demandSupply:c,marketingTime:l,priceRange:a.length>0?{low:a[0],high:a[a.length-1],predominant:i}:null,ageRange:s.length>0?{low:s[0],high:s[s.length-1],predominant:s[Math.floor(s.length/2)]}:null,landUse:b>0?{oneUnit:Math.round(N/b*100)||75,twoToFour:Math.round(x/b*100)||5,multiFamily:Math.round(y/b*100)||10,commercial:5,other:5}:null}}function u1(t){const a=new Date,s=new Date(a.getTime()-2160*60*60*1e3),r=new Date(a.getTime()-4320*60*60*1e3),n=new Date(a.getTime()-365*24*60*60*1e3),i=t.filter(b=>["CLSD","Sold"].includes(b.status)),l=t.filter(b=>O0(b.status)),c=(b,j,T)=>b.filter(O=>{if(!O.saleDate)return!1;const E=new Date(O.saleDate);return E>=j&&E<=T}),d=c(i,s,a),p=c(i,r,s),u=c(i,n,r),m=b=>{const j=b.map(T=>T.price).filter(T=>T>0).sort((T,O)=>T-O);return j.length>0?j[Math.floor(j.length/2)]:null},h=b=>{const j=b.map(T=>T.dom||0).sort((T,O)=>T-O);return j.length>0?j[Math.floor(j.length/2)]:null},f=d.length+p.length+u.length,v=f>0?f/12:null,S=v&&v>0?l.length/v:null;let N="Stable";const x=m(d),y=m(u);
39if(x&&y){const b=(x-y)/y;b>.05?N="Increasing":b<-.05&&(N="Declining")}return{inventory:{prior7to12:{sales:u.length,listings:0},prior4to6:{sales:p.length,listings:0},current0to3:{sales:d.length,listings:l.length}},absorptionRate:v,monthsOfSupply:S,medianSalePrice:{prior7to12:m(u),prior4to6:m(p),current0to3:m(d)},medianDom:{prior7to12:h(u),prior4to6:h(p),current0to3:h(d)},medianListPrice:{prior7to12:null,prior4to6:null,current0to3:m(l)},saleToListRatio:{prior7to12:null,prior4to6:null,current0to3:.98},overallTrend:N}}function p1(t){const a=new Map;for(const r of t){if(J0(r.status)!=="CLSD")continue;const n=r.contractDate||r.saleDate;if(!n)continue;const i=/^(\d{4})-(\d{2})(?:-\d{2}|T|$)/.exec(n.trim()),l=i?aN(`${i[1]}-${i[2]}`):(()=>{const d=new Date(n);return Number.isFinite(d.getTime())?aN(`${d.getUTCFullYear()}-${String(d.getUTCMonth()+1).padStart(2,"0")}`):null})();if(!l)continue;const c=a.get(l)??{prices:[],doms:[],saleToListRatios:[]};Number.isFinite(r.price)&&r.price>0&&c.prices.push(r.price),typeof r.dom=="number"&&Number.isFinite(r.dom)&&r.dom>=0&&c.doms.push(r.dom),typeof r.listPrice=="number"&&r.listPrice>0&&r.price>0&&c.saleToListRatios.push(r.price/r.listPrice),a.set(l,c)}const s=r=>{if(r.length===0)return null;const n=[...r].sort((l,c)=>l-c),i=Math.floor(n.length/2);return n.length%2===0?(n[i-1]+n[i])/2:n[i]};return Array.from(a.entries()).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>({period:r,medianPrice:s(n.prices),dom:s(n.doms),saleToListRatio:s(n.saleToListRatios),rentalRate:null,rentalInventory:null}))}function iK(t){return t<=30?{label:"Straightforward",colorClass:"text-green-600",bgClass:"bg-green-50"}:t<=50?{label:"Moderate",colorClass:"text-yellow-600",bgClass:"bg-yellow-50"}:t<=70?{label:"Complex",colorClass:"text-orange-600",bgClass:"bg-orange-50"}:{label:"Very Complex",colorClass:"text-red-600",bgClass:"bg-red-50"}}function oK({score:t,isLoading:a}){if(a)return e.jsx("div",{className:"w-14 h-14 rounded-xl bg-slate-100 flex items-center justify-center",children:e.jsx(za,{className:"w-5 h-5 animate-spin text-slate-400"})});if(t===null)return null;const s=iK(t);return e.jsxs("div",{className:Q("w-14 h-14 rounded-xl border-2 flex flex-col items-center justify-center",s.bgClass,s.colorClass.replace("text-","border-")),children:[e.jsx("span",{className:Q("text-lg font-bold",s.colorClass),children:t}),e.jsx("span",{className:Q("text-[8px] font-medium",s.colorClass),children:s.label})]})}function m1(t){return{polygons:t.polygons,circles:t.circles}}function nI(t){return{polygons:[...t.polygons],circles:[...t.circles]}}function h1(t){return t??null}function f1(t){return t?{polygons:[...t.polygons],circles:[...t.circles]}:{polygons:[],circles:[]}}function lK(t){return{filters:{...t.filters},boundaries:[...t.boundaries],radius:t.radius,shapes:nI(t.shapes)}}function xM({trend:t}){if(!t)return e.jsx("span",{className:"text-slate-400",children:"—"});const a={Increasing:{icon:Ql,color:"text-green-600",bg:"bg-green-50"},Stable:{icon:yI,color:"text-blue-600",bg:"bg-blue-50"},Declining:{icon:bN,color:"text-red-600",bg:"bg-red-50"}},{icon:s,color:r,bg:n}=a[t];return e.jsxs("div",{className:Q("inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium",n,r),children:[e.jsx(s,{className:"w-3 h-3"}),t]})}function Th({label:t,value:a,subValue:s}){return e.jsxs("div",{className:"flex items-center justify-between py-1.5",children:[e.jsx("span",{className:"text-sm text-slate-600",children:t}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-sm font-medium text-slate-900",children:a}),s&&e.jsx("div",{className:"text-xs text-slate-400",children:s})]})]})}function Om(t){return t===null?"—":t>=1e6?`$${(t/1e6).toFixed(2)}M`:t>=1e3?`$${(t/1e3).toFixed(0)}K`:`$${t.toLocaleString()}`}function e0({label:t,value:a,options:s,onChange:r,testId:n}){return e.jsxs("div",{className:"flex items-center justify-between py-1 gap-2",children:[e.jsx("span",{className:"text-xs text-slate-600",children:t}),e.jsxs(sr,{value:a??void 0,onValueChange:i=>r(i),children:[e.jsx(rr,{className:"h-7 w-[140px] text-xs","data-testid":n,children:e.jsx(or,{placeholder:"Select…"})}),e.jsx(nr,{children:Object.entries(s).map(([i,l])=>e.jsx(vs,{value:i,className:"text-xs",children:l},i))})]})]})}function cK({stats:t,locked:a,onLock:s,count:r,neighborhoodInfo:n,onNeighborhoodInfoChange:i,isGeneratingNeighborhood:l,neighborhoodAiGenerated:c,onManualEdit:d,onStatsChange:p}
39){const u=!a&&!!p,[m,h]=o.useState(n?.boundaries||""),[f,v]=o.useState(n?.description||""),[S,N]=o.useState(n?.marketConditions||""),x=o.useRef("");o.useEffect(()=>{const R=JSON.stringify(n||{});n&&R!==x.current&&(x.current=R,h(n.boundaries||""),v(n.description||""),N(n.marketConditions||""))},[n]);const y=(R,G)=>{const U={boundaries:R==="boundaries"?G:m,description:R==="description"?G:f,marketConditions:R==="marketConditions"?G:S};R==="boundaries"&&h(G),R==="description"&&v(G),R==="marketConditions"&&N(G),x.current=JSON.stringify(U),i?.(U),d?.()},b={Urban:"Urban",Suburban:"Suburban",Rural:"Rural"},j={Over75:"Over 75%","25to75":"25-75%",Under25:"Under 25%"},T={Rapid:"Rapid",Stable:"Stable",Slow:"Slow"},O={Shortage:"Shortage",InBalance:"In Balance",OverSupply:"Over Supply"},E={Under3:"Under 3 mths","3to6":"3-6 mths",Over6:"Over 6 mths"};return e.jsxs("div",{className:"space-y-4 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-semibold text-slate-800 flex items-center gap-2",children:[e.jsx(Wl,{className:"w-4 h-4 text-blue-600"}),"Market Area",r!==void 0&&e.jsxs(kt,{variant:"secondary",className:"text-xs font-normal",children:[r," sales"]})]}),e.jsxs(De,{variant:a?"default":"outline",size:"sm",onClick:s,className:"gap-1.5","data-testid":"button-lock-market",children:[a?e.jsx(Hr,{className:"w-3.5 h-3.5"}):e.jsx(lf,{className:"w-3.5 h-3.5"}),a?"Locked":"Lock Market"]})]}),e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-2",children:e.jsx(ko,{className:"text-xs uppercase tracking-wide text-slate-500",children:"Neighborhood Characteristics"})}),e.jsxs(Ta,{className:"space-y-1",children:[e.jsx(Th,{label:"Location",value:t?.locationType?b[t.locationType]:"—"}),u?e.jsxs(e.Fragment,{children:[e.jsx(e0,{label:"Built-Up",value:t?.builtUp??null,options:j,onChange:R=>p?.({builtUp:R}),testId:"select-builtup"}),e.jsx(e0,{label:"Growth",value:t?.growth??null,options:T,onChange:R=>p?.({growth:R}),testId:"select-growth"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Th,{label:"Built-Up",value:t?.builtUp?j[t.builtUp]:"—"}),e.jsx(Th,{label:"Growth",value:t?.growth?T[t.growth]:"—"})]})]})]}),e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-2",children:e.jsx(ko,{className:"text-xs uppercase tracking-wide text-slate-500",children:"One-Unit Housing Trends"})}),e.jsx(Ta,{className:"space-y-1",children:u?e.jsxs(e.Fragment,{children:[e.jsx(e0,{label:"Property Values",value:t?.propertyValueTrend??null,options:{Increasing:"Increasing",Stable:"Stable",Declining:"Declining"},onChange:R=>p?.({propertyValueTrend:R}),testId:"select-property-value-trend"}),e.jsx(e0,{label:"Demand/Supply",value:t?.demandSupply??null,options:O,onChange:R=>p?.({demandSupply:R}),testId:"select-demand-supply"}),e.jsx(e0,{label:"Marketing Time",value:t?.marketingTime??null,options:E,onChange:R=>p?.({marketingTime:R}),testId:"select-marketing-time"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Th,{label:"Property Values",value:e.jsx(xM,{trend:t?.propertyValueTrend||null})}),e.jsx(Th,{label:"Demand/Supply",value:t?.demandSupply?O[t.demandSupply]:"—"}),e.jsx(Th,{label:"Marketing Time",value:t?.marketingTime?E[t.marketingTime]:"—"})]})})]}),e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-2",children:e.jsx(ko,{className:"text-xs uppercase tracking-wide text-slate-500",children:"One-Unit Housing"})}),e.jsxs(Ta,{className:"space-y-1",children:[e.jsx(Th,{label:"Price Range",value:t?.priceRange?`${Om(t.priceRange.low)} - ${Om(t.priceRange.high)}`:"—",subValue:t?.priceRange?`Pred: ${Om(t.priceRange.predominant)}`:void 0}),e.jsx(Th,{label:"Age Range",value:t?.ageRange?`${t.ageRange.low} - ${t.ageRange.high} yrs`:"—",subValue:t?.ageRange?`Pred: ${t.ageRange.predominant} yrs`:void 0})]})]}),e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-2",children:e.jsx(ko,{className:"text-xs uppercase tracking-wide text-slate-500",children:"Present Land Use %"})}),e.jsx(Ta,{children:t?.landUse?e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"w-3.5 h-3.5 text-blue-500"}),e.jsx("span",{className:"text-xs text-slate-600",children:"One-Unit"}),e.jsxs("span",{className:"ml-auto text-sm font-medium",children:[t.landUse.oneUnit,"%"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lp,{className:"w-3.5 h-3.5 text-purple-500"}),e.jsx("span",{className:"text-xs text-slate-600",children:"2-4 Unit"}),e.jsxs("span",{className:"ml-auto text-sm font-medium",children:[t.landUse.twoToFour,"%"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lp,{className:"w-3.5 h-3.5 text-orange-500"}),e.jsx("span",{className:"text-xs text-slate-600",children:"Multi-Fam"}),e.jsxs("span",{className:"ml-auto text-sm font-medium",children:[t.landUse.multiFamily,"%"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y5,{className:"w-3.5 h-3.5 text-green-500"}),e.jsx("span",{className:"text-xs text-slate-600",children:"Comm"}),e.jsxs("span",{className:"ml-auto text-sm font-medium",children:[t.landUse.commercial,"%"]})]}),e.jsxs("div",{className:"flex items-center gap-2 col-span-2",children:[e.jsx(Wl,{className:"w-3.5 h-3.5 text-slate-400"}),e.jsx("span",{className:"text-xs text-slate-600",children:"Other"}),e.jsxs("span",{className:"ml-auto text-sm font-medium",children:[t.landUse.other,"%"]})]})]}):e.jsx("p",{className:"text-sm text-slate-400 text-center py-2",children:"No data available"})})]}),e.jsxs(ja,{children:[e.jsxs(Do,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ko,{className:"text-xs uppercase tracking-wide text-slate-500 flex items-center gap-1.5",children:[e.jsx(gn,{className:"w-3.5 h-3.5"}),"Neighborhood Info (Form 1004)"]}),l?e.jsxs(kt,{variant:"secondary",className:"h-6 text-xs gap-1",children:[e.jsx(Kl,{className:"w-3 h-3 animate-spin"}),"Generating..."]}
39):c&&(m||f)?e.jsxs(kt,{variant:"secondary",className:"h-6 text-xs gap-1 bg-purple-50 text-purple-700 border-purple-200",children:[e.jsx(ul,{className:"w-3 h-3"}),"AI Suggested"]}):null]}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:l?"AI is finding major roads & generating neighborhood info...":c?"Suggested boundaries from major roads. Feel free to edit.":"Lock market to auto-generate, or enter manually"})]}),e.jsxs(Ta,{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium text-slate-600",children:"Neighborhood Boundaries"}),e.jsx(yi,{value:m,onChange:R=>y("boundaries",R.target.value),placeholder:"North: Main St; South: Oak Ave; East: Hwy 101; West: River Rd",className:"mt-1 text-sm min-h-[50px]","data-testid":"textarea-neighborhood-boundaries",disabled:l})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium text-slate-600",children:"Neighborhood Description"}),e.jsx(yi,{value:f,onChange:R=>y("description",R.target.value),placeholder:"Land use, housing types, lot sizes...",className:"mt-1 text-sm min-h-[60px]","data-testid":"textarea-neighborhood-description",disabled:l})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium text-slate-600",children:"Market Conditions"}),e.jsx(yi,{value:S,onChange:R=>y("marketConditions",R.target.value),placeholder:"Current market conditions supporting the trend data...",className:"mt-1 text-sm min-h-[60px]","data-testid":"textarea-market-conditions",disabled:l})]})]})]})]})}function dK({stats:t,locked:a,onLock:s,count:r}){return e.jsxs("div",{className:"space-y-4 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-semibold text-slate-800 flex items-center gap-2",children:[e.jsx(Pl,{className:"w-4 h-4 text-purple-600"}),"Sub-Market",r!==void 0&&e.jsxs(kt,{variant:"secondary",className:"text-xs font-normal",children:[r," sales"]})]}),e.jsxs(De,{variant:a?"default":"outline",size:"sm",onClick:s,className:"gap-1.5","data-testid":"button-lock-submarket",children:[a?e.jsx(Hr,{className:"w-3.5 h-3.5"}):e.jsx(lf,{className:"w-3.5 h-3.5"}),a?"Locked":"Lock Sub-Market"]})]}),e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-2",children:e.jsx(ko,{className:"text-xs uppercase tracking-wide text-slate-500",children:"Inventory Analysis"})}),e.jsx(Ta,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-2 font-medium text-slate-500"}),e.jsx("th",{className:"text-center py-2 font-medium text-slate-500",children:"7-12 Mo"}),e.jsx("th",{className:"text-center py-2 font-medium text-slate-500",children:"4-6 Mo"}),e.jsx("th",{className:"text-center py-2 font-medium text-slate-500",children:"0-3 Mo"}),e.jsx("th",{className:"text-center py-2 font-medium text-slate-500",children:"Trend"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 text-slate-600",children:"Comp Sales"}),e.jsx("td",{className:"text-center font-medium",children:t?.inventory.prior7to12.sales??"—"}),e.jsx("td",{className:"text-center font-medium",children:t?.inventory.prior4to6.sales??"—"}),e.jsx("td",{className:"text-center font-medium",children:t?.inventory.current0to3.sales??"—"}),e.jsx("td",{className:"text-center",children:e.jsx(xM,{trend:t?.overallTrend||null})})]}),e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 text-slate-600",children:"Active Listings"}),e.jsx("td",{className:"text-center font-medium",children:t?.inventory.prior7to12.listings??"—"}),e.jsx("td",{className:"text-center font-medium",children:t?.inventory.prior4to6.listings??"—"}),e.jsx("td",{className:"text-center font-medium",children:t?.inventory.current0to3.listings??"—"}),e.jsx("td",{})]})]})]})})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(ja,{children:e.jsxs(Ta,{className:"pt-4 text-center",children:[e.jsx(W0,{className:"w-5 h-5 text-orange-500 mx-auto mb-1"}),e.jsx("div",{className:"text-2xl font-bold text-slate-800",children:t?.absorptionRate?`${t.absorptionRate.toFixed(1)}`:"—"}),e.jsx("div",{className:"text-xs text-slate-500",children:"Absorption Rate"}),e.jsx("div",{className:"text-xs text-slate-400",children:"(sales/month)"})]})}),e.jsx(ja,{children:e.jsxs(Ta,{className:"pt-4 text-center",children:[e.jsx(Pu,{className:"w-5 h-5 text-blue-500 mx-auto mb-1"}),e.jsx("div",{className:"text-2xl font-bold text-slate-800",children:t?.monthsOfSupply?`${t.monthsOfSupply.toFixed(1)}`:"—"}),e.jsx("div",{className:"text-xs text-slate-500",children:"Months Supply"})]})})]}
39),e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-2",children:e.jsx(ko,{className:"text-xs uppercase tracking-wide text-slate-500",children:"Median Sale & List Price, DOM"})}),e.jsx(Ta,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-2 font-medium text-slate-500"}),e.jsx("th",{className:"text-center py-2 font-medium text-slate-500",children:"7-12 Mo"}),e.jsx("th",{className:"text-center py-2 font-medium text-slate-500",children:"4-6 Mo"}),e.jsx("th",{className:"text-center py-2 font-medium text-slate-500",children:"0-3 Mo"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 text-slate-600",children:"Sale Price"}),e.jsx("td",{className:"text-center font-medium",children:Om(t?.medianSalePrice.prior7to12??null)}),e.jsx("td",{className:"text-center font-medium",children:Om(t?.medianSalePrice.prior4to6??null)}),e.jsx("td",{className:"text-center font-medium",children:Om(t?.medianSalePrice.current0to3??null)})]}),e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 text-slate-600",children:"List Price"}),e.jsx("td",{className:"text-center font-medium",children:Om(t?.medianListPrice.prior7to12??null)}),e.jsx("td",{className:"text-center font-medium",children:Om(t?.medianListPrice.prior4to6??null)}),e.jsx("td",{className:"text-center font-medium",children:Om(t?.medianListPrice.current0to3??null)})]}),e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 text-slate-600",children:"DOM"}),e.jsx("td",{className:"text-center font-medium",children:t?.medianDom.prior7to12??"—"}),e.jsx("td",{className:"text-center font-medium",children:t?.medianDom.prior4to6??"—"}),e.jsx("td",{className:"text-center font-medium",children:t?.medianDom.current0to3??"—"})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"py-2 text-slate-600",children:"Sale/List %"}),e.jsx("td",{className:"text-center font-medium",children:t?.saleToListRatio.prior7to12?`${(t.saleToListRatio.prior7to12*100).toFixed(1)}%`:"—"}),e.jsx("td",{className:"text-center font-medium",children:t?.saleToListRatio.prior4to6?`${(t.saleToListRatio.prior4to6*100).toFixed(1)}%`:"—"}),e.jsx("td",{className:"text-center font-medium",children:t?.saleToListRatio.current0to3?`${(t.saleToListRatio.current0to3*100).toFixed(1)}%`:"—"})]})]})]})})})]})]})}function uK({urarStats:t,form1004mcStats:a,marketLocked:s,subMarketLocked:r,onLockMarket:n,onLockSubMarket:i,isLoading:l,marketCount:c,submarketCount:d,neighborhoodInfo:p,onNeighborhoodInfoChange:u,onNeighborhoodManualEdit:m,onStatsChange:h,subjectAddress:f,subjectCity:v,subjectCounty:S,subjectState:N,radiusMiles:x,isGeneratingNeighborhood:y,neighborhoodAiGenerated:b}){const[j,T]=o.useState("market"),[O,E]=o.useState(!1),R=C=>{T(C)},G=()=>j==="market"?e.jsx(cK,{stats:t,locked:s,onLock:n,count:c,neighborhoodInfo:p,onNeighborhoodInfoChange:u,isGeneratingNeighborhood:y,neighborhoodAiGenerated:b,onManualEdit:m,onStatsChange:h}):j==="submarket"?e.jsx(dK,{stats:a,locked:r,onLock:i,count:d}):null,U=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"shrink-0 border-b px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(up,{value:j,onValueChange:R,className:"flex-1",children:e.jsxs(pp,{className:"grid grid-cols-2 w-full",children:[e.jsxs($n,{value:"market",className:"text-xs gap-1","data-testid":"tab-market",children:[e.jsx(Wl,{className:"w-3 h-3"}),"Market",c!==void 0&&e.jsxs("span",{className:"text-slate-400",children:["(",c,")"]}),s&&e.jsx(Hr,{className:"w-2.5 h-2.5 text-green-600"})]}),e.jsxs($n,{value:"submarket",className:"text-xs gap-1","data-testid":"tab-submarket",children:[e.jsx(Pl,{className:"w-3 h-3"}),"Sub-Market",d!==void 0&&e.jsxs("span",{className:"text-slate-400",children:["(",d,")"]}),r&&e.jsx(Hr,{className:"w-2.5 h-2.5 text-green-600"})]})]})}),!O&&e.jsx(De,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 shrink-0",onClick:()=>E(!0),"data-testid":"button-expand-panel",children:e.jsx(ub,{className:"w-4 h-4"})})]})}),e.jsx(Qd,{className:"flex-1",children:G()})]});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-full flex flex-col bg-white","data-testid":"market-stats-panel",children:U}),e.jsx(xi,{open:O,onOpenChange:E,children:e.jsxs(bi,{className:"max-w-[95vw] w-[95vw] max-h-[95vh] p-0 flex flex-col",children:[e.jsx($i,{className:"sr-only",children:e.jsx(si,{children:"Market Statistics"})}),e.jsxs("div",{className:"flex flex-col h-[90vh]",children:[e.jsx("div",{className:"shrink-0 border-b px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(up,{value:j,onValueChange:R,className:"flex-1",children:e.jsxs(pp,{className:"grid grid-cols-2 w-full max-w-sm",children:[e.jsxs($n,{value:"market",className:"text-sm gap-1.5","data-testid":"tab-market-expanded",children:[e.jsx(Wl,{className:"w-4 h-4"}),"Market",c!==void 0&&e.jsxs("span",{className:"text-slate-400",children:["(",c,")"]}),s&&e.jsx(Hr,{className:"w-3 h-3 text-green-600"})]}),e.jsxs($n,{value:"submarket",className:"text-sm gap-1.5","data-testid":"tab-submarket-expanded",children:[e.jsx(Pl,{className:"w-4 h-4"}),"Sub-Market",d!==void 0&&e.jsxs("span",{className:"text-slate-400",children:["(",d,")"]}),r&&e.jsx(Hr,{className:"w-3 h-3 text-green-600"})]})]})}),e.jsx(De,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 shrink-0",onClick:()=>E(!1),"data-testid":"button-minimize-panel",children:e.jsx(eL,{className:"w-4 h-4"})})]})}),e.jsx(Qd,{className:"flex-1",children:G()})]})]})})]})}const pK={paired_sales:{label:"Paired Sales Analysis",icon:e.jsx(gv,{className:"w-4 h-4"})},regression:{label:"Regression Analysis",icon:e.jsx(Ql,{className:"w-4 h-4"})},sale_resale:{label:"Sale/Re-sale Analysis",icon:e.jsx(gn,{className:"w-4 h-4"})},published_data:{label:"Published Data",icon:e.jsx(Jx,{className:"w-4 h-4"})},mass_data:{label:"Mass Data Analysis",icon:e.jsx(gv,{className:"w-4 h-4"})},uad_scale:{label:"UAD Scale (Fannie Mae)",icon:e.jsx(gn,{className:"w-4 h-4"})},default:{label:"Default Rate",icon:e.jsx(Di,{className:"w-4 h-4"})}};function mK({evidence:t}){return!t||t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map((a,s)=>{switch(a.type){case"paired_sale":return e.jsxs("div",{className:"bg-slate-50 rounded p-2 text-xs",children:[e.jsxs("div",{className:"font-medium text-slate-700 mb-1",children:["Paired Sale #",s+1]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-slate-600",children:[e.jsxs("div",{children:[e.jsx("div",{className:"truncate",children:a.sale1.address}
39),e.jsxs("div",{children:["$",a.sale1.salePrice.toLocaleString()]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"truncate",children:a.sale2.address}),e.jsxs("div",{children:["$",a.sale2.salePrice.toLocaleString()]})]})]}),e.jsxs("div",{className:"mt-1 font-medium text-slate-800",children:["Difference: $",Math.abs(a.priceDifference).toLocaleString()," → $",a.impliedRate.toLocaleString(),"/unit"]})]},s);case"regression":return e.jsxs("div",{className:"bg-slate-50 rounded p-2 text-xs",children:[e.jsx("div",{className:"font-medium text-slate-700 mb-1",children:"Regression Analysis"}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-4 text-slate-600",children:[e.jsxs("div",{children:["Sample Size: ",a.sampleSize]}),e.jsxs("div",{children:["R²: ",(a.rSquared*100).toFixed(1),"%"]}),e.jsxs("div",{children:["Coefficient: $",a.coefficient.toFixed(2)]}),e.jsxs("div",{children:["Range: $",a.dataRange.min.toLocaleString()," - $",a.dataRange.max.toLocaleString()]})]})]},s);case"sale_resale":return e.jsxs("div",{className:"bg-slate-50 rounded p-2 text-xs",children:[e.jsxs("div",{className:"font-medium text-slate-700 mb-1",children:["Sale/Re-sale: ",a.address]}),e.jsxs("div",{className:"text-slate-600",children:[e.jsxs("div",{children:["$",a.sale1.price.toLocaleString()," (",a.sale1.date,") → $",a.sale2.price.toLocaleString()," (",a.sale2.date,")"]}),e.jsxs("div",{className:"mt-1 font-medium text-slate-800",children:[a.monthsBetween," months, $",Math.abs(a.priceDifference).toLocaleString()," change → ",(a.impliedMonthlyRate*100).toFixed(2),"%/mo"]})]})]},s);case"published_data":return e.jsxs("div",{className:"bg-slate-50 rounded p-2 text-xs",children:[e.jsx("div",{className:"font-medium text-slate-700 mb-1",children:a.source.replace("_"," ")}),e.jsxs("div",{className:"text-slate-600",children:[e.jsxs("div",{children:[a.dataPoint,": ",a.value,"%"]}),e.jsxs("div",{children:[a.geography," as of ",a.asOfDate]})]})]},s);case"mass_data":return e.jsxs("div",{className:"bg-slate-50 rounded p-2 text-xs",children:[e.jsx("div",{className:"font-medium text-slate-700 mb-1",children:"Mass Data Analysis"}),e.jsxs("div",{className:"text-slate-600",children:[e.jsxs("div",{children:[a.metric,": ",a.value," (n=",a.sampleSize,")"]}),e.jsxs("div",{children:["Range: ",a.range.min," - ",a.range.max]}),e.jsx("div",{className:"text-slate-500 mt-1",children:a.methodology})]})]},s);default:return null}})})}function Fp({icon:t,title:a,rate:s,description:r,confidence:n,support:i,testId:l}){const[c,d]=o.useState(!1),[p,u]=o.useState(!1),m=i&&!i.isDefault,h=i?.derivationMethod||"default",f=pK[h];return e.jsxs("div",{className:Q("bg-white border border-slate-200 rounded-lg shadow-sm transition-all duration-200",m&&"cursor-pointer hover:border-slate-300 hover:shadow-md",c&&"ring-2 ring-blue-200"),onClick:()=>m&&d(!c),"data-testid":l,children:[e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t,e.jsx("span",{className:"font-semibold text-slate-700",children:a}),n&&e.jsx("span",{className:Q("text-[10px] px-1.5 py-0.5 rounded",n==="high"?"bg-green-100 text-green-700":n==="medium"?"bg-yellow-100 text-yellow-700":"bg-slate-100 text-slate-600"),children:n}),m&&e.jsx("span",{className:"ml-auto text-slate-400",children:c?e.jsx(Du,{className:"w-4 h-4"}):e.jsx(Rr,{className:"w-4 h-4"})})]}),e.jsx("div",{className:"text-2xl font-bold text-slate-900 mb-2",children:s}),e.jsx("p",{className:"text-xs text-slate-500",children:r})]}),c&&i&&e.jsxs("div",{className:"border-t border-slate-200 p-4 bg-slate-50/50 space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-slate-700 mb-2",children:[f.icon,e.jsx("span",{children:"Derivation Method"})]}),e.jsx("p",{className:"text-sm text-slate-600",children:f.label})]}),i.evidence&&i.evidence.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-slate-700 mb-2",children:[e.jsx(gv,{className:"w-4 h-4"}),e.jsx("span",{children:"Supporting Evidence"})]}),e.jsx(mK,{evidence:i.evidence})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-slate-700 mb-2",children:[e.jsx(gn,{className:"w-4 h-4"}),e.jsx("span",{children:"Narrative (for Addendum)"})]}),e.jsxs("div",{className:"bg-white rounded border border-slate-200 p-3 text-sm text-slate-700 italic",children:['"',i.narrative,'"']}),e.jsxs("button",{className:Q("mt-2 text-xs flex items-center gap-1 transition-colors",p?"text-green-600":"text-blue-600 hover:text-blue-800"),onClick:v=>{v.stopPropagation(),navigator.clipboard.writeText(i.narrative),u(!0),setTimeout(()=>u(!1),2e3)},"data-testid":`button-copy-narrative-${l}`,children:[p?e.jsx(Bs,{className:"w-3 h-3"}):e.jsx(jr,{className:"w-3 h-3"}),p?"Copied!":"Copy to clipboard"]})]}),i.methodologyNotes&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-slate-700 mb-2",children:[e.jsx(gn,{className:"w-4 h-4"}),e.jsx("span",{children:"Methodology Notes"})]}),e.jsx("p",{className:"text-xs text-slate-600",children:i.methodologyNotes})]}),i.assumptions&&i.assumptions.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-slate-700 mb-2",children:[e.jsx(Di,{className:"w-4 h-4"}),e.jsx("span",{children:"Assumptions"})]}),e.jsx("ul",{className:"text-xs text-slate-600 list-disc list-inside space-y-1",children:i.assumptions.map((v,S)=>e.jsx("li",{children:v}
39,S))})]}),i.limitingConditions&&i.limitingConditions.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-amber-700 mb-2",children:[e.jsx(Di,{className:"w-4 h-4"}),e.jsx("span",{children:"Limiting Conditions"})]}),e.jsx("ul",{className:"text-xs text-amber-600 list-disc list-inside space-y-1",children:i.limitingConditions.map((v,S)=>e.jsx("li",{children:v},S))})]}),i.dataRecency&&e.jsxs("div",{className:"text-xs text-slate-400",children:["Data as of: ",i.dataRecency]})]})]})}const bM={time:"Time",gla:"GLA (Size)",location:"Location",condition:"Condition",quality:"Quality",site:"Site (Lot)",bedrooms:"Bedrooms",bathrooms:"Bathrooms",basement:"Basement",garage:"Garage"},g1=["time","gla","location","condition","quality","site","bedrooms","bathrooms","basement","garage"];function km(t){return t===0?"$0":`${t>0?"+":""}$${Math.abs(Math.round(t)).toLocaleString()}`}function iI(t,a){if(t===0)return"text-slate-400";const s=Math.abs(t/(a||1))*100;return s>15?"text-red-700":s>8?"text-amber-700":"text-emerald-700"}function hK(t,a){if(t===0)return"bg-white";const s=Math.abs(t/(a||1))*100;return s>15?"bg-red-50":s>8?"bg-amber-50":"bg-emerald-50"}function yM(t){return t==="high"?"bg-emerald-500":t==="medium"?"bg-amber-500":"bg-red-500"}function fK(t){return{high:"bg-emerald-100 text-emerald-700 border-emerald-200",medium:"bg-amber-100 text-amber-700 border-amber-200",low:"bg-red-100 text-red-700 border-red-200"}[t]}function gK(t){const a=typeof t.subjectValue=="number"?t.subjectValue.toLocaleString():String(t.subjectValue||""),s=typeof t.compValue=="number"?t.compValue.toLocaleString():String(t.compValue||""),r=t.difference,n=t.rate,i=r>0?"+":"";if(t.suggestedAmount===0&&r===0)return a&&s&&a===s?`Both ${a}`:"Same";switch(t.factor){case"time":return r===0?"Current sale":`${r} mo × $${Math.abs(n).toLocaleString()}/mo`;case"gla":return r===0?`Both ${a}`:`${a} → ${s} = ${i}${r.toLocaleString()} sqft × $${Math.round(n).toLocaleString()}/sqft`;case"location":return r===0?`Both ${a}`:`${a} → ${s} = ${i}${r} pts × $${Math.round(n).toLocaleString()}/pt`;case"condition":case"quality":return r===0?`Both ${a}`:`${a} → ${s} = ${Math.abs(r)} lvl × $${Math.round(n).toLocaleString()}/lvl`;case"site":return r===0?`Both ${a}`:`${a} → ${s} = ${i}${r} ac × $${Math.round(n).toLocaleString()}/ac`;case"bedrooms":return r===0?`Both ${a}`:`${a} → ${s} = ${i}${r} bed × $${Math.round(n).toLocaleString()}/bed`;case"bathrooms":return r===0?`Both ${a}`:`${a} → ${s} = ${i}${r} bath × $${Math.round(n).toLocaleString()}/bath`;case"basement":return r===0?`Both ${a}`:`${a} → ${s}`;case"garage":return r===0?`Both ${a}`:`${a} → ${s} = ${i}${r} spc × $${Math.round(n).toLocaleString()}/spc`;default:return t.rateBasis}}function xK({low:t,high:a,value:s,confidence:r}){const n=Math.max(Math.abs(t),Math.abs(a),1),i=(a-t)/(n*2.5)*100,l=(t+n)/(n*2.5)*100,c=(s+n)/(n*2.5)*100,d=yM(r);return e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("div",{className:"w-full h-2.5 relative mt-0.5 mb-0.5 cursor-help","data-testid":"range-bar",children:[e.jsx("div",{className:"absolute inset-0 bg-slate-100 rounded-full"}),e.jsx("div",{className:"absolute top-0 h-2.5 bg-blue-200 rounded-full",style:{left:`${Math.max(0,Math.min(100,l))}%`,width:`${Math.max(2,Math.min(100,i))}%`}}),e.jsx("div",{className:`absolute top-0 w-2 h-2.5 rounded-full ${d}`,style:{left:`${Math.max(0,Math.min(96,c))}%`}})]})}),e.jsx(Wa,{side:"top",className:"max-w-[220px]",children:e.jsxs("div",{className:"text-xs space-y-0.5",children:[e.jsxs("div",{className:"font-medium",children:["Suggested: ",km(s)]}),e.jsxs("div",{children:["Range: ",km(t)," – ",km(a)]}),e.jsxs("div",{className:"capitalize",children:["Confidence: ",r]})]})})]})})}function bK({dep:t}){const a={info:"border-blue-200 bg-blue-50 text-blue-800",warning:"border-amber-200 bg-amber-50 text-amber-800",critical:"border-red-200 bg-red-50 text-red-800"},s=t.severity==="critical"?Ns:t.severity==="warning"?Ns:on;return e.jsxs("div",{className:`flex items-start gap-2 p-2.5 rounded-lg border text-xs ${a[t.severity]}`,"data-testid":`interdependency-${t.factor1}-${t.factor2}`,children:[e.jsx(s,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium",children:[t.factor1," ↔ ",t.factor2]}),e.jsxs("span",{className:"mx-1.5 opacity-60",children:["r=",t.correlation.toFixed(2)]}),e.jsxs("span",{className:"opacity-80",children:["— ",t.recommendation]})]})]})}function yK(t,a){const s=a.rateDetails?.[t],r=s?s.sampleSize>=15?"high":s.sampleSize>=8?"medium":"low":"low",n=s?.source||"Default",c=a.compSuggestions[0]?.adjustments.find(d=>d.factor===t)?.rate||0;switch(t){case"time":return{rate:`${(c*100).toFixed(2)}%`,unit:"/month",confidence:r,source:n};
39case"gla":return{rate:`$${Math.round(c).toLocaleString()}`,unit:"/sqft",confidence:r,source:n};case"location":return{rate:`$${Math.round(c).toLocaleString()}`,unit:"/point",confidence:r,source:n};case"condition":case"quality":return{rate:`$${Math.round(c).toLocaleString()}`,unit:"/level",confidence:r,source:n};case"site":return{rate:`$${Math.round(c).toLocaleString()}`,unit:"/acre",confidence:r,source:n};case"bedrooms":return{rate:`$${Math.round(c).toLocaleString()}`,unit:"/bed",confidence:r,source:n};case"bathrooms":return{rate:`$${Math.round(c).toLocaleString()}`,unit:"/bath",confidence:r,source:n};case"basement":return{rate:`$${Math.round(c).toLocaleString()}`,unit:"",confidence:r,source:n};case"garage":return{rate:`$${Math.round(c).toLocaleString()}`,unit:"/space",confidence:r,source:n};default:return{rate:`$${Math.round(c).toLocaleString()}`,unit:"",confidence:r,source:n}}}function SK(t){switch(t){case"green":return{label:"Within utility band — adjustment may not be needed",className:"bg-emerald-50 text-emerald-700 border-emerald-200"};case"yellow":return{label:"Sensitivity zone",className:"bg-amber-50 text-amber-700 border-amber-200"};case"red":return{label:"",className:""}}}function vK({data:t,loading:a,onApplyAdjustments:s,onClose:r,glaBand:n,utilityBands:i}){const[l,c]=o.useState(1),[d,p]=o.useState(new Set(g1)),[u,m]=o.useState({}),[h,f]=o.useState(null),[v,S]=o.useState(""),N=o.useMemo(()=>{if(!t)return[];const A=new Set;return t.compSuggestions.forEach(M=>{M.adjustments.forEach(B=>{(B.suggestedAmount!==0||B.suppressed)&&A.add(B.factor)})}),g1.filter(M=>A.has(M))},[t]),x=o.useCallback((A,M,B)=>u[A]?.[M]??B,[u]),y=o.useCallback((A,M,B)=>{m(oe=>({...oe,[A]:{...oe[A]||{},[M]:Math.round(B)}}))},[]),b=o.useCallback((A,M)=>{m(B=>{const oe={...B};if(oe[A]){const{[M]:ae,...D}=oe[A];Object.keys(D).length===0?delete oe[A]:oe[A]=D}return oe})},[]),j=o.useCallback((A,M)=>u[A]?.[M]!==void 0,[u]),T=o.useMemo(()=>t?t.compSuggestions.map(A=>{let M=0,B=0;A.adjustments.forEach(ae=>{if(!d.has(ae.factor)||ae.suppressed)return;const D=x(A.compId,ae.factor,ae.suggestedAmount);M+=D,B+=Math.abs(D)});const oe=A.salePrice>0?B/A.salePrice*100:0;return{compId:A.compId,compAddress:A.compAddress,salePrice:A.salePrice,net:Math.round(M),gross:Math.round(B),grossPct:Math.round(oe*10)/10,adjustedPrice:Math.round(A.salePrice+M)}}):[],[t,d,x]),O=o.useMemo(()=>{if(T.length===0)return 0;const A=[...T].map(M=>M.adjustedPrice).sort((M,B)=>M-B);return A[Math.floor(A.length/2)]},[T]),E=A=>{p(M=>{const B=new Set(M);return B.has(A)?B.delete(A):B.add(A),B})},R=(A,M,B)=>{f({compId:A,factor:M}),S(String(Math.round(B)))},G=()=>{if(!h)return;const A=parseInt(v,10);!isNaN(A)&&v.trim()!==""&&y(h.compId,h.factor,A),f(null)},U=()=>{if(!t||!s)return;const A=t.compSuggestions.map(M=>{const B={};return M.adjustments.forEach(oe=>{d.has(oe.factor)&&!oe.suppressed&&(B[oe.factor]=x(M.compId,oe.factor,oe.suggestedAmount))}),{compId:M.compId,adjustments:B}});s(A)};if(a)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 gap-3","data-testid":"advisor-loading",children:[e.jsx("div",{className:"w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Analyzing market data and deriving adjustments..."})]});if(!t||t.compSuggestions.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 gap-3","data-testid":"advisor-empty",children:[e.jsx(Ng,{className:"w-10 h-10 text-slate-300"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Select comps and run AVM analysis first to see suggested adjustments."})]});const C=t.compSuggestions.length,F=Object.values(u).reduce((A,M)=>A+Object.keys(M).length,0);return e.jsxs("div",{className:"space-y-4","data-testid":"adjustment-advisor",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ul,{className:"w-5 h-5 text-blue-600"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-900",children:"Adjustment Advisor"}),e.jsxs("p",{className:"text-xs text-slate-500",children:[t.marketPoolSize," market sales • Median: $",t.medianPrice.toLocaleStr
39ing()," • ",C," comp",C!==1?"s":""]})]})]}),e.jsxs(kt,{variant:"outline",className:t.overallComplexity==="low"?"border-emerald-300 text-emerald-700 bg-emerald-50":t.overallComplexity==="moderate"?"border-amber-300 text-amber-700 bg-amber-50":"border-red-300 text-red-700 bg-red-50","data-testid":"advisor-complexity",children:[t.overallComplexity," complexity"]})]}),e.jsx("div",{className:"flex items-center gap-2","data-testid":"advisor-step-nav",children:[1,2,3].map(A=>e.jsxs("button",{onClick:()=>c(A),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition-all ${l===A?"bg-blue-600 text-white shadow-sm":l>A?"bg-emerald-100 text-emerald-700 hover:bg-emerald-200":"bg-slate-100 text-slate-500 hover:bg-slate-200"}`,"data-testid":`advisor-step-${A}`,children:[l>A?e.jsx(kr,{className:"w-3.5 h-3.5"}):e.jsx("span",{className:"w-4 h-4 rounded-full border border-current flex items-center justify-center text-[10px]",children:A}),A===1?"Rates":A===2?"Per-Comp":"Apply"]},A))}),t.interdependencies.length>0&&l<=2&&e.jsx("div",{className:"space-y-1.5","data-testid":"advisor-interdependencies",children:t.interdependencies.map((A,M)=>e.jsx(bK,{dep:A},M))}),l===1&&e.jsx(NK,{data:t,activeFactors:N,selectedFactors:d,toggleFactor:E,onNext:()=>c(2),glaBand:n,utilityBands:i}),l===2&&e.jsx(AK,{data:t,activeFactors:N,selectedFactors:d,overrides:u,editingCell:h,editInputValue:v,getEffectiveValue:x,hasOverride:j,startEditing:R,setEditInputValue:S,commitEdit:G,clearOverride:b,setOverride:y,computedFooter:T,onBack:()=>c(1),onNext:()=>c(3),glaBand:n,utilityBands:i}),l===3&&e.jsx(jK,{data:t,computedFooter:T,medianAdjustedPrice:O,totalOverrides:F,onResetOverrides:()=>m({}),onApply:U,onBack:()=>c(2)})]})}function NK({data:t,activeFactors:a,selectedFactors:s,toggleFactor:r,onNext:n,glaBand:i,utilityBands:l}){return e.jsxs("div",{className:"space-y-3","data-testid":"advisor-step1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-slate-500 mb-2 block",children:"1. Your Rates at a Glance"}),e.jsx("p",{className:"text-xs text-slate-400 mb-3",children:"These rates were derived from your locked market data. Check the factor tabs (Time, GLA, Cond/Qual, Location) for detailed analysis. Toggle factors on/off to include in the adjustment grid."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:a.map(c=>{const d=yK(c,t),p=s.has(c),u=t.compSuggestions[0]?.adjustments.find(h=>h.factor===c),m=u?.suppressed??!1;return e.jsxs("div",{className:`flex flex-col gap-1 p-3 rounded-lg border transition-all ${m?"bg-slate-50 border-slate-200 opacity-60":p?"bg-white border-slate-200 hover:border-blue-300":"bg-slate-50/50 border-slate-100"}`,"data-testid":`rate-card-${c}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Pa,{checked:p&&!m,disabled:m,onCheckedChange:()=>r(c),className:"w-4 h-4 shrink-0","data-testid":`checkbox-factor-${c}`}),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-xs font-semibold ${m?"line-through text-slate-400":"text-slate-700"}`,children:bM[c]||c}),m&&u?.suppressionReason&&e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{children:e.jsx(tL,{className:"w-3 h-3 text-amber-500"})}),e.jsx(Wa,{side:"right",className:"max-w-[250px]",children:e.jsx("p",{className:"text-xs",children:u.suppressionReason})})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5",children:[e.jsx("span",{className:"text-sm font-bold text-slate-900",children:d.rate}),e.jsx("span",{className:"text-[10px] text-slate-400",children:d.unit})]}),e.jsx("div",{className:"text-[10px] text-slate-400 mt-0.5",children:d.source})]}),e.jsx(kt,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${fK(d.confidence)}`,children:d.confidence})]}),(()=>{const h=c==="gla"&&i?{band:i,unit:"sqft",tooltip:`Buyer utility analysis: comps within ±${Math.round(.5*i.stdDev).toLocaleString()} sqft of the mean (${i.mean.toLocaleString()} sqft) fall in the green band where buyers perceive homes as similar — GLA adjustment may not be needed.`}:c==="site"&&l?.lotSize?{band:l.lotSize,unit:"sqft",tooltip:`Buyer utility analysis: lots within ±${Math.round(.5*l.lotSize.stdDev).toLocaleStr
39ing()} sqft of the mean (${l.lotSize.mean.toLocaleString()} sqft) fall in the green band where size differences are not meaningful to buyers.`}:null;return h?e.jsxs("div",{className:"mt-0.5 ml-7 flex items-center gap-1.5","data-testid":`utility-band-indicator-${c}`,children:[e.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-50 border border-emerald-200",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-500"}),e.jsxs("span",{className:"text-[10px] text-emerald-700 font-medium",children:["±",Math.round(.5*h.band.stdDev).toLocaleString()," ",h.unit," utility band"]})]}),e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{children:e.jsx(on,{className:"w-3 h-3 text-slate-400"})}),e.jsx(Wa,{side:"right",className:"max-w-[280px]",children:e.jsx("p",{className:"text-xs",children:h.tooltip})})]})})]}):null})()]},c)})}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 flex items-start gap-2",children:[e.jsx(on,{className:"w-4 h-4 text-blue-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-blue-700",children:["Use the ",e.jsx("strong",{children:"Time"}),", ",e.jsx("strong",{children:"GLA"}),", ",e.jsx("strong",{children:"Cond/Qual"}),", and ",e.jsx("strong",{children:"Location"})," tabs to review each factor's analysis in detail. The rates shown here are the starting points."]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs("div",{className:"text-xs text-slate-400",children:[a.filter(c=>s.has(c)).length," of ",a.length," factors selected"]}),e.jsxs(De,{onClick:n,size:"sm",className:"gap-1.5",disabled:a.filter(c=>s.has(c)).length===0,"data-testid":"btn-step1-next",children:["Next: Per-Comp Grid",e.jsx(Zp,{className:"w-3.5 h-3.5"})]})]})]})}function AK({data:t,activeFactors:a,selectedFactors:s,overrides:r,editingCell:n,editInputValue:i,getEffectiveValue:l,hasOverride:c,startEditing:d,setEditInputValue:p,commitEdit:u,clearOverride:m,setOverride:h,computedFooter:f,onBack:v,onNext:S,glaBand:N,utilityBands:x}){return e.jsxs("div",{className:"space-y-3","data-testid":"advisor-step2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-slate-500 mb-1 block",children:"2. Per-Comp Adjustments"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Click any cell to edit. Each adjustment is calculated from subject-to-comp differences multiplied by the market rate."})]}),e.jsxs("div",{className:"flex items-center gap-4 text-[10px] text-slate-400 px-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-1.5 bg-blue-200 rounded-full"}),e.jsx("span",{children:"Confidence range"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-500"}),e.jsx("span",{children:"High"}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-amber-500 ml-1"}),e.jsx("span",{children:"Med"}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500 ml-1"}),e.jsx("span",{children:"Low"})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden","data-testid":"advisor-grid",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50 border-b",children:[e.jsx("th",{className:"text-left py-2 px-3 font-medium text-slate-600 sticky left-0 bg-slate-50 z-10 min-w-[140px]",children:"Factor"}),t.compSuggestions.map(y=>e.jsxs("th",{className:"text-center py-2 px-2 font-medium text-slate-600 min-w-[130px]",children:[e.jsx("div",{className:"truncate max-w-[120px] mx-auto",title:y.compAddress,children:y.compAddress.split(",")[0].replace(/^\d+\s/,"").slice(0,18)}),e.jsxs("div",{className:"text-[10px] text-slate-500 font-semibold",children:["$",y.salePrice.toLocaleString()]})]},y.compId))]})}),e.jsxs("tbody",{children:[a.filter(y=>s.has(y)).map(y=>{const j=t.compSuggestions.map(O=>O.adjustments.find(E=>E.factor===y)).find(O=>O),T=j?.suppressed??!1;return e.jsxs("tr",{className:`border-b last:border-b-0 ${T?"opacity-60":""}`,children:[e.jsx("td",{className:"py-1.5 px-3 sticky left-0 bg-white z-10 border-r",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`font-medium ${T?"line-through text-slate-400":"text-slate-700"}`,children:bM[y]||y}),j&&e.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${yM(j.rateConfidence)}`})]})}),t.compSuggestions.map(O=>{const E=O.adjustments.find(A=>A.factor===y);if(!E)return e.jsx("td",{className:"py-1.5 px-2 text-center text-slate-300",children:"—"},O.compId);const R=l(O.compId,y,E.suggestedAmount),G=c(O.compId,y),U=n?.compId===O.compId&&n?.factor===y,C=gK(E),F=G&&(R<E.rangeLow||R>E.rangeHigh);return e.jsx("td",{className:`py-1 px-1.5 text-center ${T?"":hK(R,O.salePrice)} ${!T&&!U?"cursor-pointer hover:ring-1 hover:ring-inset hover:ring-blue-300":""} transition-all`,"data-testid":`adj-cell-${y}-${O.compId}`,onClick:()=>{!T&&!U&&d(O.compId,y,R)},children:T?e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-400 line-through text-[11px]",children:km(E.suggestedAmount)}),e.jsx("div",{className:"text-[9px] text-slate-400 italic mt-0.5",children:C})]}):U?e.jsxs("div",{className:"space-y-1 p-0.5",onClick:A=>A.stopPropagation(),children:[e.jsx(ze,{type:"number",value:i,onChange:A=>p(A.target.value),onKeyDown:A=>{A.key==="Enter"&&u(),A.key==="Escape"&&(p(""),u())},onBlur:u,autoFocus:!0,className:"h-6 text-xs text-center font-mono px-1 w-full","data-testid":`edit-input-${y}-${O.compId}`}),E.rangeLow!==E.rangeHigh&&e.jsx(IN,{value:[parseInt(i,10)||0],min:E.rangeLow,max:E.rangeHigh,step:Math.max(1,Math.round((E.rangeHigh-E.rangeLow)/50)),onValueChange:([A])=>p(String(Math.round(A))),className:"w-full","data-testid":`slider-${y}-${O.compId}`}),e.jsxs("div",{className:"text-[9px] text-slate-400 font-mono",children:[km(E.rangeLow)," – ",km(E.rangeHigh)]})]}):e.jsxs("div",{className:"relative group",children:[e.jsxs("div",{className:`font-mono font-medium text-[11px] ${iI(R,O.salePrice)}`,children:[km(R),G&&e.jsx("button",{className:"inline-flex ml-0.5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:A=>{A.stopPropagation(),m(O.compId,y)},title:"Reset to suggested","data-testid":`undo-${y}-${O.compId}`,children:e.jsx(G5,{className:"w-2.5 h-2.5 text-slate-400 hover:text-slate-600"})})]}),G&&F&&e.jsx("div",{className:"text-[8px] text-amber-600 font-medium",children:"outside range"}),G&&!F&&e.jsx("div",{className:"text-[8px] text-indigo-500 font-medium",children:"edited"}),R!==0&&e.jsx(xK,{low:E.rangeLow,high:E.rangeHigh,value:R,confidence:E.rateConfidence}),e.jsx("div",{className:"text-[9px] text-slate-400 leading-tight mt-0.5",title:E.derivationNote,children:C}),(()=>{const A=y==="gla"?N:y==="site"?x?.lotSize:null;if(!A||E.compValue==null)return null;let M=typeof E.compValue=="number"?E.compValue:parseFloat(String(E.compValue).replace(/[^0-9.
39-]/g,""));if(isNaN(M))return null;y==="site"&&(M=Math.round(M*43560));const B=Yx(M,A),oe=SK(B);return B==="red"||!oe.label?null:e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("div",{className:`inline-flex items-center gap-0.5 px-1.5 py-0 rounded-full border text-[8px] font-medium mt-0.5 cursor-help ${oe.className}`,"data-testid":`${y}-band-badge-${O.compId}`,children:[e.jsx("div",{className:`w-1.5 h-1.5 rounded-full ${B==="green"?"bg-emerald-500":"bg-amber-500"}`}),B==="green"?"No adj. needed":"Sensitive"]})}),e.jsx(Wa,{side:"top",className:"max-w-[240px]",children:e.jsx("p",{className:"text-xs",children:oe.label})})]})})})()]})},O.compId)})]},y)}),e.jsxs("tr",{className:"border-t-2 border-slate-300 bg-slate-50 font-medium",children:[e.jsx("td",{className:"py-2 px-3 sticky left-0 bg-slate-50 z-10 border-r text-slate-700",children:"Net Adjustment"}),f.map(y=>e.jsx("td",{className:"py-2 px-2 text-center",children:e.jsx("span",{className:`font-mono text-[11px] ${iI(y.net,y.salePrice)}`,children:km(y.net)})},y.compId))]}),e.jsxs("tr",{className:"bg-slate-50 font-medium",children:[e.jsx("td",{className:"py-2 px-3 sticky left-0 bg-slate-50 z-10 border-r text-slate-700",children:"Gross Adjustment"}),f.map(y=>e.jsxs("td",{className:"py-2 px-2 text-center",children:[e.jsxs("div",{className:`font-mono text-[11px] ${y.grossPct>25?"text-red-700":y.grossPct>15?"text-amber-700":"text-slate-700"}`,children:["$",y.gross.toLocaleString()]}),e.jsxs("div",{className:`text-[10px] ${y.grossPct>25?"text-red-500":y.grossPct>15?"text-amber-500":"text-slate-400"}`,children:[y.grossPct.toFixed(1),"%"]})]},y.compId))]}),e.jsxs("tr",{className:"bg-blue-50/50 font-semibold",children:[e.jsx("td",{className:"py-2 px-3 sticky left-0 bg-blue-50/50 z-10 border-r text-blue-800",children:"Adjusted Price"}),f.map(y=>e.jsx("td",{className:"py-2 px-2 text-center",children:e.jsxs("span",{className:"font-mono text-[11px] text-blue-800",children:["$",y.adjustedPrice.toLocaleString()]})},y.compId))]})]})]})})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs(De,{variant:"outline",size:"sm",onClick:v,className:"gap-1.5 text-xs","data-testid":"btn-step2-back",children:[e.jsx(yN,{className:"w-3.5 h-3.5"}),"Back"]}),e.jsxs(De,{onClick:S,size:"sm",className:"gap-1.5","data-testid":"btn-step2-next",children:["Next: Apply",e.jsx(Zp,{className:"w-3.5 h-3.5"})]})]})]})}function jK({data:t,computedFooter:a,medianAdjustedPrice:s,totalOverrides:r,onResetOverrides:n,onApply:i,onBack:l}){const c=a.length>0?{low:Math.min(...a.map(d=>d.adjustedPrice)),high:Math.max(...a.map(d=>d.adjustedPrice))}:{low:0,high:0};return e.jsxs("div",{className:"space-y-4","data-testid":"advisor-step3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium text-slate-500 mb-1 block",children:"3. Apply to Grid"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Review your adjusted prices below, then apply them to the comp grid."})]}),e.jsx(ja,{className:"border-blue-200 bg-blue-50/30",children:e.jsx(Ta,{className:"py-4",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Median Adjusted Price"}),e.jsxs("div",{className:"text-3xl font-bold text-blue-800","data-testid":"median-adjusted-price",children:["$",s.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-slate-400 mt-1",children:["Range: $",c.low.toLocaleString()," – $",c.high.toLocaleString()]})]})})}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2",children:a.map(d=>e.jsxs("div",{className:"p-3 rounded-lg border bg-white","data-testid":`apply-comp-${d.compId}`,children:[e.jsx("div",{className:"text-xs text-slate-500 truncate",title:d.compAddress||d.compId,children:(d.compAddress||d.compId||"Comp").split(",")[0]}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-slate-400",children:"Sale Price"}),e.jsxs("div",{className:"text-xs font-mono text-slate-600",children:["$",d.salePrice.toLocaleStr
39ing()]})]}),e.jsx(Zp,{className:"w-3 h-3 text-slate-300"}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[10px] text-slate-400",children:"Adjusted"}),e.jsxs("div",{className:"text-xs font-mono font-semibold text-blue-700",children:["$",d.adjustedPrice.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5 text-[10px]",children:[e.jsxs("span",{className:iI(d.net,d.salePrice),children:["Net: ",km(d.net)]}),e.jsxs("span",{className:`${d.grossPct>25?"text-red-500":d.grossPct>15?"text-amber-500":"text-slate-400"}`,children:["Gross: ",d.grossPct.toFixed(1),"%"]})]})]},d.compId))}),r>0&&e.jsxs("div",{className:"flex items-center justify-between bg-indigo-50 border border-indigo-200 rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-indigo-700",children:[e.jsx(SI,{className:"w-3.5 h-3.5"}),e.jsxs("span",{children:[r," manual edit",r!==1?"s":""," applied"]})]}),e.jsx("button",{className:"text-xs text-indigo-600 hover:text-indigo-800 underline",onClick:n,"data-testid":"btn-reset-all-overrides",children:"Reset all"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 flex items-start gap-2",children:[e.jsx(on,{className:"w-4 h-4 text-blue-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-blue-700",children:["Clicking ",e.jsx("strong",{children:"Apply to Grid"})," will populate the adjustment cells in your comp grid with these values. You can still manually edit individual cells in the grid afterwards."]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs(De,{variant:"outline",size:"sm",onClick:l,className:"gap-1.5 text-xs","data-testid":"btn-step3-back",children:[e.jsx(yN,{className:"w-3.5 h-3.5"}),"Back"]}),e.jsxs(De,{size:"lg",onClick:i,className:"gap-2 bg-blue-600 hover:bg-blue-700 px-8","data-testid":"btn-apply-adjustments",children:[e.jsx(Hr,{className:"w-4 h-4"}),"Apply to Grid"]})]})]})}const SM={gla:{subjectKey:"gla",compKey:"gla",getSubjectVal:t=>t?.gla||0},lotSize:{subjectKey:"lotSizeAcres",compKey:"lotSize",getSubjectVal:t=>(t?.lotSizeAcres||0)*43560},age:{subjectKey:"yearBuilt",compKey:"age",getSubjectVal:t=>t?.yearBuilt?new Date().getFullYear()-t.yearBuilt:0},garageSpaces:{subjectKey:"garageSpaces",compKey:"garageSpaces",getSubjectVal:t=>t?.garageSpaces||0},finBasementSf:{subjectKey:"basementFinishedSqft",compKey:"finBasementSf",getSubjectVal:t=>t?.basementFinishedSqft||t?.basementSqft||0},bathEquiv:{subjectKey:"bathrooms",compKey:"bathEquiv",getSubjectVal:t=>t?.bathrooms||0},timeIndex:{subjectKey:"",compKey:"timeIndex",getSubjectVal:()=>0},condGood:{subjectKey:"condition",compKey:"condGood",getSubjectVal:t=>t?.condition?.toUpperCase()==="C3"?1:0},condExcellent:{subjectKey:"condition",compKey:"condExcellent",getSubjectVal:t=>{const a=t?.condition?.toUpperCase();return a==="C1"||a==="C2"?1:0}}};function TK({open:t,onClose:a,assignmentId:s,marketLocked:r,subMarketLocked:n,verifiedSubject:i,selectedComps:l,onApplyAdjustments:c,advisorRateDetails:d,onStateChange:p,initialState:u}){const[m,h]=o.useState(0),[f,v]=o.useState(r?"market":"submarket"),[S,N]=o.useState(!1),[x,y]=o.useState(u?.analysis||{}),[b,j]=o.useState(()=>u?.excludedIds?{market:new Set(u.excludedIds.market||[]),submarket:new Set(u.excludedIds.submarket||[])}:{market:new Set,submarket:new Set}),[T,O]=o.useState(["gla","lotSize","age","garageSpaces","finBasementSf","bathEquiv","timeIndex","condGood","condExcellent"]),[E,R]=o.useState(u?.reconciledRatesMap||{}),[G,U]=o.useState(null),[C,F]=o.useState(null),[A,M]=o.useState([]),B=x[f]||null,oe=b[f]||new Set,ae=E[f]||[],D=B?.data?.usableSales??0,_=D>=90?"text-emerald-600":D>=30?"text-amber-600":"text-red-600",$=D>=90?"bg-emerald-50":D>=30?"bg-amber-50":"bg-red-50",z=o.useCallback(fe=>{R(ue=>({...ue,[f]:typeof fe=="function"?fe(ue[f]||[]):fe}))},[f]),V=o.useCallback(async()=>{N(!0),F(null);try{const fe=await fetch("/api/regression/analyze",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({assignmentId:s,pool:f,excludedIds:Array.from(oe),enabledVars:T})});if(!fe.ok){const be=await fe.json().catch(()=>null);F(be?.error||`Server error: ${fe.status}`);return}const ue=await fe.json();if(ue.success||F(ue.warning||"Analysis returned no results"),y(be=>({...be,[f]:ue})),ue.data?.outliers?.length&&!oe.size){const be=new Set(ue.data.outliers.filter(H=>H.isExcluded).map(H=>H.id));be.size>0&&j(H=>({...H,[f]:be}))}if(ue.regression){const be=ue.regression.coefficients.filter(H=>!["timeIndex","condGood","condExcellent"].includes(H.variable)).map(H=>({variable:H.variable,label:H.label,unit:H.unit,regressionRate:H.coefficient,regressionConfidence:H.significance==="primary"?"strong":H.significance==="secondary"?"moderate":"weak",pValue:H.pValue,recommendedRate:Math.round(H.coefficient*100)/100,apply:H.significance!=="none",warning:H.warning}));z(be)}}catch(fe){console.error("Regression analysis failed:",fe),F(fe instanceof Error?fe.message:"Network error")}finally{N(!1)}},[s,f,oe,T,z]);o.useEffect(()=>{if(p&&(Object.keys(x).length>0||Object.keys(E).length>0)){const fe={};for(const[ue,be]of Object.entries(b))fe[ue]=Array.from(be);p({analysis:x,reconciledRatesMap:E,excludedIds:fe})}},[x,E,b,p]);const le=o.useMemo(()=>l?.length?l.map(fe=>fe.id||fe.snapshotId).sort().join(","):"",[l]);o.useEffect(()=>{if(!t||!B||!l?.length){M([]);return}(async()=>{try{const ue=await fetch("/api/regression/rank-comps",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({assignmentId:s,pool:f,excludedIds:Array.from(oe),enabledVars:T})});if(!ue.ok)return;const be=await ue.json(),H=be.rankedComps||be.rankings;if(H){const ye=new Set(l.flatMap(ge=>
39[ge.id,ge.snapshotId,ge.mlsNumber].filter(Boolean))),de=H.filter(ge=>ye.has(ge.id)).map(ge=>({id:ge.id,address:ge.address,salePrice:ge.salePrice,predictedPrice:ge.predictedPrice,residual:ge.residual,gla:ge.gla,similarityScore:ge.similarityScore||0}));M(de)}}catch{}})()},[t,B,s,f,le,oe,T]);const W=o.useCallback(fe=>{j(ue=>{const be=new Set(ue[f]||[]);return be.has(fe)?be.delete(fe):be.add(fe),{...ue,[f]:be}})},[f]),me=o.useCallback(fe=>{O(ue=>ue.includes(fe)?ue.filter(be=>be!==fe):[...ue,fe])},[]),Z=o.useCallback((fe,ue)=>{navigator.clipboard.writeText(fe),U(ue),setTimeout(()=>U(null),2e3)},[]),pe=o.useMemo(()=>{if(!l?.length||!ae.length)return[];const fe=ae.filter(ue=>ue.apply);return l.map(ue=>{const be={};let H=0;for(const de of fe){const ge=SM[de.variable];if(!ge)continue;const Be=ge.getSubjectVal(i);let He=0;if(de.variable==="gla")He=ue.btNormalizedGla||ue.sqft||0;else if(de.variable==="lotSize")He=ue.lotSqftPR||ue.lotSqft||0;else if(de.variable==="age"){const We=ue.yearBuiltPR||ue.yearBuilt;He=We?new Date().getFullYear()-We:0}else de.variable==="garageSpaces"?He=ue.garageSpaces||0:de.variable==="finBasementSf"?He=ue.basementFinishedSf||ue.basementSqft||0:de.variable==="bathEquiv"&&(He=ue.baths||0);if(Be===0&&He===0)continue;const Ie=Be-He,ce=Math.round(Ie*de.recommendedRate),Pe=de.unit.replace("/","per ");be[de.variable]={diff:Ie,rate:de.recommendedRate,amount:ce,derivation:`Subject ${Be.toLocaleString()} − Comp ${He.toLocaleString()} = ${Ie>=0?"+":""}${Ie.toLocaleString()} × $${de.recommendedRate.toFixed(2)}${Pe} = ${ce>=0?"+":""}$${Math.abs(ce).toLocaleString()}`},H+=ce}const ye=ue.price||0;return{compId:ue.id||ue.snapshotId,address:ue.address||"",salePrice:ye,adjustments:be,totalAdjustment:H,adjustedPrice:ye+H}})},[l,ae,i]),se=[{label:"Data Review",icon:H5},{label:"Regression Results",icon:sL},{label:"Adjustment Rates",icon:W5}
39,{label:"Apply to Grid",icon:Bx}];return e.jsx(xi,{open:t,onOpenChange:fe=>!fe&&a(),children:e.jsxs(bi,{className:"max-w-[95vw] w-[1400px] max-h-[92vh] h-[92vh] p-0 flex flex-col overflow-hidden","data-testid":"adjustment-derivation-panel",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b bg-gradient-to-r from-slate-50 to-white","data-testid":"derivation-panel-header",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Pl,{className:"w-5 h-5 text-[#1B2A4A]"}),e.jsx(si,{className:"text-base font-semibold text-[#1B2A4A]",children:"Adjustment Derivation Panel"}),e.jsx("span",{className:"text-xs text-slate-400 font-normal",children:"Market-Derived Regression Analysis"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-white p-0.5","data-testid":"pool-toggle",children:[e.jsx("button",{onClick:()=>v("market"),disabled:!r,className:Q("px-3 py-1 text-xs font-medium rounded transition-colors",f==="market"?"bg-[#1B2A4A] text-white":"text-slate-600 hover:bg-slate-100",!r&&"opacity-40 cursor-not-allowed"),"data-testid":"pool-toggle-market",children:"Market"}),e.jsx("button",{onClick:()=>v("submarket"),disabled:!n,className:Q("px-3 py-1 text-xs font-medium rounded transition-colors",f==="submarket"?"bg-[#1B2A4A] text-white":"text-slate-600 hover:bg-slate-100",!n&&"opacity-40 cursor-not-allowed"),"data-testid":"pool-toggle-submarket",children:"Submarket"})]}),B&&e.jsxs("div",{className:Q("flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium",$),"data-testid":"sample-size-badge",children:[e.jsxs("span",{className:_,children:[D," sales"]}),D<30&&e.jsx(Ns,{className:"w-3.5 h-3.5 text-red-500"})]}),e.jsxs(De,{size:"sm",onClick:V,disabled:S,className:"h-7 text-xs gap-1 px-3 bg-[#1B2A4A] hover:bg-[#2a3d66]","data-testid":"btn-run-regression",children:[S?e.jsx(za,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(aL,{className:"w-3.5 h-3.5"}),S?"Analyzing...":B?"Re-Run":"Run Analysis"]})]})]}),e.jsx("div",{className:"flex items-center gap-1 px-5 py-2 border-b bg-white",children:se.map((fe,ue)=>{const be=fe.icon,H=m===ue,ye=ue>0&&!B?.regression;return e.jsxs("button",{onClick:()=>!ye&&h(ue),disabled:ye,className:Q("flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md transition-colors",H?"bg-[#1B2A4A] text-white":"text-slate-600 hover:bg-slate-100",ye&&"opacity-40 cursor-not-allowed"),"data-testid":`tab-${fe.label.toLowerCase().replace(/\s+/g,"-")}`,children:[e.jsx(be,{className:"w-3.5 h-3.5"}),fe.label]},fe.label)})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-5",children:[!B&&!S&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center","data-testid":"empty-state",children:[e.jsx(Pl,{className:"w-12 h-12 text-slate-300 mb-3"}),e.jsx("p",{className:"text-sm text-slate-600 font-medium mb-1",children:"Ready to Derive Adjustments"}),e.jsx("p",{className:"text-xs text-slate-400 max-w-md",children:'Select your pool (Market or Submarket) and click "Run Analysis" to perform regression analysis on the locked sales data.'})]}),S&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-full","data-testid":"loading-state",children:[e.jsx(za,{className:"w-8 h-8 animate-spin text-[#1B2A4A] mb-3"}),e.jsx("p",{className:"text-sm text-slate-600",children:"Running OLS regression analysis..."}),e.jsxs("p",{className:"text-xs text-slate-400 mt-1",children:["Analyzing ",f," pool data"]})]}),C&&!S&&e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 mb-4 bg-red-50 border border-red-200 rounded-md text-sm text-red-800","data-testid":"error-banner",children:[e.jsx(Ns,{className:"w-4 h-4 text-red-500 shrink-0"}),e.jsx("div",{className:"flex-1",children:e.jsx("span",{children:C})}),e.jsxs(De,{size:"sm",variant:"outline",className:"shrink-0 h-7 text-xs border-red-300 text-red-700 hover:bg-red-100",onClick:V,"data-testid":"btn-retry-regression",children:[e.jsx(Kl,{className:"w-3 h-3 mr-1"})," Retry"]})]}),B&&!B.regression&&B.warning&&!S&&e.jsxs("div",{className:"flex items-start gap-3 px-4 py-4 mb-4 bg-amber-50 border border-amber-200 rounded-md","data-testid":"warning-banner",children:[e.jsx(Ns,{className:"w-5 h-5 text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-amber-800 mb-1",children:"Regression Could Not Run"}),e.jsx("p",{className:"text-xs text-amber-700",children:B.warning}),e.jsx("p",{className:"text-xs text-amber-600 mt-2",children:(B.data?.usableSales??0)<15?"Try switching to the market pool for a larger dataset, or expand your search radius before locking.":"Try disabling some variables (e.g., Condition or Basement) and re-run the analysis."})]}),e.jsxs(De,{size:"sm",variant:"outline",className:"shrink-0 h-7 text-xs border-amber-300 text-amber-700 hover:bg-amber-100",onClick:V,"data-testid":"btn-rerun-warning",children:[e.jsx(Kl,{className:"w-3 h-3 mr-1"})," Re-Run"]})]}),B&&!S&&m===0&&e.jsx(IK,{analysis:B,excludedIds:oe,onToggleExclude:W,onRunAnalysis:V}),B?.regression&&!S&&m===1&&e.jsx(CK,{analysis:B,pool:f,otherPoolAnalysis:x[f==="market"?"submarket":"market"]||null,enabledVars:T,onToggleVar:me,onCopy:Z,copiedField:G,verifiedSubject:i,onEditNarrative:(fe,ue)=>{y(be=>{const H=be[f];return H?.narratives?{...be,[f]:{...H,narratives:{...H.narratives,[fe]:ue}}}:be})}}),B?.regression&&!S&&m===2&&e.jsx(RK,{rates:ae,onUpdateRate:(fe,ue)=>{z(be=>{const H=[...be];return H[fe]={...H[fe],recommendedRate:ue},H})},onToggleApply:fe=>{z(ue=>{const be=[...ue];return be[fe]={...be[fe],apply:!be[fe].apply},be})},advisorRates:d}),B?.regression&&!S&&m===3&&e.jsx(EK,{compAdjustments:pe,reconciledRates:ae.filter(fe=>fe.apply),onApply:()=>c?.(pe),selectedComps:l,compRankings:A})]})]})})}
39function IK({analysis:t,excludedIds:a,onToggleExclude:s,onRunAnalysis:r}){const n=t.data.allSales||[],i=new Set(t.data.outliers.map(T=>T.id)),l=new Map(t.data.outliers.map(T=>[T.id,T.reason])),[c,d]=o.useState("salePrice"),[p,u]=o.useState("desc"),[m,h]=o.useState(""),f=T=>{c===T?u(O=>O==="asc"?"desc":"asc"):(d(T),u("desc"))},v=o.useMemo(()=>{let T=[...n];if(m){const O=m.toLowerCase();T=T.filter(E=>E.address.toLowerCase().includes(O))}return T.sort((O,E)=>{const R=O[c]??0,G=E[c]??0;return p==="asc"?R>G?1:-1:R<G?1:-1}),T},[n,c,p,m]),S=n.filter(T=>!a.has(T.id)).length,N=n.filter(T=>!a.has(T.id)).map(T=>T.salePrice),x=N.length?N.reduce((T,O)=>T+O,0)/N.length:0,y=N.length?[...N].sort((T,O)=>T-O)[Math.floor(N.length/2)]:0,b=(()=>{const T=n.filter(O=>!a.has(O.id)).map(O=>O.gla);return T.length?T.reduce((O,E)=>O+E,0)/T.length:0})(),j=[{key:"address",label:"Address",w:"w-48"},{key:"salePrice",label:"Sale Price",w:"w-24"},{key:"gla",label:"GLA",w:"w-16"},{key:"lotSize",label:"Lot SF",w:"w-20"},{key:"age",label:"Age",w:"w-12"},{key:"garageSpaces",label:"Gar",w:"w-10"},{key:"finBasementSf",label:"Fin Bsmt",w:"w-16"},{key:"bathEquiv",label:"Bath",w:"w-12"},{key:"dom",label:"DOM",w:"w-12"},{key:"closeDate",label:"Close Date",w:"w-20"}];return e.jsxs("div",{className:"space-y-4","data-testid":"tab-data-review-content",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-white border rounded-md px-3 py-1.5","data-testid":"data-review-summary",children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Using"}),e.jsx("span",{className:"text-sm font-semibold text-[#1B2A4A]",children:S}),e.jsxs("span",{className:"text-xs text-slate-500",children:["of ",n.length," sales"]}),n.length-S>0&&e.jsxs("span",{className:"text-xs text-amber-600",children:["(",n.length-S," excluded)"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-slate-500",children:[e.jsxs("span",{children:["Mean: ",e.jsxs("span",{className:"font-mono font-medium text-slate-700",children:["$",Math.round(x).toLocaleString()]})]}),e.jsxs("span",{children:["Median: ",e.jsxs("span",{className:"font-mono font-medium text-slate-700",children:["$",Math.round(y).toLocaleString()]})]}),e.jsxs("span",{children:["Avg GLA: ",e.jsxs("span",{className:"font-mono font-medium text-slate-700",children:[Math.round(b).toLocaleString()," sf"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Eu,{className:"w-3.5 h-3.5 absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(ze,{placeholder:"Search address...",value:m,onChange:T=>h(T.target.value),className:"h-7 text-xs pl-8 w-48","data-testid":"search-sales"})]}),e.jsxs(De,{size:"sm",variant:"outline",onClick:r,className:"h-7 text-xs gap-1","data-testid":"btn-rerun-data-review",children:[e.jsx(Kl,{className:"w-3 h-3"}),"Re-Run with Changes"]})]})]}),t.data.outliers.length>0&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-amber-50 border border-amber-200 rounded-md text-xs text-amber-800","data-testid":"outlier-banner",children:[e.jsx(Ns,{className:"w-4 h-4 text-amber-500 shrink-0"}),e.jsxs("span",{children:[t.data.outliers.length," price outlier",t.data.outliers.length>1?"s":""," detected via IQR method — auto-excluded. Toggle to re-include."]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden bg-white",children:e.jsx("div",{className:"max-h-[55vh] overflow-auto",children:e.jsxs("table",{className:"w-full text-xs","data-testid":"sales-table",children:[e.jsx("thead",{className:"sticky top-0 z-10 bg-slate-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"w-8 px-2 py-2",children:e.jsx("span",{className:"sr-only",children:"Include"})}),j.map(T=>e.jsx("th",{className:Q("px-2 py-2 text-left font-medium text-slate-600 cursor-pointer hover:text-slate-900 select-none",T.w),onClick:()=>f(T.key),children:e.jsxs("span",{className:"flex items-center gap-1",children:[T.label,c===T.key&&e.jsx(hN,{className:"w-3 h-3"})]})},T.key))]})}),e.jsx("tbody",{children:v.map(T=>{const O=i.has(T.id),E=a.has(T.id);return e.jsxs("tr",{className:Q("border-b last:border-b-0 transition-colors",E&&O&&"bg-amber-50/60",E&&!O&&"bg-red-50/40 opacity-60",!E&&"hover:bg-slate-50"),"data-testid":`sale-row-${T.id}`,children:[e.jsx("td",{className:"px-2 py-1.5 text-center",children:e.jsx(Pa,{checked:!E,onCheckedChange:()=>s(T.id),className:"h-3.5 w-3.5","data-testid":`checkbox-${T.id}`})}),e.jsx("td",{className:"px-2 py-1.5 font-medium text-slate-800 truncate max-w-[200px]",children:e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-1",children:[T.address,O&&e.jsx(Ns,{className:"w-3 h-3 text-amber-500 shrink-0"})]})}),O&&e.jsx(Wa,{className:"text-xs max-w-xs",children:l.get(T.id)})]})})}),e.jsxs("td",{className:"px-2 py-1.5 font-mono text-right",children:["$",T.salePrice.toLocaleStr
39ing()]}),e.jsx("td",{className:"px-2 py-1.5 font-mono text-right",children:T.gla.toLocaleString()}),e.jsx("td",{className:"px-2 py-1.5 font-mono text-right",children:T.lotSize>0?T.lotSize.toLocaleString():"—"}),e.jsx("td",{className:"px-2 py-1.5 font-mono text-right",children:T.age}),e.jsx("td",{className:"px-2 py-1.5 font-mono text-right",children:T.garageSpaces}),e.jsx("td",{className:"px-2 py-1.5 font-mono text-right",children:T.finBasementSf>0?T.finBasementSf.toLocaleString():"—"}),e.jsx("td",{className:"px-2 py-1.5 font-mono text-right",children:T.bathEquiv.toFixed(1)}),e.jsx("td",{className:"px-2 py-1.5 font-mono text-right",children:T.dom??"—"}),e.jsx("td",{className:"px-2 py-1.5 text-slate-600",children:T.closeDate?new Date(T.closeDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"2-digit"}):"—"})]},T.id)})})]})})}),t.data.missingData.length>0&&e.jsxs(CN,{children:[e.jsxs(RN,{className:"flex items-center gap-2 text-xs text-slate-500 hover:text-slate-700","data-testid":"toggle-missing-data",children:[e.jsx(fo,{className:"w-3 h-3"}),t.data.missingData.length," properties excluded due to missing data"]}),e.jsx(EN,{className:"mt-2 pl-5 space-y-1",children:t.data.missingData.map(T=>e.jsxs("div",{className:"text-xs text-slate-400",children:[e.jsx("span",{className:"font-medium text-slate-500",children:T.address})," — ",T.reason]},T.id))})]})]})}function CK({analysis:t,pool:a,otherPoolAnalysis:s,enabledVars:r,onToggleVar:n,onCopy:i,copiedField:l,verifiedSubject:c,onEditNarrative:d}){const p=t.regression,u=t.marketTrend,m=t.narratives,h=[{name:"gla",label:"GLA"},{name:"lotSize",label:"Lot Size"},{name:"age",label:"Age"},{name:"garageSpaces",label:"Garage"},{name:"finBasementSf",label:"Fin Bsmt"},{name:"bathEquiv",label:"Baths"},{name:"timeIndex",label:"Time"},{name:"condGood",label:"Cond Good"},{name:"condExcellent",label:"Cond Excellent"}],f=o.useMemo(()=>{if(!c)return null;let v=p.intercept.coefficient;const S=[];for(const N of p.coefficients){const x=SM[N.variable],y=x?x.getSubjectVal(c):0,b=N.coefficient*y;v+=b,S.push({label:N.label,value:y,contribution:b})}return{predicted:v,breakdown:S}},[p,c]);return e.jsxs("div",{className:"space-y-5","data-testid":"tab-regression-results-content",children:[e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsx(t0,{label:"Observations",value:p.diagnostics.observations.toString(),tooltip:"The number of comparable sales used in this analysis. More sales generally means more reliable results."}),e.jsx(t0,{label:"R²",value:(p.diagnostics.rSquared*100).toFixed(1)+"%",subtitle:`Model explains ${(p.diagnostics.rSquared*100).toFixed(0)}% of price variation`,tooltip:"How well the model explains price differences. 76% means 76 out of 100 price differences are explained by these property features. Higher is better — above 70% is good."}),e.jsx(t0,{label:"Adjusted R²",value:(p.diagnostics.adjustedRSquared*100).toFixed(1)+"%",tooltip:"Same as R², but accounts for the number of variables used. If this drops far below R², you may have unnecessary variables included."}),e.jsx(t0,{label:"RMSE",value:"$"+Math.round(p.diagnostics.rmse).toLocaleString(),subtitle:"Typical prediction error",tooltip:"The typical dollar amount the model's predictions are off by. Lower means more accurate. Think of it as the model's average miss."}),e.jsx(t0,{label:"Max VIF",value:p.diagnostics.maxVif.toFixed(1),color:p.diagnostics.maxVif>10?"red":p.diagnostics.maxVif>5?"amber":"emerald",subtitle:p.diagnostics.maxVif>10?"High multicollinearity":"Acceptable",tooltip:"Checks if variables overlap too much (measure the same thing). Below 5 is good. Above 10 means two variables are redundant — consider removing one."})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap mb-2",children:[e.jsx("span",{className:"text-xs text-slate-500 font-medium",children:"Variables:"}),h.map(v=>e.jsx("button",{onClick:()=>n(v.name),className:Q("px-2 py-0.5 text-[10px] font-medium rounded border transition-colors",r.includes(v.name)?"bg-[#1B2A4A] text-white border-[#1B2A4A]":"bg-white text-slate-400 border-slate-200 hover:border-slate-300"),"data-testid":`var-toggle-${v.name}`,children:v.label},v.name)),e.jsx("span",{className:"text-[10px] text-slate-400 ml-1",children:"Toggle to re-run"})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden bg-white",children:e.jsxs("table",{className:"w-full text-xs","data-testid":"coefficient-table",children:[e.jsx("thead",{className:"bg-slate-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center gap-1",children:["Variable ",e.jsx(Ko,{text:"The property feature being analyzed for its effect on price."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["Coefficient ",e.jsx(Ko,{text:"How much the price changes for each unit of this feature. For example, $171/sqft means each additional square foot adds about $171."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["Std Error ",e.jsx(Ko,{text:"How uncertain the estimate is. Smaller numbers mean more confidence in the result."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["t-Stat ",e.jsx(Ko,{text:"Signal strength. Values farther from zero (above 2 or below -2) mean stronger evidence this feature matters."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["p-Value ",e.jsx(Ko,{text:"Probability this result happened by chance. Green (below 0.05) = strong evidence. Amber (below 0.20) = some evidence. Gray = not enough evidence."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["95% CI ",e.jsx(Ko,{text:"The range where the true value likely falls. If it doesn't cross zero, the feature reliably affects price."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["VIF ",e.jsx(Ko,{text:"Checks overlap with other variables. Below 5 is fine. Above 10 means it's redundant with another variable."})]})}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center gap-1",children:["Interpretation ",e.jsx(Ko,{text:"Plain-English summary of what this variable's numbers mean for property value."})]})})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b bg-slate-50/50",children:[e.jsx("td",{className:"px-3 py-1.5 font-medium text-slate-500",children:"(Intercept)"}),e.jsxs("td",{className:"px-3 py-1.5 font-mono text-right",children:["$",Math.round(p.intercept.coefficient).toLocaleStr
39ing()]}),e.jsxs("td",{className:"px-3 py-1.5 font-mono text-right text-slate-400",children:["$",Math.round(p.intercept.stdError).toLocaleString()]}),e.jsx("td",{className:"px-3 py-1.5 font-mono text-right text-slate-400",children:p.intercept.tStatistic.toFixed(2)}),e.jsx("td",{className:"px-3 py-1.5 font-mono text-right text-slate-400",children:p.intercept.pValue.toFixed(4)}),e.jsx("td",{className:"px-3 py-1.5 font-mono text-right text-slate-400",children:"—"}),e.jsx("td",{className:"px-3 py-1.5 font-mono text-right text-slate-400",children:"—"}),e.jsx("td",{className:"px-3 py-1.5 text-slate-400",children:"Base price level"})]}),p.coefficients.map(v=>e.jsxs("tr",{className:Q("border-b last:border-b-0",v.significance==="primary"&&"bg-emerald-50/40",v.significance==="secondary"&&"bg-amber-50/40"),children:[e.jsxs("td",{className:"px-3 py-1.5 font-medium text-slate-800 flex items-center gap-1.5",children:[v.label,e.jsx(wK,{significance:v.significance})]}),e.jsxs("td",{className:"px-3 py-1.5 font-mono text-right font-medium",children:["$",v.coefficient.toFixed(2),v.unit]}),e.jsx("td",{className:"px-3 py-1.5 font-mono text-right text-slate-500",children:v.stdError.toFixed(2)}),e.jsx("td",{className:"px-3 py-1.5 font-mono text-right text-slate-500",children:v.tStatistic.toFixed(2)}),e.jsx("td",{className:Q("px-3 py-1.5 font-mono text-right font-medium",v.pValue<.05?"text-emerald-700":v.pValue<.2?"text-amber-700":"text-slate-400"),children:v.pValue.toFixed(4)}),e.jsxs("td",{className:"px-3 py-1.5 font-mono text-right text-slate-500 text-[10px]",children:["[",v.ciLower.toFixed(1),", ",v.ciUpper.toFixed(1),"]"]}),e.jsx("td",{className:Q("px-3 py-1.5 font-mono text-right",v.vif>10?"text-red-600 font-medium":v.vif>5?"text-amber-600":"text-slate-500"),children:v.vif.toFixed(1)}),e.jsx("td",{className:"px-3 py-1.5 text-slate-600",children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{children:v.interpretation}),v.warning&&e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(Ns,{className:"w-3 h-3 text-amber-500 shrink-0 cursor-help"})}),e.jsx(Wa,{side:"left",className:"max-w-xs text-xs",children:e.jsx("p",{children:v.warning})})]})})]})})]},v.variable))]})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(ja,{className:"border-emerald-200 bg-emerald-50/30",children:e.jsxs(Ta,{className:"p-3",children:[e.jsxs("h4",{className:"text-xs font-semibold text-emerald-800 mb-1.5 flex items-center gap-1",children:[e.jsx(kr,{className:"w-3.5 h-3.5"})," Primary Drivers (p < 0.05) ",e.jsx(Ko,{text:"Strong statistical evidence these features affect price. Safe to use as adjustment factors."})]}),p.drivers.primary.length>0?p.drivers.primary.map(v=>e.jsxs("p",{className:"text-xs text-emerald-700",children:["• ",v]},v)):e.jsx("p",{className:"text-xs text-emerald-600 italic",children:"None identified"})]})}),e.jsx(ja,{className:"border-amber-200 bg-amber-50/30",children:e.jsxs(Ta,{className:"p-3",children:[e.jsxs("h4",{className:"text-xs font-semibold text-amber-800 mb-1.5 flex items-center gap-1",children:[e.jsx(Ns,{className:"w-3.5 h-3.5"})," Secondary Drivers (p < 0.20) ",e.jsx(Ko,{text:"Some evidence of affecting price, but not as strong. Use with caution as supporting evidence."})]}),p.drivers.secondary.length>0?p.drivers.secondary.map(v=>e.jsxs("p",{className:"text-xs text-amber-700",children:["• ",v]},v)):e.jsx("p",{className:"text-xs text-amber-600 italic",children:"None identified"})]})}),e.jsx(ja,{className:"border-slate-200",children:e.jsxs(Ta,{className:"p-3",children:[e.jsxs("h4",{className:"text-xs font-semibold text-slate-600 mb-1.5 flex items-center gap-1",children:[e.jsx(nf,{className:"w-3.5 h-3.5"})," No Reliable Impact ",e.jsx(Ko,{text:"Not enough evidence these features affect price in this dataset. Doesn't mean they don't matter — just can't be proven here."})]}),p.drivers.noImpact.length>0?p.drivers.noImpact.map(v=>e.jsxs("p",{className:"text-xs text-slate-500",children:["• ",v]},v)):e.jsx("p",{className:"text-xs text-slate-400 italic",children:"All variables contribute"})]})})]}),f&&e.jsx(ja,{className:"border-[#1B2A4A]/20 bg-[#F5F0E8]/30",children:e.jsxs(Ta,{className:"p-3","data-testid":"predicted-value-card",children:[e.jsxs("h4",{className:"text-xs font-semibold text-[#1B2A4A] mb
39-1 flex items-center gap-1",children:["Predicted Subject Value (Regression) ",e.jsx(Ko,{text:"What the regression model estimates the subject is worth based on its features. Use as one piece of supporting evidence, not a final value opinion."})]}),e.jsxs("p",{className:"text-xl font-bold text-[#1B2A4A] font-mono",children:["$",Math.round(f.predicted).toLocaleString()]}),e.jsx("p",{className:"text-[10px] text-slate-500 mt-1",children:"Based on subject characteristics applied to the regression equation. This is supportive analytical evidence, not a final value opinion."})]})}),s?.regression&&e.jsx(ja,{className:"border-indigo-200 bg-indigo-50/20",children:e.jsxs(Ta,{className:"p-3","data-testid":"pool-comparison",children:[e.jsx("h4",{className:"text-xs font-semibold text-indigo-800 mb-2",children:"Market vs Submarket Comparison"}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[{label:"Market",r:a==="market"?p:s.regression,n:a==="market"?t.data.usableSales:s.data.usableSales},{label:"Submarket",r:a==="submarket"?p:s.regression,n:a==="submarket"?t.data.usableSales:s.data.usableSales}].map(({label:v,r:S,n:N})=>e.jsxs("div",{children:[e.jsxs("p",{className:"text-[10px] font-medium text-indigo-600 mb-1",children:[v," (",N," sales)"]}),S.coefficients.filter(x=>x.significance!=="none").map(x=>e.jsxs("p",{className:"text-[10px] text-indigo-700 font-mono",children:[x.label,": $",x.coefficient.toFixed(2),x.unit]},x.variable))]},v))})]})}),m&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(x1,{title:"Regression Narrative",text:m.regression,field:"regression",onCopy:i,copiedField:l,onEdit:d?v=>d("regression",v):void 0}),u&&e.jsx(x1,{title:"Market Trend Narrative",text:m.marketTrend,field:"marketTrend",onCopy:i,copiedField:l,onEdit:d?v=>d("marketTrend",v):void 0})]}),u&&e.jsxs(CN,{defaultOpen:!0,children:[e.jsxs(RN,{className:"flex items-center gap-2 text-xs font-medium text-slate-600 hover:text-slate-800","data-testid":"toggle-market-trend",children:[e.jsx(fo,{className:"w-3 h-3"}),"Market Trend Details"]}),e.jsx(EN,{className:"mt-3",children:e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(ja,{children:e.jsxs(Ta,{className:"p-3",children:[e.jsx("h5",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-wide mb-2",children:"Price Trend"}),e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[u.priceTrend.direction==="increasing"&&e.jsx(Ql,{className:"w-4 h-4 text-emerald-600"}),u.priceTrend.direction==="decreasing"&&e.jsx(bN,{className:"w-4 h-4 text-red-600"}),u.priceTrend.direction==="stable"&&e.jsx(yI,{className:"w-4 h-4 text-slate-500"}),e.jsx("span",{className:"text-sm font-semibold capitalize",children:u.priceTrend.direction})]}),e.jsxs("p",{className:"text-[10px] text-slate-500",children:["$",Math.round(Math.abs(u.priceTrend.monthlyRate)).toLocaleString(),"/month",u.priceTrend.isSignificant?" (significant)":" (not significant)"]})]})}),e.jsx(ja,{children:e.jsxs(Ta,{className:"p-3",children:[e.jsx("h5",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-wide mb-2",children:"Supply & Demand"}),e.jsxs("p",{className:"text-sm font-semibold capitalize",children:[u.supplyDemand.marketCondition,"'s Market"]}),e.jsxs("div",{className:"text-[10px] text-slate-500 mt-1 space-y-0.5",children:[e.jsxs("p",{children:["Absorption: ",u.supplyDemand.absorptionRate," sales/mo"]}),e.jsxs("p",{children:["Supply: ",u.supplyDemand.monthsOfSupply," months"]}),e.jsxs("p",{children:["Active: ",u.supplyDemand.activeListings," | Pending: ",u.supplyDemand.pendingListings]})]})]})}),e.jsx(ja,{children:e.jsxs(Ta,{className:"p-3",children:[e.jsx("h5",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-wide mb-2",children:"Marketing Time"}),e.jsxs("p",{className:"text-sm font-semibold",children:[u.marketTime.medianDom," days ",e.jsx("span",{className:"text-xs font-normal text-slate-400",children:"(median)"})]}),e.jsxs("div",{className:"text-[10px] text-slate-500 mt-1 space-y-0.5",children:[e.jsxs("p",{children:["Average: ",u.marketTime.averageDom," days"]}),e.jsxs("p",{children:["Range: ",u.marketTime.minDom,"–",u.marketTime.maxDom," days"]})]})]})})]})})]})]})}function RK({rates:t,onUpdateRate:a,onToggleApply:s,advisorRates:r}){return e.jsxs("div",{className:"space-y-4","data-testid":"tab-adjustment-rates-content",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 bg-blue-50 border border-blue-200 rounded-md text-xs text-blue-800",children:[e.jsx(on,{className:"w-4 h-4 text-blue-500 shrink-0"}),e.jsx("span",{children:`Review each factor's regression rate and confidence level. Edit the recommended rate if needed. Toggle "Apply" to include/exclude from grid adjustments.`})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden bg-white",children:e.jsxs("table",{className:"w-full text-xs","data-testid":"rates-table",children:[e.jsx("thead",{className:"bg-slate-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"w-8 px-3 py-2"}),e.jsx("th",{className:"px-3 py-2 text-left font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center gap-1",children:["Factor ",e.jsx(Ko,{text:"The property characteristic being adjusted for (e.g., size, age, bathrooms)."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["Regression Rate ",e.jsx(Ko,{text:"The adjustment rate calculated from the market data. This is what the math says the rate should be."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["Advisor Rate ",e.jsx(Ko,{text:"An independent reference rate from a market advisor, if available. Compare this with the regression rate as a sanity check."})]})}),e.jsx("th",{className:"px-3 py-2 text-center font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:["Confidence ",e.jsx(Ko,{text:"How reliable the regression rate is. Strong = high confidence, use it. Moderate = review before using. Weak = consider skipping."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["p-Value ",e.jsx(Ko,{text:"The probability this adjustment rate happened by chance. Lower is better — green means strong evidence, amber means some evidence."})]})}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:["Recommended Rate ",e.jsx(Ko,{text:"The final rate that will be applied. You can edit this to override the regression rate based on your professional judgment."})]})}),e.jsx("th",{className:"px-3 py-2 text-center font-medium text-slate-600",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:["Apply ",e.jsx(Ko,{text:"Check to include this adjustment when applying rates to the comp grid. Uncheck to skip it."})]})})]})}),e.jsx("tbody",{children:t.map((n,i)=>e.jsxs("tr",{className:Q("border-b last:border-b-0 transition-colors",n.regressionConfidence==="strong"&&"bg-emerald-50/30",n.regressionConfidence==="moderate"&&"bg-amber-50/30",n.regressionConfidence==="weak"&&"bg-slate-50/30 opacity-70"),"data-testid":`rate-row-${n.variable}`,children:[e.jsxs("td",{className:"px-3 py-2 text-center",children:[n.regressionConfidence==="strong"&&e.jsx(kr,{className:"w-3.5 h-3.5 text-emerald-500"}),n.regressionConfidence==="moderate"&&e.jsx(Ns,{className:"w-3.5 h-3.5 text-amber-500"}),n.regressionConfidence==="weak"&&e.jsx(nf,{className:"w-3.5 h-3.5 text-slate-400"})]}),e.jsxs("td",{className:"px-3 py-2 font-medium text-slate-800",children:[n.label,n.regressionConfidence==="weak"&&e.jsx("span",{className:"block text-[9px] text-slate-400 mt-0.5",children:"Regression found no independent impact"}),n.warning&&n.regressionConfidence!=="weak"&&e.jsx("span",{className:"block text-[9px] text-amber-600 mt-0.5",children:"⚠ Rate may be inflated — see details"})]}),e.jsx("td",{className:"px-3 py-2 font-mono text-right font-medium",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[n.warning&&e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(Ns,{className:"w-3.5 h-3.5 text-amber-500 shrink-0 cursor-help","data-testid":`rate-warning-${n.variable}`})}),e.jsx(Wa,{side:"left",className:"max-w-xs text-xs",children:e.jsx("p",{children:n.warning})})]})}),e.jsx("span",{children:n.regressionRate!==null?`$${n.regressionRate.toFixed(2)}${n.unit}`:"—"})]})}),e.jsx("td",{className:"px-3 py-2 text-right",children:(()=>{const c={gla:"gla",lotSize:"site",age:"time",garageSpaces:"garage",finBasementSf:"basement",bathEquiv:"bathrooms",condGood:"condition",condExcellent:"condition"}[n.variable],d=c?r?.[c]:void 0;return d&&d.rate!=null?e.jsxs("span",{className:"font-mono text-xs text-slate-500",children:["$",d.rate.toFixed(2),d.unit||n.unit]}):e.jsx("span",{className:"text-slate-300",children:"—"})})()}),e.jsx("td",{className:"px-3 py-2 text-center",children:e.jsx(PK,{confidence:n.regressionConfidence})}),e.jsx("td",{className:Q("px-3 py-2 font-mono text-right",n.pValue!==null&&n.pValue<.05?"text-emerald-700":n.pValue!==null&&n.pValue<.2?"text-amber-700":"text-slate-400"),children:n.pValue?.toFixed(4)??"—"}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsx(ze,{type:"number",value:n.recommendedRate,onChange:l=>a(i,parseFloat(l.target.value)||0),className:"h-6 w-24 text-xs font-mono text-right ml-auto",step:.01,"data-testid":`rate-input-${n.variable}`})}),e.jsx("td",{className:"px-3 py-2 text-center",children:e.jsx(Pa,{checked:n.apply,onCheckedChange:()=>s(i),className:"h-4 w-4","data-testid":`apply-toggle-${n.variable}`})})]},n.variable))})]})}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-slate-500",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kr,{className:"w-3 h-3 text-emerald-500"})," Strong — apply adjustment with confidence"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ns,{className:"w-3 h-3 text-amber-500"})," Moderate — review and verify"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(nf,{className:"w-3 h-3 text-slate-400"})," Weak — consider skipping"]})]}),t.some(n=>n.warning)&&e.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 bg-amber-50 border border-amber-200 rounded-md text-xs text-amber-800","data-testid":"rates-warning-note",children:[e.jsx(Ns,{className:"w-3.5 h-3.5 text-amber-500 shrink-0 mt-0.5"}),e.jsx("span",{children:"Rates are market-extracted indications, not automatic adjustments. Flagged items (⚠) may be inflated by correlation between variables. Hover over the warning icon for details. The appraiser is always the final decision-maker."})]})]})}function EK({compAdjustments:t,reconciledRates:a,onApply:s,selectedComps:r,compRankings:n}){const[i,l]=o.useState(!1);return r?.length?e.jsxs("div",{className:"space-y-4","data-testid":"tab-apply-content",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-slate-500",children:["Calculated adjustments for ",t.length," selected comp",t.length>
391?"s":""," using ",a.length," factor",a.length>1?"s":""]}),e.jsxs(De,{size:"sm",onClick:s,className:"h-8 text-xs gap-1.5 px-4 bg-[#1B2A4A] hover:bg-[#2a3d66]","data-testid":"btn-apply-to-grid",children:[e.jsx(Zp,{className:"w-3.5 h-3.5"}),"Apply to Grid"]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden bg-white",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs","data-testid":"apply-grid-table",children:[e.jsx("thead",{className:"bg-slate-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left font-medium text-slate-600 sticky left-0 bg-slate-50 z-10 min-w-[200px]",children:"Comp"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600 min-w-[90px]",children:"Sale Price"}),a.map(c=>e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600 min-w-[120px]",children:c.label},c.variable)),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600 min-w-[90px]",children:"Net Adj"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium text-slate-600 min-w-[100px]",children:"Adj Price"})]})}),e.jsx("tbody",{children:t.map(c=>e.jsxs("tr",{className:"border-b last:border-b-0 hover:bg-slate-50","data-testid":`apply-row-${c.compId}`,children:[e.jsx("td",{className:"px-3 py-2 font-medium text-slate-800 sticky left-0 bg-white z-10",children:e.jsx("span",{className:"truncate block max-w-[190px]",children:c.address})}),e.jsxs("td",{className:"px-3 py-2 font-mono text-right",children:["$",c.salePrice.toLocaleString()]}),a.map(d=>{const p=c.adjustments[d.variable];return e.jsx("td",{className:"px-3 py-2 text-right",children:p?e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("span",{className:Q("font-mono font-medium cursor-help",p.amount>0?"text-emerald-700":p.amount<0?"text-red-700":"text-slate-400"),children:[p.amount>=0?"+":"","$",Math.abs(p.amount).toLocaleString()]})}),e.jsx(Wa,{className:"text-[10px] max-w-sm font-mono",children:p.derivation})]})}):e.jsx("span",{className:"text-slate-300",children:"—"})},d.variable)}),e.jsxs("td",{className:Q("px-3 py-2 font-mono text-right font-semibold",c.totalAdjustment>0?"text-emerald-700":c.totalAdjustment<0?"text-red-700":"text-slate-500"),children:[c.totalAdjustment>=0?"+":"","$",Math.abs(c.totalAdjustment).toLocaleString()]}),e.jsxs("td",{className:"px-3 py-2 font-mono text-right font-bold text-[#1B2A4A]",children:["$",c.adjustedPrice.toLocaleString()]})]},c.compId))})]})})}),t.length>0&&e.jsx(ja,{className:"border-[#1B2A4A]/20 bg-[#F5F0E8]/20",children:e.jsxs(Ta,{className:"p-3","data-testid":"adjustment-summary",children:[e.jsx("h4",{className:"text-xs font-semibold text-[#1B2A4A] mb-2",children:"Adjustment Summary"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-xs",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-slate-500",children:"Indicated Range"}),e.jsxs("p",{className:"font-mono font-semibold text-[#1B2A4A]",children:["$",Math.min(...t.map(c=>c.adjustedPrice)).toLocaleString()," – $",Math.max(...t.map(c=>c.adjustedPrice)).toLocaleString()]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-slate-500",children:"Median Adjusted"}),e.jsxs("p",{className:"font-mono font-semibold text-[#1B2A4A]",children:["$",(()=>{const c=[...t.map(d=>d.adjustedPrice)].sort((d,p)=>d-p);return Math.round(c[Math.floor(c.length/2)]).toLocaleString()})()]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-slate-500",children:"Avg Net Adjustment"}),e.jsxs("p",{className:"font-mono font-semibold text-[#1B2A4A]",children:["$",Math.round(t.reduce((c,d)=>c+Math.abs(d.totalAdjustment),0)/t.length).toLocaleString()]})]})]})]})}),n.length>0&&e.jsx(ja,{className:"border-slate-200",children:e.jsxs(Ta,{className:"p-0",children:[e.jsxs("button",{onClick:()=>l(!i),className:"w-full flex items-center justify-between px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50 transition-colors","data-testid":"btn-toggle-rankings",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Pl,{className:"w-3.5 h-3.5 text-indigo-500"}),"Regression-Ranked Comps (",n.length,")"]}),e.jsx(Rr,{className:Q("w-4 h-4 transition-transform",i&&"rotate-180")}
39)]}),i&&e.jsxs("div",{className:"border-t",children:[e.jsxs("table",{className:"w-full text-xs","data-testid":"rankings-table",children:[e.jsx("thead",{className:"bg-slate-50 border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-1.5 text-center font-medium text-slate-600 w-12",children:"Rank"}),e.jsx("th",{className:"px-3 py-1.5 text-left font-medium text-slate-600",children:"Address"}),e.jsx("th",{className:"px-3 py-1.5 text-right font-medium text-slate-600",children:"Sale Price"}),e.jsx("th",{className:"px-3 py-1.5 text-right font-medium text-slate-600",children:"Predicted"}),e.jsx("th",{className:"px-3 py-1.5 text-right font-medium text-slate-600",children:"Residual"}),e.jsx("th",{className:"px-3 py-1.5 text-right font-medium text-slate-600",children:"GLA"})]})}),e.jsx("tbody",{children:n.map((c,d)=>{const p=c.salePrice>0?Math.abs(c.residual/c.salePrice*100):0;return e.jsxs("tr",{className:"border-b last:border-b-0 hover:bg-slate-50","data-testid":`ranking-row-${c.id}`,children:[e.jsx("td",{className:"px-3 py-1.5 text-center",children:e.jsx("span",{className:Q("inline-flex items-center justify-center w-5 h-5 rounded-full text-[10px] font-bold",d===0?"bg-emerald-100 text-emerald-700":d===1?"bg-blue-100 text-blue-700":d===2?"bg-amber-100 text-amber-700":"bg-slate-100 text-slate-500"),children:d+1})}),e.jsx("td",{className:"px-3 py-1.5 font-medium text-slate-800 truncate max-w-[200px]",children:c.address}),e.jsxs("td",{className:"px-3 py-1.5 font-mono text-right",children:["$",c.salePrice.toLocaleString()]}),e.jsxs("td",{className:"px-3 py-1.5 font-mono text-right text-slate-600",children:["$",Math.round(c.predictedPrice).toLocaleString()]}),e.jsxs("td",{className:Q("px-3 py-1.5 font-mono text-right",p<5?"text-emerald-600":p<10?"text-amber-600":"text-red-600"),children:[c.residual>=0?"+":"","$",Math.round(c.residual).toLocaleString(),e.jsxs("span",{className:"text-[9px] ml-0.5 text-slate-400",children:["(",p.toFixed(1),"%)"]})]}),e.jsx("td",{className:"px-3 py-1.5 font-mono text-right text-slate-600",children:c.gla.toLocaleString()})]},c.id)})})]}),e.jsx("div",{className:"px-3 py-1.5 bg-slate-50 border-t text-[10px] text-slate-500",children:"Lower residual = comp is better explained by the regression model. Top-ranked comps are most consistent with market patterns."})]})]})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-center","data-testid":"tab-apply-no-comps",children:[e.jsx(Bx,{className:"w-10 h-10 text-slate-300 mb-2"}),e.jsx("p",{className:"text-sm text-slate-600 font-medium",children:"No Comps Selected"}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:"Select comparables in the Property Lab grid to calculate adjustments."})]})}function Ko({text:t}){return e.jsx(gr,{delayDuration:200,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(on,{className:"w-3 h-3 text-slate-400 hover:text-slate-600 cursor-help shrink-0"})}),e.jsx(Wa,{side:"bottom",className:"max-w-[260px] text-xs leading-relaxed",children:e.jsx("p",{children:t})})]})})}function t0({label:t,value:a,subtitle:s,color:r,tooltip:n}){return e.jsx(ja,{children:e.jsxs(Ta,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("p",{className:"text-[10px] font-medium text-slate-500 uppercase tracking-wide",children:t}),n&&e.jsx(Ko,{text:n})]}),e.jsx("p",{className:Q("text-lg font-bold font-mono",r?`text-${r}-700`:"text-[#1B2A4A]"),children:a}),s&&e.jsx("p",{className:"text-[10px] text-slate-400 mt-0.5",children:s})]})})}function wK({significance:t}){return t==="primary"?e.jsx(kt,{className:"text-[8px] px-1 py-0 bg-emerald-100 text-emerald-700 border-emerald-200",children:"Primary"}):t==="secondary"?e.jsx(kt,{className:"text-[8px] px-1 py-0 bg-amber-100 text-amber-700 border-amber-200",children:"Secondary"}):e.jsx(kt,{className:"text-[8px] px-1 py-0 bg-slate-100 text-slate-500 border-slate-200",children:"None"})}function PK({confidence:t}){const a={strong:"bg-emerald-100 text-emerald-700 border-emerald-200",moderate:"bg-amber-100 text-amber-700 border-amber-200",weak:"bg-slate-100 text-slate-500 border-slate-200",none:"bg-slate-100 text-slate-400 border-slate-200"};return e.jsx(kt,{className:Q("text-[8px] px-1.5 py-0 capitalize",a[t]),children:t})}function x1({title:t,text:a,field:s,onCopy:r,copiedField:n,onEdit:i}
39){const[l,c]=o.useState(!1),[d,p]=o.useState(a);return e.jsx(ja,{className:"border-slate-200",children:e.jsxs(Ta,{className:"p-3","data-testid":`narrative-${s}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold text-slate-700",children:t}),e.jsxs("div",{className:"flex items-center gap-1",children:[i&&!l&&e.jsxs(De,{size:"sm",variant:"ghost",onClick:()=>{p(a),c(!0)},className:"h-6 text-[10px] gap-1 px-2","data-testid":`btn-edit-${s}`,children:[e.jsx(Ru,{className:"w-3 h-3"})," Edit"]}),l&&e.jsxs(De,{size:"sm",variant:"ghost",onClick:()=>{i?.(d),c(!1)},className:"h-6 text-[10px] gap-1 px-2 text-emerald-600","data-testid":`btn-save-${s}`,children:[e.jsx(Bs,{className:"w-3 h-3"})," Save"]}),l&&e.jsx(De,{size:"sm",variant:"ghost",onClick:()=>c(!1),className:"h-6 text-[10px] gap-1 px-2 text-slate-400",children:"Cancel"}),e.jsxs(De,{size:"sm",variant:"ghost",onClick:()=>r(l?d:a,s),className:"h-6 text-[10px] gap-1 px-2","data-testid":`btn-copy-${s}`,children:[n===s?e.jsx(Bs,{className:"w-3 h-3 text-emerald-500"}):e.jsx(jr,{className:"w-3 h-3"}),n===s?"Copied":"Copy"]})]})]}),l?e.jsx("textarea",{value:d,onChange:u=>p(u.target.value),className:"w-full text-xs text-slate-600 leading-relaxed border rounded-md p-2 min-h-[100px] resize-y focus:outline-none focus:ring-1 focus:ring-[#1B2A4A]/30","data-testid":`textarea-${s}`}):e.jsx("p",{className:"text-xs text-slate-600 leading-relaxed whitespace-pre-wrap",children:a})]})})}const vM={stable:{verdict:"stable",label:"Stable",description:"Current supply and demand, recent sales activity, and price trends support predictable pricing behavior and typical exposure times. No special assumptions or abnormal risk qualifiers needed.",color:"text-emerald-700",bgColor:"bg-emerald-50",borderColor:"border-emerald-200"},declining:{verdict:"declining",label:"Declining",description:"Softening demand, downward price trends, and lengthening marketing times require increased market analysis and support to reflect current market behavior.",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-200"},increasing:{verdict:"increasing",label:"Increasing",description:"Strengthening demand, upward price trends, and shortened marketing times may require additional market analysis or support to reflect current market behavior.",color:"text-blue-700",bgColor:"bg-blue-50",borderColor:"border-blue-200"}};function uv(t){return t<=-2?"declining":t>=2?"increasing":"stable"}function OK(t,a){if(!t||!a)return"Date range unavailable";const s=new Date(t),r=new Date(a),n={month:"short",year:"numeric"};return`${s.toLocaleDateString("en-US",n)} – ${r.toLocaleDateString("en-US",n)}`}function LK(t){return t>.15?"increasing":t<-.15?"declining":"stable"}function $0({text:t}){return e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(on,{className:"w-3.5 h-3.5 text-slate-400 cursor-help inline-block ml-1"})}),e.jsx(Wa,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:t})})]})})}function Dj({data:t,isLoading:a,effectiveDate:s,isHpiData:r=!1}){if(a)return e.jsx("div",{className:"space-y-4",children:[1,2,3].map(m=>e.jsx(ja,{className:"animate-pulse",children:e.jsx(Ta,{className:"p-4",children:e.jsx("div",{className:"h-24 bg-slate-100 rounded"})})},m))});if(!t)return e.jsx(ja,{children:e.jsx(Ta,{className:"p-6 text-center text-slate-500",children:"No analysis data available. Lock the dataset first."})});const n=LK(t.monthlyRatePct),i=n==="increasing"?Ql:n==="declining"?bN:yI,l=n==="increasing"?"text-green-600":n==="declining"?"text-red-600":"text-slate-600",c=t.priceOverTime||(t.indexPoints||[]).map(m=>({month:m.fullLabel,medianPrice:m.medianPrice,salesCount:0,isLowConfidence:!1,rawMedian:m.medianPrice})),d=t.adjustmentTable||[],p=(t.monthsWithLowConfidence||0)>0,u=t.reliableMonthsCount||0;return e.jsxs("div",{className:"space-y-4","data-testid":"analysis-panel",children:[t.isReasonable===!1&&e.jsx(ja,{className:"border-amber-300 bg-amber-50",children:e.jsx(Ta,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2 text-amber-700",children:[e.jsx(Ns,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"This rate is unusually high (over 15% per year). Please double-check your data and confirm this matches what you're seeing in the market."})]})})}),!r&&u<2&&e.jsx(ja,{className:"border-red-200 bg-red-50",children:e.jsx(Ta,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2 text-red-700",children:[e.jsx(Ns,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Not enough reliable months to calculate a trend. Need at least 2 months with 3+ sales each."})]})})}),!r&&p&&u>=2&&e.jsx(ja,{className:"border-blue-200 bg-blue-50",children:e.jsx(Ta,{className:"p-3",children:e.jsxs("div",{className:"flex items-start gap-2 text-blue-700",children:[e.jsx(on,{className:"w-4 h-4 mt-0.5"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("span",{className:"font-medium",children:[t.monthsWithLowConfidence," of ",t.totalMonths," months"]})," have fewer than 3 sales.",e.jsx("span",{className:"text-blue-500 block mt-1",children:"Months with low confidence shown but should be used cautiously."})]})]})})}),!r&&t.salesCount===0&&e.jsx(ja,{className:"border-amber-300 bg-amber-50",children:e.jsx(Ta,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ns,{className:"w-5 h-5 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-amber-900",children:"No Sales in Analysis Window"}),e.jsx("p",{className:"text-sm text-amber-700 mt-1",children:"No closed sales found for the current effective date and window. This may happen if:"}),e.jsxs("ul",{className:"text-sm text-amber-700 mt-2 list-disc list-inside space-y-1",children:[e.jsx("li",{children:"The effective date is earlier than available MLS data"}),e.jsx("li",{children:"All sales were excluded by filters"}),e.jsx("li",{children:"The market area has insufficient recent activity"})]}),e.jsx("p",{className:"text-sm text-amber-600 mt-2 font-medium",children:"Try adjusting your effective date or expanding the market area."})]})]})})}),!r&&t.salesCount>0&&(()=>{const m=t.annualizedRatePct??t.yearOverYearPct??0,h=t.monthlyRatePct??0,f=uv(m),v=vM[f],S=u>=6?"high":u>=3?"medium":"low",N=f==="declining"?{label:"Severe",color:"bg-red-100 text-red-700 border-red-200"}:f==="stable"?{label:"Normal",color:"bg-slate-100 text-slate-700 border-slate-200"}:{label:"Strong",color:"bg-emerald-100 text-emerald-700 border-emerald-200"},x=t.dateRangeStart&&t.dateRangeEnd?`${Vi(new Date(t.dateRangeStart),"MMM")} - ${Vi(new Date(t.dateRangeEnd),"MMM yyyy")}`:"—",y=t.dateRangeStart&&t.dateRangeEnd?pb(new Date(t.dateRangeEnd),new Date(t.dateRangeStart))+1:0;return e.jsx(ja,{className:`border-2 ${v.borderColor}`,children:e.jsxs(Ta,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wide",children:"Market Condition"}),e.jsx(Ns,{className:`w-5 h-5 ${v.color}`})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("h2",{className:`text-3xl font-bold ${v.color}`,children:v.label}),e.jsxs(kt,{className:`${N.color} text-xs`,children:[e.jsx(Ql,{className:"w-3 h-3 mr-1"}),N.label]})]}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:v.description})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Annual Trend"}),e.jsxs("p",{className:`text-xl font-semibold ${m>=0?"text-emerald-600":"text-red-600"}`,"data-testid":"annual-trend",children:[m>=0?"+":"",m.toFixed(1),"%"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Confidence Score"}),e.jsx(kt,{variant:"outline",className:`mt-1 ${S==="high"?"border-emerald-300 text-emerald-700 bg-emerald-50":S==="medium"?"border-amber-300 text-amber-700 bg-amber-50":"border-slate-300 text-slate-700 bg-slate-50"}`,children:S.charAt(0).toUpperCase()+S.slice(1)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(mc,{className:"w-4 h-4 text-slate-400 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-500 block",children:"Time Range"}),e.jsx("span",{className:"text-sm font-medium text-slate-700",children:x}),e.jsxs("span",{className:"text-xs text-slate-400 block",children:[y," months analyzed"]})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(pf,{className:"w-4 h-4 text-slate-400 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-500 block",children:"Sample Size"}),e.jsxs("span",{className:"text-sm font-medium text-slate-700",children:[t.salesCount," Sales"]}),t.excludedCount>0&&e.jsxs("span",{className:"text-xs text-amber-600 block",children:[t.excludedCount," excluded"]})]})]})]}),e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("h4",{className:"text-sm font-medium text-slate-700 mb-3",children:"Market Vitality"}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[e.jsx("span",{className:"text-slate-600",children:"Avg Monthly Rate"}),e.jsxs("span",{className:`font-medium ${h>=0?"text-emerald-600":"text-red-600"}`,children:[h>=0?"+":"",h.toFixed(2),"%"]})]}),e.jsx("div",{className:"h-2 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${h>=0?"bg-emerald-500":"bg-red-500"}
39`,style:{width:`${Math.min(Math.abs(h)*10,100)}%`}})})]})})]})]})})})(),r&&e.jsx(ja,{children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Pl,{className:"w-4 h-4 text-slate-500"}),e.jsx("h3",{className:"font-semibold text-slate-900",children:"FHFA House Price Index"}),e.jsx(kt,{variant:"outline",className:"text-xs ml-auto",children:"Reference Only"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium text-slate-700","data-testid":"date-range",children:OK(t.dateRangeStart,t.dateRangeEnd)}),e.jsx("div",{className:"text-xs text-slate-500",children:"Data Range"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-lg font-semibold text-blue-600",children:[t.totalMonths||0," ",(t.totalMonths||0)===1?"period":"periods"]}),e.jsx("div",{className:"text-xs text-slate-500",children:"Data Points"})]})]}),(t.totalMonths||0)<=1&&e.jsxs("div",{className:"mt-3 p-2 bg-amber-50 border border-amber-200 rounded text-xs text-amber-700",children:[e.jsx(Ns,{className:"w-3 h-3 inline mr-1"}),"Limited data: FHFA ZIP data is annual (published with ~1 year lag). Consider MSA or State data for more recent quarterly trends."]})]})}),!r&&c.length>1&&e.jsx(ja,{children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(i,{className:`w-4 h-4 ${l}`}),e.jsx("h3",{className:"font-semibold text-slate-900",children:"Price Over Time"}),e.jsx(kt,{variant:"outline",className:"text-xs ml-auto",children:"Interactive Mode"}),e.jsx($0,{text:"Months with 3+ sales shown as connected blue line. Months with 1-2 sales shown as amber markers only (excluded from trend). Does NOT show adjustment magnitude."})]}),e.jsxs("div",{className:"mb-3 p-2 bg-slate-50 rounded-lg",children:[e.jsx("div",{className:"text-xs text-slate-500 mb-2",children:"Sales per month:"}),e.jsx("div",{className:"flex gap-1 flex-wrap",children:c.map((m,h)=>e.jsxs("div",{className:`px-2 py-1 rounded text-xs ${m.isLowConfidence?"bg-amber-100 text-amber-700 border border-amber-200":"bg-blue-100 text-blue-700 border border-blue-200"}`,title:`${m.month}: ${m.salesCount} sale${m.salesCount!==1?"s":""}`,children:[e.jsx("span",{className:"font-medium",children:m.salesCount}),e.jsx("span",{className:"text-slate-400 ml-1",children:m.month.split(" ")[0]})]},h))}),e.jsxs("div",{className:"mt-2 text-xs text-slate-400 flex gap-4",children:[e.jsxs("span",{children:[e.jsx("span",{className:"inline-block w-3 h-3 bg-blue-100 border border-blue-200 rounded mr-1"}),"3+ sales (reliable)"]}),e.jsxs("span",{children:[e.jsx("span",{className:"inline-block w-3 h-3 bg-amber-100 border border-amber-200 rounded mr-1"}),"<3 sales (low confidence)"]})]})]}),e.jsx("div",{className:"h-48",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(Fh,{data:c,margin:{top:5,right:10,left:10,bottom:5},children:[e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"month",tick:{fontSize:10,fill:"#64748b"},tickLine:!1,axisLine:{stroke:"#e2e8f0"}}),e.jsx(ql,{tick:{fontSize:10,fill:"#64748b"},tickLine:!1,axisLine:!1,tickFormatter:m=>`$${(m/1e3).toFixed(0)}k`,domain:["dataMin - 50000","dataMax + 50000"]}),e.jsx(uc,{content:({active:m,payload:h})=>{if(m&&h&&h.length){const f=h[0].payload,v=f.isLowConfidence,S=f.rawMedian||f.medianPrice;return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg shadow-lg p-3",children:[e.jsx("p",{className:"font-medium text-slate-900 text-sm",children:f.month}),e.jsxs("p",{className:"text-slate-600 text-sm mt-1",children:["Median: ",e.jsxs("span",{className:"font-semibold",children:["$",S?.toLocaleString()||"N/A"]})]}),e.jsxs("p",{className:`text-sm mt-1 ${v?"text-amber-600":"text-blue-600"}`,children:[e.jsx("span",{className:"font-medium",children:f.salesCount})," sale",f.salesCount!==1?"s":"",v?" (low confidence)":" (reliable)"]})]})}return null}}),e.jsx(np,{type:"monotone",dataKey:"medianPrice",stroke:"#3b82f6",strokeWidth:2,connectNulls:!1,dot:({cx:m,cy:h,payload:f})=>!f||f.isLowConfidence||f.medianPrice===null?e.jsx("g",{},`dot-${m}-${h}`):e.jsx("circle",{cx:m,cy:h,r:4,fill:"#3b82f6",stroke:"#fff",strokeWidth:2},`dot-${m}-${h}`),activeDot:{r:6,strokeWidth:2,stroke:"#fff",fill:"#3b82f6"}}),e.jsx(_h,{dataKey:"rawMedian",fill:"#f59e0b",shape:({cx:m,cy:h,payload:f})=>!f||!f.isLowConfidence?e.jsx("g",{},`scatter-empty-${m}-${h}`):e.jsxs("g",{children:[e.jsx("circle",{cx:m,cy:h,r:5,fill:"#f59e0b",stroke:"#d97706",strokeWidth:1}),e.jsx("text",{x:m,y:h-10,textAnchor:"middle",fontSize:9,fill:"#92400e",children:f.salesCount})]},`scatter-${m}-${h}`)})]})})}),e.jsx("p",{className:"text-xs text-slate-400 mt-2 text-center",children:"Blue line = reliable months (3+ sales). Amber dots = sparse months."})]})}),e.jsx(ja,{children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(mc,{className:"w-4 h-4 text-slate-500"}),e.jsx("h3",{className:"font-semibold text-slate-900",children:"Overall Market Trend"}),e.jsx($0,{text:"Linear approximation of overall market movement. See table below for month-specific adjustments."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("div",{className:"text-center p-4 bg-slate-50 rounded-lg",children:[e.jsx("div",{className:`text-3xl font-bold ${u<2?"text-slate-400":l}`,"data-testid":"annual-rate",children:u<2?"—":e.jsxs(e.Fragment,{children:[(t.annualizedRatePct??t.yearOverYearPct)>=0?"+":"",(t.annualizedRatePct??t.yearOverYearPct).toFixed(1),"%"]})}),e.jsx("div",{className:"text-sm text-slate-600 mt-1",children:"Annualized Rate"})]}),e.jsxs("div",{className:"text-center p-4 bg-blue-50 rounded-lg",children:[e.jsx("div",{className:`text-3xl font-bold ${u<2?"text-slate-400":"text-blue-700"}`,"data-testid":"monthly-rate",children:u<2?"—":e.jsxs(e.Fragment,{children:[t.monthlyRatePct>=0?"+":"",t.monthlyRatePct.toFixed(2),"%"]})}),e.jsx("div",{className:"text-sm text-slate-600 mt-1",children:"Avg Monthly Rate"})]})]})]})}
39),e.jsx(DK,{adjustmentRows:d,anchorMonth:t.anchorMonth,anchorMedian:t.anchorMedian,anchorIsLowConfidence:t.anchorIsLowConfidence})]})}function DK({adjustmentRows:t,anchorMonth:a,anchorMedian:s,anchorIsLowConfidence:r}){const[n,i]=o.useState("table");if(!t||t.length===0)return null;const l=t.map(u=>{const m=u.month.split(" "),h=m[0],v=(m[1]||"").slice(-2);return{month:`${h} '${v}`,fullMonth:u.month,priceLevel:u.priceIndexPct||0,salesCount:u.salesCount,isLowConfidence:u.isLowConfidence,isAnchor:u.isAnchor,medianPrice:u.medianPrice,adjustment:u.adjustmentPct}}),c=Math.min(...l.map(u=>u.priceLevel)),d=Math.max(...l.map(u=>u.priceLevel)),p=[Math.floor(c/5)*5-5,Math.ceil(d/5)*5+5];return l.findIndex(u=>u.isAnchor),e.jsx(ja,{children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(K0,{className:"w-4 h-4 text-slate-500"}),e.jsx("h3",{className:"font-semibold text-slate-900",children:"Monthly Adjustments"}),e.jsx(kt,{variant:"outline",className:"text-xs",children:"Fannie Mae B4-1.3-09"}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 bg-slate-100 rounded-lg p-1",children:[e.jsxs(De,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>i("table"),"data-testid":"toggle-table-view",children:[e.jsx(K5,{className:"w-4 h-4 mr-1"}),"Table"]}),e.jsxs(De,{variant:n==="chart"?"default":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>i("chart"),"data-testid":"toggle-chart-view",children:[e.jsx(sL,{className:"w-4 h-4 mr-1"}),"Chart"]})]}),e.jsx($0,{text:"Each month's adjustment is based on its actual median price relative to the effective date. Markets don't move linearly - use these month-specific adjustments for accuracy."})]}),a&&s&&e.jsx("div",{className:"mb-3 p-2 bg-green-50 border border-green-200 rounded-lg",children:e.jsxs("div",{className:"flex items-center gap-2 text-green-700 text-sm",children:[e.jsx(K0,{className:"w-4 h-4"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Effective Date Anchor:"})," ",a," @ $",s.toLocaleString(),r&&e.jsx("span",{className:"text-amber-600 ml-1",children:"(low confidence)"})]})]})}),n==="chart"?e.jsxs("div",{children:[e.jsx("div",{className:"h-64",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(Fh,{data:l,margin:{top:20,right:30,left:10,bottom:20},children:[e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"month",tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:{stroke:"#94a3b8"}}),e.jsx(ql,{domain:p,tick:{fontSize:11,fill:"#64748b"},tickLine:!1,axisLine:{stroke:"#94a3b8"},tickFormatter:u=>`${u>=0?"+":""}${u.toFixed(0)}%`,label:{value:"Price Level vs Effective Date",angle:-90,position:"insideLeft",style:{textAnchor:"middle",fontSize:11,fill:"#64748b"}}}),e.jsx(wu,{y:0,stroke:"#22c55e",strokeWidth:2,strokeDasharray:"5 5",children:e.jsx(C0,{value:"Effective Date",position:"right",fill:"#22c55e",fontSize:11,fontWeight:600})}),e.jsx(uc,{content:({active:u,payload:m})=>{if(u&&m&&m.length){const h=m[0].payload;return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg shadow-lg p-3",children:[e.jsx("p",{className:"font-semibold text-slate-900 text-sm",children:h.fullMonth}),e.jsxs("p",{className:"text-slate-600 text-sm mt-1",children:["Median: ",e.jsxs("span",{className:"font-semibold",children:["$",h.medianPrice?.toLocaleString()]})]}),e.jsxs("p",{className:`text-sm mt-1 ${h.priceLevel>=0?"text-green-600":"text-red-600"}`,children:["Price Level: ",e.jsxs("span",{className:"font-semibold",children:[h.priceLevel>=0?"+":"",h.priceLevel.toFixed(1),"%"]})]}),e.jsxs("p",{className:`text-sm font-medium ${h.adjustment>=0?"text-green-700":"text-red-700"}`,children:["Adjustment: ",h.adjustment>=0?"+":"",h.adjustment.toFixed(1),"%"]}),e.jsxs("p",{className:`text-xs mt-1 ${h.isLowConfidence?"text-amber-600":"text-blue-600"}`,children:[h.salesCount," sale",h.salesCount!==1?"s":"",h.isLowConfidence?" (low confidence)":""]})]})}return null}}),e.jsx(np,{type:"monotone",dataKey:"priceLevel",stroke:"#1e3a5f",strokeWidth:2.5,dot:({cx:u,cy:m,payload:h,index:f})=>h?h.isAnchor?e.jsxs("g",{children:[e.jsx("circle",{cx:u,cy:m,r:8,fill:"#22c55e",stroke:"#fff",strokeWidth:2}),e.jsx("text",{x:u,y:m-14,textAnchor:"middle",fontSize:10,fill:"#22c55e",fontWeight:600,children:"Anchor"})]},`dot-${f}`):h.isLowConfidence?e.jsx("circle",{cx:u,cy:m,r:5,fill:"#f59e0b",stroke:"#fff",strokeWidth:2},`dot-${f}`):e.jsx("circle",{cx:u,cy:m,r:5,fill:"#1e3a5f",stroke:"#fff",strokeWidth:2},`dot-${f}`):e.jsx("g",{},`dot-${f}`),activeDot:{r:7,strokeWidth:2,stroke:"#fff",fill:"#1e3a5f"}})]})})}),e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-6 text-xs text-slate-500",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full bg-[#1e3a5f]"}),"Reliable month"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full bg-amber-500"}),"Low confidence (<3 sales)"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full bg-green-500"}),"Effective date anchor"]})]}),e.jsx("p",{className:"text-xs text-slate-500 mt-2 text-center",children:"Points above the green line were priced higher than effective date (need negative adjustment). Points below were priced lower (need positive adjustment)."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-[300px] overflow-y-auto",children:e.jsxs(Gd,{children:[e.jsx(Hd,{className:"sticky top-0 bg-white",children:e.jsxs(gi,{children:[e.jsx(Ds,{className:"text-xs",children:"Month"}),e.jsx(Ds,{className:"text-xs text-center",children:"Sales"}),e.jsx(Ds,{className:"text-xs text-right",children:"Median"}),e.jsxs(Ds,{className:"text-xs text-center",children:["Price Level",e.jsx($0,{text:"How this month's median compares to effective date. Positive = above anchor, Negative = below anchor."})]}),e.jsxs(Ds,{className:"text-xs text-right",children:["Adjustment",e.jsx($0,{text:"Apply this % to a sale from this month to bring it to effective date value."})]})]})}),e.jsx(Wd,{children:t.map((u,m)=>e.jsxs(gi,{className:u.isAnchor?"bg-green-50":u.isLowConfidence?"bg-amber-50/50":"",children:[e.jsxs(ws,{className:"text-sm font-medium",children:[u.month,u.isAnchor&&e.jsx(kt,{className:"ml-2 text-xs bg-green-100 text-green-700",children:"Anchor"}),u.isLowConfidence&&!u.isAnchor&&e.jsx("span",{className:"text-amber-500 ml-1",title:"Fewer than 3 sales",children:"⚠"})]}),e.jsx(ws,{className:"text-sm text-center",children:e.jsx("span",{className:u.isLowConfidence?"text-amber-600 font-medium":"text-slate-600",children:u.salesCount})}),e.jsxs(ws,{className:"text-sm text-right font-mono text-slate-700",children:["$",(u.medianPrice||0).toLocaleStr
39ing()]}),e.jsx(ws,{className:"text-sm text-center font-mono",children:u.isAnchor?e.jsx("span",{className:"text-green-600",children:"0.0%"}):e.jsxs("span",{className:(u.priceIndexPct||0)>=0?"text-green-600":"text-red-600",children:[(u.priceIndexPct||0)>=0?"+":"",(u.priceIndexPct||0).toFixed(1),"%"]})}),e.jsx(ws,{className:"text-sm text-right font-mono font-semibold",children:u.isAnchor?e.jsx("span",{className:"text-slate-400",children:"0.0%"}):e.jsxs("span",{className:u.adjustmentPct>=0?"text-green-600":"text-red-600",children:[u.adjustmentPct>=0?"+":"",u.adjustmentPct.toFixed(1),"%"]})})]},m))})]})}),e.jsxs("p",{className:"text-xs text-slate-500 mt-3",children:[e.jsx("strong",{children:"How to use:"})," If a comparable sold in a specific month, apply that month's adjustment to bring the sale to the effective date value. Positive = add to sale price, Negative = subtract from sale price."]})]})]})})}function kK(t){if(t.contractDate){const a=new Date(t.contractDate);if(!isNaN(a.getTime()))return{date:a,basis:"contract"}}if(t.closeDate){const a=new Date(t.closeDate);if(!isNaN(a.getTime()))return{date:a,basis:"close"}}if(t.saleDate){const a=new Date(t.saleDate);if(!isNaN(a.getTime()))return{date:a,basis:"recording"}}return{date:null,basis:"none"}}function MK(t,a){const s=t.filter(f=>!a.has(f.id)&&!f.isNotClosed&&!f.isMissingDate&&f.salePrice>0);if(s.length<5){t.forEach(f=>{f.isHighOutlier=!1,f.isLowOutlier=!1});return}const r=s.map(f=>f.salePrice).sort((f,v)=>f-v),n=Math.floor(r.length*.05),i=Math.floor(r.length*.95);r[n],r[Math.min(i,r.length-1)];const l=Math.floor(r.length*.25),c=Math.floor(r.length*.75),d=r[l],p=r[c],u=p-d,m=d-u*1.5,h=p+u*1.5;t.forEach(f=>{if(a.has(f.id)||f.isNotClosed||f.isMissingDate||f.salePrice<=0){f.isHighOutlier=!1,f.isLowOutlier=!1;return}f.isHighOutlier=f.salePrice>h,f.isLowOutlier=f.salePrice<m})}function b1({title:t,sales:a,excludedIds:s,onExclusionsChange:r,onRecompute:n,isRecomputing:i=!1,lockedTotalCount:l}){const c=o.useMemo(()=>{const T=a.map(O=>{const{date:E,basis:R}=kK(O),G=O.status?.toLowerCase()||"sold",C=!["sold","closed","clsd","cls"].includes(G);return{...O,usableDate:E,dateBasis:R,isNotClosed:C,isMissingDate:E===null,isHighOutlier:!1,isLowOutlier:!1}});return MK(T,s),T},[a,s]),d=o.useMemo(()=>{const T=new Set;return c.forEach(O=>{(O.isNotClosed||O.isMissingDate)&&T.add(O.id)}),T},[c]),p=o.useMemo(()=>{const T=new Set(s);return d.forEach(O=>T.add(O)),T},[s,d]),u=a.length,m=u-p.size,h=p.size,f=c.filter(T=>T.isHighOutlier||T.isLowOutlier).length,[v,S]=o.useState(!0),[N,x]=o.useState("desc"),y=()=>{x(T=>T==="desc"?"asc":"desc")},b=(T,O)=>{const E=new Set(s);O?E.delete(T):E.add(T),r(E)},j=o.useMemo(()=>[...c].sort((T,O)=>{const E=N==="desc"?-1:1;return T.salePrice!==O.salePrice?(T.salePrice-O.salePrice)*E:T.usableDate&&O.usableDate?O.usableDate.getTime()-T.usableDate.getTime():T.usableDate?-1:O.usableDate?1:0}),[c,N]);return e.jsxs(ja,{children:[e.jsxs(Do,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ko,{className:"text-sm font-medium",children:t}),e.jsx(De,{size:"sm",variant:"ghost",onClick:()=>S(!v),className:"h-6 px-2","data-testid":"button-collapse-sales",children:v?e.jsx(Rr,{className:"w-4 h-4"}):e.jsx(Du,{className:"w-4 h-4"})})]}),e.jsxs(De,{size:"sm",variant:"outline",onClick:n,disabled:i,"data-testid":"button-recompute",children:[e.jsx(Kl,{className:`w-3 h-3 mr-1 ${i?"animate-spin":""}`}),"Recompute Analysis"]})]}),e.jsxs("div",{className:"flex gap-4 text-xs text-slate-500 mt-2",children:[e.jsxs("span",{children:["Locked: ",e.jsx("strong",{className:"text-slate-700",children:u})]}),e.jsxs("span",{children:["Included: ",e.jsx("strong",{className:"text-green-600",children:m})]}),e.jsxs("span",{children:["Excluded: ",e.jsx("strong",{className:"text-red-600",children:h})]}),f>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ns,{className:"w-3 h-3 text-amber-500"}),"Flagged outliers: ",e.jsx("strong",{className:"text-amber-600",children:f})]}),f===0&&e.jsx("span",{className:"text-slate-400",children:"No outliers flagged"})]})]}),!v&&e.jsx(Ta,{className:"p-0",children:e.jsx("div",{className:"max-h-[400px] overflow-y-auto",children:e.jsxs(Gd,{children:[e.jsx(Hd,{className:"sticky top-0 bg-white z-10",children:e.jsxs(gi,{children:[e.jsx(Ds,{className:"w-[50px]",children:"Include"}),e.jsx(Ds,{children:"Address"}),e.jsx(Ds,{className:"w-[140px]",children:"Contract Date"}),e.jsx(Ds,{className:"w-[130px] text-right",children:e.jsxs("button",{onClick:y,className:"flex items-center gap-1 ml-auto hover:text-slate-900 transition-colors","data-testid":"button-sort-price",children:["Sale Price",N==="desc"?e.jsx(gN,{className:"w-3 h-3"}):e.jsx(xN,{className:"w-3 h-3"})]})}),e.jsx(Ds,{className:"w-[80px]",children:"Flag"})]})}),e.jsx(Wd,{children:j.map(T=>{const O=d.has(T.id);s.has(T.id);const E=p.has(T.id);return e.jsxs(gi,{className:E?"bg-slate-50 text-slate-400":"","data-testid":`row-sale-${T.id}`,children:[e.jsx(ws,{children:e.jsx(Pa,{checked:!E,disabled:O,onCheckedChange:R=>b(T.id,!!R),"data-testid":`checkbox-include-${T.id}`})}),e.jsx(ws,{className:"font-mono text-xs",children:T.address}),e.jsx(ws,{children:e.jsx("div",{className:"flex items-center gap-1",children:T.usableDate?e.jsx("span",{className:"text-xs",children:Vi(T.usableDate,"MM/dd
39/yyyy")}):e.jsx("span",{className:"text-xs text-red-500",children:"Missing date (data gap)"})})}),e.jsxs(ws,{className:"text-right font-mono text-xs",children:["$",T.salePrice.toLocaleString()]}),e.jsxs(ws,{children:[T.isNotClosed&&e.jsx(kt,{variant:"destructive",className:"text-[10px]",children:"Not closed sale"}),T.isMissingDate&&!T.isNotClosed&&e.jsx(kt,{variant:"destructive",className:"text-[10px]",children:"Missing date (data gap)"}),T.isHighOutlier&&!T.isNotClosed&&!T.isMissingDate&&e.jsxs(kt,{variant:"outline",className:"text-[10px] border-amber-300 text-amber-600",children:[e.jsx(Ql,{className:"w-2 h-2 mr-0.5"}),"High"]}),T.isLowOutlier&&!T.isNotClosed&&!T.isMissingDate&&e.jsxs(kt,{variant:"outline",className:"text-[10px] border-amber-300 text-amber-600",children:[e.jsx(bN,{className:"w-2 h-2 mr-0.5"}),"Low"]}),!T.isNotClosed&&!T.isMissingDate&&!T.isHighOutlier&&!T.isLowOutlier&&e.jsx("span",{className:"text-slate-300",children:"—"})]})]},T.id)})})]})})})]})}function y1(t){return t>.25?"Increasing":t<-.25?"Declining":"Stable"}function FK(t,a){return!t||!a?!1:t.direction!==a.direction}function _K({effectiveDate:t,windowMonths:a,marketAnalysis:s,submarketAnalysis:r,hpiAnalysis:n,hpiSource:i,hpiGeography:l,selectedDataset:c,adjustmentRate:d,rationale:p,marketLockCount:u,submarketLockCount:m,marketExcludedCount:h,submarketExcludedCount:f}){const{toast:v}=hc(),[S,N]=o.useState(!0),[x,y]=o.useState(!0),[b,j]=o.useState(!0),[T,O]=o.useState(!0),[E,R]=o.useState(""),[G,U]=o.useState(""),[C,F]=o.useState(!1),[A,M]=o.useState(!1),B=new Date(t);B.setMonth(B.getMonth()-a);const oe=s?.monthlyRatePct??0,ae=r?.monthlyRatePct??0,D=n?.monthlyRatePct??0,_={windowStart:Vi(B,"yyyy-MM-dd"),marketAnalysis:s?{includedCount:u-h,excludedCount:h,monthlyRatePct:oe,direction:y1(oe)}:null,submarketAnalysis:r?{includedCount:m-f,excludedCount:f,monthlyRatePct:ae,direction:y1(ae)}:null,hpiAnalysis:n?{source:i==="zillow"?"Zillow":"FHFA",geography:l?.name||"Unknown",monthlyRatePct:D}:null},$=FK(_.marketAnalysis,_.submarketAnalysis),z=Yd({mutationKey:["narrativeGeneration",t,c],mutationFn:async()=>{console.log("[NarrativeBuilder] Starting generation...");const me=H=>{if(!H?.priceOverTime?.length)return{start:void 0,end:void 0};const ye=H.priceOverTime.filter(de=>de.medianPrice!==null&&de.salesCount>0);return ye.length<2?{start:void 0,end:void 0}:{start:ye[0].medianPrice??void 0,end:ye[ye.length-1].medianPrice??void 0}},Z=me(s),pe=me(r),se={effectiveDate:t,windowStart:Vi(B,"yyyy-MM-dd"),windowEnd:t,windowMonths:a,marketSalesCount:_.marketAnalysis?.includedCount??0,marketExcludedCount:_.marketAnalysis?.excludedCount??0,marketRate:_.marketAnalysis?.monthlyRatePct??0,submarketSalesCount:_.submarketAnalysis?.includedCount??0,submarketExcludedCount:_.submarketAnalysis?.excludedCount??0,submarketRate:_.submarketAnalysis?.monthlyRatePct??0,hpiSource:T&&_.hpiAnalysis?_.hpiAnalysis.source.toLowerCase():null,hpiGeography:T&&_.hpiAnalysis?_.hpiAnalysis.geography:null,hpiRate:T&&_.hpiAnalysis?_.hpiAnalysis.monthlyRatePct:null,selectedDataset:c,adjustmentRate:d,rationale:E||p||"",analysisMethod:"median price analysis",reliableMonthsCount:(c==="submarket"?r:s)?.reliableMonthsCount,totalMonths:(c==="submarket"?r:s)?.totalMonths,monthsWithLowConfidence:(c==="submarket"?r:s)?.monthsWithLowConfidence,marketMedianPriceStart:Z.start,marketMedianPriceEnd:Z.end,submarketMedianPriceStart:pe.start,submarketMedianPriceEnd:pe.end,outlierMethod:"iqr",dateBasis:"contract",marketAnnualizedRate:s?.annualizedRatePct,submarketAnnualizedRate:r?.annualizedRatePct},fe={marketConditions:S,timeAdjustmentSupport:x,reconciliation:b&&$};console.log("[NarrativeBuilder] Sending request with inputs:",se);const ue=await fetch("/api/time-adj/narrative/generate",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({inputs:se,sections:fe})});if(console.log("[NarrativeBuilder] Response status:",ue.status),!ue.ok){const H=await ue.json().catch(()=>({message:"Failed to generate narrative"}));throw console.error("[NarrativeBuilder] Error response:",H),new Error(H.message||"Failed to generate narrative")}const be=await ue.json();return console.log("[NarrativeBuilder] Success response:",{source:be.source,narrativeLength:be.narrative?.length}),be},onSuccess:me=>{console.log("[NarrativeBuilder] onSuccess called, setting narrative of length:",me.narrative?.length),me.narrative&&(U(me.narrative),console.log("[NarrativeBuilder] Narrative state updated")),me.source==="deterministic"?v({title:"Narrative Generated",description:"Used template-based generation. Review and edit as needed."}):v({title:"Narrative Generated",description:"AI-assisted narrative ready for review."})},onError:me=>{console.error("[NarrativeBuilder] onError called:",me.message),v({title:"Generation Failed",description:me.message,variant:"destructive"})}}),V=()=>{z.mutate()},le=async()=>
39{if(G)try{await navigator.clipboard.writeText(G),M(!0),setTimeout(()=>M(!1),2e3),v({title:"Copied!",description:"Narrative copied to clipboard."})}catch{v({title:"Copy Failed",description:"Could not copy to clipboard.",variant:"destructive"})}},W=(s||r)&&t;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ja,{className:"bg-slate-50",children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(gn,{className:"w-4 h-4 text-slate-600"}),e.jsx("h4",{className:"font-medium text-slate-900 text-sm",children:"Narrative Builder"}),e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("button",{className:"ml-1 text-slate-400 hover:text-slate-600","data-testid":"tooltip-trend-classification",children:e.jsx(on,{className:"w-3.5 h-3.5"})})}),e.jsxs(Wa,{side:"right",className:"max-w-xs text-xs",children:[e.jsx("p",{className:"font-medium mb-1",children:"Trend Classification Guidelines"}),e.jsx("p",{children:"Monthly rates within ±0.25% are considered generally stable. Rates above or below this range suggest increasing or declining conditions. Appraiser judgment governs final conclusions."})]})]})})]}),e.jsx("p",{className:"text-xs text-slate-600 mb-4",children:"Generate a neutral, factual narrative for your appraisal report based on your locked analysis data."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Pa,{id:"include-market",checked:S,onCheckedChange:me=>N(!!me),"data-testid":"checkbox-include-market"}),e.jsx(Ja,{htmlFor:"include-market",className:"text-xs",children:"Market summary"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Pa,{id:"include-timeadj",checked:x,onCheckedChange:me=>y(!!me),"data-testid":"checkbox-include-timeadj"}),e.jsx(Ja,{htmlFor:"include-timeadj",className:"text-xs",children:"Time adjustment support"})]}),$&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Pa,{id:"include-reconciliation",checked:b,onCheckedChange:me=>j(!!me),"data-testid":"checkbox-include-reconciliation"}),e.jsxs(Ja,{htmlFor:"include-reconciliation",className:"text-xs flex items-center gap-1",children:["Reconciliation",e.jsx(Ns,{className:"w-3 h-3 text-amber-500"})]})]}),n&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Pa,{id:"include-hpi",checked:T,onCheckedChange:me=>O(!!me),"data-testid":"checkbox-include-hpi"}),e.jsx(Ja,{htmlFor:"include-hpi",className:"text-xs",children:"External HPI context"})]})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(Ja,{htmlFor:"appraiser-notes",className:"text-xs text-slate-600 mb-1 block",children:"Additional notes (optional)"}),e.jsx(yi,{id:"appraiser-notes",placeholder:"Any additional context you want included...",value:E,onChange:me=>R(me.target.value),className:"text-sm h-16","data-testid":"input-appraiser-notes"})]}),e.jsx(De,{onClick:V,disabled:!W||z.isPending,className:"w-full","data-testid":"button-generate-narrative",children:z.isPending?e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gn,{className:"w-4 h-4 mr-2"}),"Generate Narrative"]})})]})}),G&&e.jsx(ja,{className:"bg-white border-green-200",children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"w-4 h-4 text-green-600"}),e.jsx("h4",{className:"font-medium text-slate-900 text-sm",children:"Generated Narrative"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(De,{variant:"outline",size:"sm",onClick:()=>F(!C),"data-testid":"button-edit-narrative",children:[e.jsx(SI,{className:"w-3 h-3 mr-1"}),C?"Done":"Edit"]}),e.jsx(De,{variant:"outline",size:"sm",onClick:le,"data-testid":"button-copy-narrative",children:A?e.jsxs(e.Fragment,{children:[e.jsx(pc,{className:"w-3 h-3 mr-1 text-green-600"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(jr,{className:"w-3 h-3 mr-1"}),"Copy"]})})]})]}),C?e.jsx(yi,{value:G,onChange:me=>U(me.target.value),className:"min-h-[200px] text-sm font-serif","data-testid":"textarea-narrative-edit"}):e.jsx("div",{className:"text-sm text-slate-700 whitespace-pre-wrap font-serif leading-relaxed bg-slate-50 p-4 rounded-lg border","data-testid":"text-narrative-output",children:G})]})}),!W&&e.jsx(ja,{className:"border-amber-200 bg-amber-50",children:e.jsx(Ta,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ns,{className:"w-4 h-4 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-amber-800",children:"Analysis Required"}),e.jsx("p",{className:"text-xs text-amber-700 mt-1",children:"Lock your Market and Sub-Market datasets to generate a narrative. The narrative is based on your actual analysis results."})]})]})})})]})}const B0=[{id:"market",label:"Market",icon:e.jsx(Pl,{className:"w-4 h-4"})},{id:"submarket",label:"Sub-Market",icon:e.jsx(K0,{className:"w-4 h-4"})},{id:"external",label:"External",icon:e.jsx(R0,{className:"w-4 h-4"})},{id:"reconcile",label:"Reconcile",icon:e.jsx(Ql,{className:"w-4 h-4"})},{id:"done",label:"Done",icon:e.jsx(pc,{className:"w-4 h-4"})}];function UK(t){switch(t){case"declining":return{label:"Severe",color:"bg-red-100 text-red-700 border-red-200"};case"stable":return{label:"Normal",color:"bg-slate-100 text-slate-700 border-slate-200"};default:return{label:"Strong",color:"bg-emerald-100 text-emerald-700 border-emerald-200"}}}function VK({children:t}){return e.jsx("div",{className:"bg-slate-50 border-l-4 border-blue-400 rounded-r-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ng,{className:"w-5 h-5 text-amber-500 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-slate-600",children:[e.jsx("span",{className:"font-semibold text-slate-700",children:"Did you know?"})," ",t]})]})})}function $K({children:t}){return e.jsx("div",{className:"bg-slate-50 border-l-4 border-slate-300 rounded-r-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ng,{className:"w-5 h-5 text-slate-500 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-slate-600",children:[e.jsx("span",{className:"font-semibold text-slate-700",children:"Reviewer Tip"}),e.jsx("br",{}),t]})]})})}function BK({currentStep:t,onStepClick:a,onContinue:s,onRefresh:r,continueLabel:n="Continue",isRefreshing:i=!1,canContinue:l=!0}){const c=B0.findIndex(d=>d.id===t);return e.jsxs("div",{className:"flex items-center justify-between border-b bg-white px-6 py-3",children:[e.jsx("div",{className:"flex items-center gap-1",children:B0.map((d,p)=>{const u=d.id===t,m=p<c,h=p>c;return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("button",{onClick:()=>a?.(d.id),disabled:h,"aria-disabled":h,tabIndex:h?-1:0,className:`
40                  flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-colors
41                  ${u?"bg-blue-50 text-blue-700 border border-blue-200":""}
42                  ${m?"text-slate-600 hover:bg-slate-100":""}
43                  ${h?"text-slate-400 cursor-not-allowed":""}
44                `,"data-testid":`step-${d.id}`,children:[m&&e.jsx(pc,{className:"w-4 h-4 text-emerald-500"}),!m&&d.icon,e.jsx("span",{children:d.label})]}),p<B0.length-1&&e.jsx("div",{className:`w-6 h-px mx-1 ${p<c?"bg-emerald-300":"bg-slate-200"}`})]},d.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx("button",{onClick:r,disabled:i,className:"p-2 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100 disabled:opacity-50","data-testid":"refresh-analysis",children:e.jsx(Kl,{className:`w-4 h-4 ${i?"animate-spin":""}`})}),e.jsxs(De,{onClick:s,disabled:!l,className:"bg-emerald-600 hover:bg-emerald-700 px-6 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"continue-button",children:[n," ",e.jsx(fo,{className:"w-4 h-4 ml-1"})]})]})]})}function S1({isOpen:t,onClose:a,title:s,sales:r,excludedIds:n,onExclusionsChange:i,onRecompute:l,isRecomputing:c,annualRatePct:d=0}){const p=r.length-n.size,u=r.filter(f=>f.isOutlier).length,m=Math.abs(d)>15,h=f=>{const v=new Set(n);v.has(f)?v.delete(f):v.add(f),i(v)};return e.jsx(Z5,{open:t,onOpenChange:f=>{f||a()}
44,children:e.jsxs(J5,{children:[e.jsx(X5,{className:"fixed inset-0 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",style:{zIndex:1100}}),e.jsxs(e2,{className:"fixed left-[50%] top-[50%] grid w-full max-w-4xl max-h-[85vh] translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-0 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg",style:{zIndex:1100},onPointerDownOutside:f=>{f.stopPropagation()},onEscapeKeyDown:f=>{f.stopPropagation()},children:[e.jsx($i,{className:"px-6 pt-6 pb-4 border-b",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(si,{className:"text-lg font-semibold flex items-center gap-2",children:[s,e.jsx(fo,{className:"w-4 h-4 text-slate-400 rotate-90"})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-sm",children:[e.jsxs("span",{className:"text-slate-500",children:["Locked: ",e.jsx("span",{className:"font-medium text-slate-700",children:r.length})]}),e.jsxs("span",{className:"text-emerald-600",children:["Included: ",e.jsx("span",{className:"font-medium",children:p})]}),e.jsxs("span",{className:"text-slate-500",children:["Excluded: ",e.jsx("span",{className:"font-medium",children:n.size})]}),u>0&&e.jsxs("span",{className:"text-amber-600 flex items-center gap-1",children:[e.jsx(Ns,{className:"w-3.5 h-3.5"}),"Flagged outliers: ",u]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(De,{variant:"outline",size:"sm",onClick:l,disabled:c,"data-testid":"modal-recompute",children:[e.jsx(Kl,{className:`w-4 h-4 mr-2 ${c?"animate-spin":""}`}),"Recompute Analysis"]}),e.jsx("button",{onClick:a,className:"p-2 hover:bg-slate-100 rounded-lg","data-testid":"modal-close",children:e.jsx(ur,{className:"w-4 h-4"})})]})]})}),e.jsx("div",{className:"overflow-auto max-h-[55vh]",children:e.jsxs(Gd,{children:[e.jsx(Hd,{children:e.jsxs(gi,{className:"bg-slate-50",children:[e.jsx(Ds,{className:"w-20",children:"INCLUDE"}),e.jsx(Ds,{children:"ADDRESS"}),e.jsx(Ds,{children:"CONTRACT DATE"}),e.jsx(Ds,{className:"text-right",children:"SALE PRICE"}),e.jsx(Ds,{className:"text-center",children:"FLAG"})]})}),e.jsx(Wd,{children:r.map(f=>{const v=n.has(f.id);return e.jsxs(gi,{className:v?"opacity-50":"","data-testid":`sale-row-${f.id}`,children:[e.jsx(ws,{children:e.jsx(Pa,{checked:!v,onCheckedChange:()=>h(f.id),className:"border-amber-400 data-[state=checked]:bg-amber-500 data-[state=checked]:border-amber-500","data-testid":`checkbox-${f.id}`})}),e.jsx(ws,{className:"font-medium",children:f.address}),e.jsx(ws,{className:"text-slate-500",children:f.contractDate?Vi(new Date(f.contractDate),"MM/dd/yyyy"):"—"}),e.jsxs(ws,{className:"text-right font-medium",children:["$",f.salePrice.toLocaleString()]}),e.jsxs(ws,{className:"text-center",children:[f.isOutlier&&f.outlierDirection==="high"&&e.jsxs(kt,{variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50",children:[e.jsx(YO,{className:"w-3 h-3 mr-1"})," High"]}),f.isOutlier&&f.outlierDirection==="low"&&e.jsxs(kt,{variant:"outline",className:"text-blue-600 border-blue-300 bg-blue-50",children:[e.jsx(GO,{className:"w-3 h-3 mr-1"})," Low"]}),f.isOutlier&&!f.outlierDirection&&e.jsxs(kt,{variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50",children:[e.jsx(Ns,{className:"w-3 h-3 mr-1"})," Outlier"]})]})]},f.id)})})]})}),m&&e.jsxs("div",{className:"px-6 py-4 border-t bg-amber-50 flex items-start gap-3",children:[e.jsx(Ns,{className:"w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5"}),e.jsx("p",{className:"text-sm text-amber-800",children:"This rate is unusually high (over 15% per year). Please double-check your data and confirm this reflects true market conditions."})]})]})]})})}function v1({verdict:t,annualTrend:a,monthlyRate:s,confidence:r,dateRange:n,salesCount:i,onViewEdit:l}){const c=vM[t],d=UK(t),p=n?`${Vi(new Date(n.start),"MMM")} - ${Vi(new Date(n.end),"MMM yyyy")}`:"—",u=n?pb(new Date(n.end),new Date(n.start))+1:0;return e.jsxs("div",{className:`rounded-xl border-2 ${c.borderColor} p-5 space-y-5`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wide",children:"Market Condition"}),e.jsx(Ns,{className:`w-5 h-5 ${c.color}`})]}),e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("h2",{className:`text-3xl font-bold ${c.color}`,children:c.label}),e.jsxs(kt,{className:`${d.color} text-xs`,children:[e.jsx(Ql,{className:"w-3 h-3 mr-1"}),d.label]})]}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:c.description})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Annual Trend"}),e.jsxs("p",{className:`text-xl font-semibold ${a>=0?"text-emerald-600":"text-red-600"}`,children:[a>=0?"+":"",a.toFixed(1),"%"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Confidence Score"}),e.jsx(kt,{variant:"outline",className:`mt-1 ${r==="high"?"border-emerald-300 text-emerald-700 bg-emerald-50":r==="medium"?"border-amber-300 text-amber-700 bg-amber-50":"border-slate-300 text-slate-700 bg-slate-50"}`,children:r.charAt(0).toUpperCase()+r.slice(1)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4 border-t",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(mc,{className:"w-4 h-4 text-slate-400 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-500 block",children:"Time Range"}),e.jsx("span",{className:"text-sm font-medium text-slate-700",children:p}),e.jsxs("span",{className:"text-xs text-slate-400 block",children:[u," months analyzed"]})]})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(pf,{className:"w-4 h-4 text-slate-400 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs text-slate-500 block",children:"Sample Size"}),e.jsxs("span",{className:"text-sm font-medium text-slate-700",children:[i," Sales"]}),e.jsxs("button",{onClick:l,className:"text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1",children:["View & Edit ",e.jsx(fo,{className:"w-3 h-3"})]})]})]})]}),e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("h4",{className:"text-sm font-medium text-slate-700 mb-3",children:"Market Vitality"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[e.jsx("span",{className:"text-slate-600",children:"Avg Monthly Rate"}),e.jsxs("span",{className:`font-medium ${s>=0?"text-emerald-600":"text-red-600"}`,children:[s>=0?"+":"",s.toFixed(2),"%"]})]}),e.jsx("div",{className:"h-2 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${s>=0?"bg-emerald-500":"bg-red-500"}`,style:{width:`${Math.min(Math.abs(s)*10,100)}%`}})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[e.jsx("span",{className:"text-slate-600",children:"Absorption Rate"}),e.jsx("span",{className:"font-medium text-emerald-600",children:"2.4 mo"})]}),e.jsx("div",{className:"h-2 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-emerald-500 rounded-full",style:{width:"30%"}})})]})]})]})]})}
44function N1({analysis:t,effectiveDate:a}){const s=o.useMemo(()=>t?.adjustmentTable?t.adjustmentTable.map(r=>({month:r.month,price:r.medianPrice,isAnchor:r.isAnchor})):[],[t]);return s.length?e.jsx("div",{className:"h-80",children:e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(Q5,{data:s,margin:{top:20,right:30,left:20,bottom:20},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"priceGradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#6366f1",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"#6366f1",stopOpacity:0})]})}),e.jsx(dc,{dataKey:"month",tick:{fontSize:12,fill:"#64748b"},axisLine:{stroke:"#e2e8f0"},tickLine:!1}),e.jsx(ql,{tick:{fontSize:12,fill:"#64748b"},axisLine:!1,tickLine:!1,tickFormatter:r=>`$${(r/1e3).toFixed(0)}k`}),e.jsx(uc,{formatter:r=>[`$${r.toLocaleString()}`,"Median Price"],contentStyle:{borderRadius:8,border:"1px solid #e2e8f0"}}),e.jsx(KS,{type:"monotone",dataKey:"price",stroke:"#6366f1",strokeWidth:2,fill:"url(#priceGradient)"}),e.jsx(wu,{y:s[s.length-1]?.price,stroke:"#ef4444",strokeDasharray:"4 4",label:{value:"T",position:"right",fill:"#ef4444",fontSize:12}})]})})}):e.jsx("div",{className:"h-80 flex items-center justify-center text-slate-400",children:"No data available"})}function A1({analysis:t,effectiveDate:a}){const s=o.useMemo(()=>t?.adjustmentTable?t.adjustmentTable.map(n=>({month:n.month.slice(0,3)+" '"+n.month.slice(-2),priceLevel:n.priceIndexPct??0,isAnchor:n.isAnchor})):[],[t]),r=s.find(n=>n.isAnchor);return s.length?e.jsxs("div",{className:"h-64",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-800",children:"Monthly Adjustment Analysis"}),r&&e.jsxs(kt,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:["Anchor: ",t?.adjustmentTable?.find(n=>n.isAnchor)?.month||"N/A"]})]}),e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(xI,{data:s,margin:{top:20,right:30,left:20,bottom:20},children:[e.jsx(dc,{dataKey:"month",tick:{fontSize:11,fill:"#64748b"},axisLine:{stroke:"#e2e8f0"},tickLine:!1}),e.jsx(ql,{tick:{fontSize:11,fill:"#64748b"},axisLine:!1,tickLine:!1,tickFormatter:n=>`${n>=0?"+":""}${n.toFixed(0)}%`}),e.jsx(uc,{formatter:n=>[`${n>=0?"+":""}${n.toFixed(1)}%`,"Price Level"],contentStyle:{borderRadius:8,border:"1px solid #e2e8f0"}}),e.jsx(np,{type:"monotone",dataKey:"priceLevel",stroke:"#1e293b",strokeWidth:2,dot:({cx:n,cy:i,payload:l})=>e.jsx("circle",{cx:n,cy:i,r:l.isAnchor?8:5,fill:l.isAnchor?"#10b981":"#1e293b",stroke:l.isAnchor?"#10b981":"#1e293b"})})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-6 mt-2 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-800"}),e.jsx("span",{className:"text-slate-600",children:"Reliable"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-amber-500"}),e.jsx("span",{className:"text-slate-600",children:"Low confidence"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-slate-600",children:"Effective Date"})]})]})]}):e.jsx("div",{className:"h-64 flex items-center justify-center text-slate-400",children:"No data available"})}function zK({zillowAnalysis:t,fhfaAnalysis:a}
44){const{chartData:s,anchorMonthLabel:r}=o.useMemo(()=>{const l=t?.adjustmentTable??[],c=a?.adjustmentTable??[],d=new Map,p=(h,f,v,S,N)=>{const x=h.includes("'")?h:h.length>=4?h.slice(0,3)+" '"+h.slice(-2):h,y=d.get(x);y?(y[f]=v,y.isAnchor=y.isAnchor||S):d.set(x,{month:x,zillow:f==="zillow"?v:null,fhfa:f==="fhfa"?v:null,isAnchor:S,sortKey:N})};l.forEach(h=>p(h.month,"zillow",h.priceIndexPct??0,!!h.isAnchor,-h.monthsToEffective)),c.forEach(h=>p(h.month,"fhfa",h.priceIndexPct??0,!!h.isAnchor,-h.monthsToEffective));const u=Array.from(d.values()).sort((h,f)=>h.sortKey-f.sortKey),m=u.find(h=>h.isAnchor);return{chartData:u,anchorMonthLabel:m?.month??null}},[t,a]),n=!!t?.adjustmentTable?.length,i=!!a?.adjustmentTable?.length;return s.length?e.jsxs("div",{className:"h-72",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-800",children:"Monthly Adjustment Analysis"}),r&&e.jsxs(kt,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200",children:["Anchor: ",r]})]}),e.jsx(cc,{width:"100%",height:"100%",children:e.jsxs(xI,{data:s,margin:{top:20,right:30,left:20,bottom:20},children:[e.jsx(dc,{dataKey:"month",tick:{fontSize:11,fill:"#64748b"},axisLine:{stroke:"#e2e8f0"},tickLine:!1}),e.jsx(ql,{tick:{fontSize:11,fill:"#64748b"},axisLine:!1,tickLine:!1,tickFormatter:l=>`${l>=0?"+":""}${l.toFixed(0)}%`}),e.jsx(uc,{formatter:(l,c)=>[l==null?"—":`${l>=0?"+":""}${l.toFixed(1)}%`,c],contentStyle:{borderRadius:8,border:"1px solid #e2e8f0"}}),e.jsx(Xj,{verticalAlign:"top",height:28,iconType:"circle",wrapperStyle:{fontSize:12,color:"#475569"}}),n&&e.jsx(np,{type:"monotone",dataKey:"zillow",name:"Zillow ZHVI",stroke:"#1e293b",strokeWidth:2,connectNulls:!0,dot:({cx:l,cy:c,payload:d})=>e.jsx("circle",{cx:l,cy:c,r:d.isAnchor?7:4,fill:d.isAnchor?"#10b981":"#1e293b",stroke:d.isAnchor?"#10b981":"#1e293b"})}),i&&e.jsx(np,{type:"monotone",dataKey:"fhfa",name:"FHFA HPI",stroke:"#6366f1",strokeWidth:2,connectNulls:!0,dot:({cx:l,cy:c,payload:d})=>e.jsx("circle",{cx:l,cy:c,r:d.isAnchor?7:4,fill:d.isAnchor?"#10b981":"#6366f1",stroke:d.isAnchor?"#10b981":"#6366f1"})})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-6 mt-2 text-xs",children:[n&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-800"}),e.jsx("span",{className:"text-slate-600",children:"Zillow ZHVI"})]}),i&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-indigo-500"}),e.jsx("span",{className:"text-slate-600",children:"FHFA HPI"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-slate-600",children:"Effective Date"})]})]})]}):e.jsx("div",{className:"h-64 flex items-center justify-center text-slate-400",children:"No data available"})}function j1({analysis:t}){return t?.adjustmentTable?.length?e.jsxs("div",{className:"mt-6",children:[e.jsxs("h3",{className:"text-lg font-semibold text-slate-800 mb-4 flex items-center gap-2",children:[e.jsx(Pl,{className:"w-5 h-5"}),"Monthly Adjustment Calculation"]}),e.jsxs(Gd,{children:[e.jsx(Hd,{children:e.jsxs(gi,{className:"bg-slate-50",children:[e.jsx(Ds,{className:"uppercase text-xs",children:"Month"}),e.jsx(Ds,{className:"uppercase text-xs text-center",children:"Sales Volume"}),e.jsx(Ds,{className:"uppercase text-xs text-right",children:"Median Price"}),e.jsx(Ds,{className:"uppercase text-xs text-right",children:"Price Level %"}),e.jsx(Ds,{className:"uppercase text-xs text-right",children:"Adjustment"})]})}),e.jsx(Wd,{children:t.adjustmentTable.map(a=>e.jsxs(gi,{children:[e.jsxs(ws,{className:"font-medium",children:[a.month,a.isAnchor&&e.jsx(kt,{className:"ml-2 bg-emerald-100 text-emerald-700 text-xs",children:"ANCHOR"})]}),e.jsx(ws,{className:"text-center",children:a.salesCount}),e.jsxs(ws,{className:"text-right",children:["$",(a.medianPrice??0).toLocaleString()]}),e.jsxs(ws,{className:`text-right ${(a.priceIndexPct??0)>=0?"text-emerald-600":"text-red-600"}`,children:[(a.priceIndexPct??0)>=0?"+":"",(a.priceIndexPct??0).toFixed(1),"%"]}),e.jsxs(ws,{className:`text-right font-medium ${a.adjustmentPct>=0?"text-emerald-600":"text-red-600"}`,children:[a.adjustmentPct>=0?"+":"",a.adjustmentPct.toFixed(1),"%"]})]},a.month))})]}),e.jsxs("div",{className:"mt-4 px-4 py-3 bg-slate-50 rounded-lg flex items-start gap-2",children:[e.jsx(Ng,{className:"w-4 h-4 text-slate-500 mt-0.5 flex-shrink-0"}),e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-medium",children:"Pro Tip:"})," If a comparable sold in a specific month, apply that month's adjustment to bring the sale to the effective date value. Positive means add to sale price, Negative means 
44subtract."]})]})]}):e.jsx("div",{className:"text-center py-8 text-slate-400",children:"No monthly data available"})}function qK({marketAnalysis:t,submarketAnalysis:a,externalAnalysis:s,externalSource:r,effectiveDate:n,selectedComps:i,onApplyAdjustments:l,isLoading:c=!1,marketSalesData:d=[],submarketSalesData:p=[],marketExcludedIds:u=new Set,submarketExcludedIds:m=new Set,onMarketExclusionsChange:h,onSubmarketExclusionsChange:f,onRecomputeMarket:v,onRecomputeSubmarket:S,isRecomputing:N=!1,zillowAnalysis:x,zillowSource:y,hpiSource:b="zillow",onHpiSourceChange:j}){const[T,O]=o.useState("market"),[E,R]=o.useState("price"),[G,U]=o.useState(!1),[C,F]=o.useState("even"),[A,M]=o.useState("submarket"),[B,oe]=o.useState("chart"),ae=o.useMemo(()=>{if(!t)return null;const de=t.annualizedRatePct??t.monthlyRatePct*12;return{verdict:uv(de),salesCount:t.salesCount,annualRatePct:de,monthlyRatePct:t.monthlyRatePct,confidence:t.salesCount>=30?"high":t.salesCount>=15?"medium":"low",dateRange:t.dateRangeStart&&t.dateRangeEnd?{start:t.dateRangeStart,end:t.dateRangeEnd}:null}},[t]),D=o.useMemo(()=>{if(!a)return null;const de=a.annualizedRatePct??a.monthlyRatePct*12;return{verdict:uv(de),salesCount:a.salesCount,annualRatePct:de,monthlyRatePct:a.monthlyRatePct,confidence:a.salesCount>=20?"high":a.salesCount>=10?"medium":"low",dateRange:a.dateRangeStart&&a.dateRangeEnd?{start:a.dateRangeStart,end:a.dateRangeEnd}:null}},[a]),_=de=>{if(!de)return null;const ge=de.annualizedRatePct??de.monthlyRatePct*12;return{verdict:uv(ge),salesCount:0,annualRatePct:ge,monthlyRatePct:de.monthlyRatePct,confidence:"high",dateRange:de.dateRangeStart&&de.dateRangeEnd?{start:de.dateRangeStart,end:de.dateRangeEnd}:null}},$=o.useMemo(()=>_(x),[x]),z=o.useMemo(()=>_(s),[s]),V=b==="fhfa"?z??$:$??z,le=b==="fhfa"?r??y:y??r,W=A==="market"?ae:D,me=A==="market"?t:a,Z=o.useMemo(()=>W?.monthlyRatePct??(W?.annualRatePct?W.annualRatePct/12:0),[W]),pe=o.useMemo(()=>{if(i.length===0)return[];const de=Z;return i.map(ge=>{const Be=ge.saleDate?new Date(ge.saleDate):null,He=Be?pb(n,Be):0;let Ie=0;return C==="even"?Ie=He*de:Ie=me?.adjustmentTable?.find(Pe=>{if(Be){const We=Be.toLocaleDateString("en-US",{month:"short",year:"numeric"});return Pe.month.includes(We.split(" ")[0])||Pe.month===We}return!1})?.adjustmentPct??He*de,{compId:ge.id,address:ge.address,saleDate:ge.saleDate||"",monthsAgo:He,adjustmentPct:Math.round(Ie*10)/10}})},[Z,me,i,C,n]),se=()=>{const de=["market","submarket","external","reconcile","done"],ge=de.indexOf(T);ge<de.length-1&&(O(de[ge+1]),R("price"))},fe=()=>{l(pe,C,Z),se()},ue=o.useMemo(()=>!ae||!$||!z?"moderate":$.verdict===ae.verdict&&z.verdict===ae.verdict?"strong":"moderate",[ae,$,z]);if(c)return e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsxs("div",{className:"animate-pulse space-y-4 w-full max-w-2xl",children:[e.jsx("div",{className:"h-8 bg-slate-200 rounded w-1/3 mx-auto"}),e.jsx("div",{className:"h-48 bg-slate-100 rounded-xl"}),e.jsx("div",{className:"h-12 bg-slate-100 rounded-lg w-1/4 mx-auto"})]})});const be=B0.findIndex(de=>de.id===T),H=T==="reconcile"?"Apply to Comps":"Continue",ye=o.useMemo(()=>{switch(T){case"market":return!!ae&&ae.salesCount>0;case"submarket":return!!D&&D.salesCount>0;case"external":return!0;case"reconcile":return!0;case"done":return!1;default:return!0}},[T,ae,D]);return e.jsxs("div",{className:"h-full flex flex-col bg-white",children:[e.jsx(BK,{currentStep:T,onStepClick:de=>{B0.findIndex(Be=>Be.id===de)<=be&&O(de)},onContinue:T==="reconcile"?fe:se,onRefresh:T==="market"?v:T==="submarket"?S:void 0,isRefreshing:N,continueLabel:H,canContinue:ye}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[T==="market"&&ae&&e.jsxs("div",{className:"grid grid-cols-[380px_1fr] h-full",children:[e.jsx("div",{className:"p-6 border-r overflow-auto",children:e.jsx(v1,{verdict:ae.verdict,annualTrend:ae.annualRatePct,monthlyRate:ae.monthlyRatePct,confidence:ae.confidence,dateRange:ae.dateRange,salesCount:ae.salesCount,onViewEdit:()=>U(!0)})}),e.jsxs("div",{className:"p-6 overflow-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsxs("button",{onClick:()=>R("price"),className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${E==="price"?"bg-blue-50 text-blue-700 border border-blue-200":"text-slate-600 hover:bg-slate-100"}`,children:[e.jsx(Ql,{className:"w-4 h-4"}),"Price Over Time"]}),e.jsxs("button",{onClick:()=>R("monthly"),className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${E==="monthly"?"bg-blue-50 text-blue-700 border border-blue-200":"text-slate-600 hover:bg-slate-100"}`,children:[e.jsx(Pl,{className:"w-4 h-4"}),"Monthly Adjustment"]})]}),e.jsx(ja,{children:e.jsxs(Ta,{className:"p-6",children:[E==="price"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-800",children:"Price Over Time"}),e.jsx(De,{variant:"outline",size:"sm",className:"text-xs",children:"Interactive Mode"})]}),e.jsx(N1,{analysis:t,effectiveDate:n})]}),E==="monthly"&&e.jsxs(e.Fragment,{children:[e.jsx(A1,{analysis:t,effectiveDate:n}),e.jsx(j1,{analysis:t})]})]})})]}),e.jsx(S1,{isOpen:G,onClose:()=>U(!1),title:"Market Sales",sales:d,excludedIds:u,onExclusionsChange:h||(()=>{}),onRecompute:v||(()=>{}),isRecomputing:N,annualRatePct:ae?.annualRatePct??0})]}),T==="submarket"&&D&&e.jsxs("div",{className:"grid grid-cols-[380px_1fr] h-full",children:[e.jsx("div",{className:"p-6 border-r overflow-auto",children:e.jsx(v1,{verdict:D.verdict,annualTrend:D.annualRatePct,monthlyRate:D.monthlyRatePct,confidence:D.confidence,dateRange:D.dateRange,salesCount:D.salesCount,onViewEdit:()=>U(!0)})}),e.jsxs("div",{className:"p-6 overflow-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsxs("button",{onClick:()=>R("price"),className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${E==="price"?"bg-blue-50 text-blue-700 border border-blue-200":"text-slate-600 hover:bg-slate-100"}`,children:[e.jsx(Ql,{className:"w-4 h-4"}),"Price Over Time"]}),e.jsxs("button",{onClick:()=>R("monthly"),className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${E==="monthly"?"bg-blue-50 text-blue-700 border border-blue-200":"text-slate-600 hover:bg-slate-100"}`,children:[e.jsx(Pl,{className:"w-4 h-4"}),"Monthly Adjustment"]})]}),e.jsx(ja,{children:e.jsxs(Ta,{className:"p-6",children:[E==="price"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-800",children:"Price Over Time"}),e.jsx(De,{variant:"outline",size:"sm",className:"text-xs",children:"Interactive Mode"})]}),e.jsx(N1,{analysis:a,effectiveDate:n})]}),E==="monthly"&&e.jsxs(e.Fragment,{children:[e.jsx(A1,{analysis:a,effectiveDate:n}),e.jsx(j1,{analysis:a})]})]})})]}),e.jsx(S1,{isOpen:G,onClose:()=>U(!1),title:"Sub-Market Sales",sales:p,excludedIds:m,onExclusionsChange:f||(()=>{}),onRecompute:S||(()=>{}),isRecomputing:N,annualRatePct:D?.annualRatePct??0})]}),T==="external"&&e.jsxs("div",{className:"grid grid-cols-[380px_1fr] h-full",children:[e.jsxs("div",{className:"p-6 border-r space-y-6 overflow-auto",children:[e.jsxs("div",{className:`rounded-xl border-2 p-5 ${ue==="strong"?"border-emerald-200":"border-amber-200"}`,"data-testid":"external-index-signal",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 uppercase tracking-wide",children:"Index Signal"}),e.jsx(R0,{className:"w-5 h-5 text-slate-400"})]}),e.jsx("h2",{className:`text-2xl font-bold mb-3 ${ue==="strong"?"text-emerald-700":"text-amber-700"}`,children:ue==="strong"?"Supports Your Findings":"Partially Aligned"}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed mb-4",children:ue==="strong"?"Both Zillow and FHFA confirm your local observations. The external indices point to the same market direction.":"The external indices partially agree with your local findings. Compare each source against your market verdict below."}),e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("div",{"data-testid":"index-signal-zillow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-slate-800"}),e.jsx("span",{className:"text-xs font-semibold text-slate-700 uppercase tracking-wide",children:"Zillow ZHVI"})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-slate-600",children:"Annual Trend"}),e.jsx("span",{className:`font-medium ${$?$.annualRatePct>=0?"text-emerald-600":"text-red-600":"text-slate-400"}`,children:$?`${$.annualRatePct>=0?"+":""}${$.annualRatePct.toFixed(1)}%`:"—"})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-slate-600",children:"Monthly Rate"}),e.jsx("span",{className:`font-medium ${$?$.monthlyRatePct>=0?"text-emerald-600":"text-red-600":"text-slate-400"}`,children:$?`${$.monthlyRatePct>=0?"+":""}${$.monthlyRatePct.toFixed(2)}%`:"—"})]})]}),e.jsxs("div",{className:"pt-2 border-t border-slate-100","data-testid":"index-signal-fhfa",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-indigo-500"}),e.jsx("span",{className:"text-xs font-semibold text-slate-700 uppercase tracking-wide",children:"FHFA HPI"})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-slate-600",children:"Annual Trend"}),e.jsx("span",{className:`font-medium ${z?z.annualRatePct>=0?"text-emerald-600":"text-red-600":"text-slate-400"}`,children:z?`${z.annualRatePct>=0?"+":""}${z.annualRatePct.toFixed(1)}%`:"—"})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-slate-600",children:"Monthly Rate"}),e.jsx("span",{className:`font-medium ${z?z.monthlyRatePct>=0?"text-emerald-600":"text-red-600":"text-slate-400"}`,children:z?`${z.monthlyRatePct>=0?"+":""}${z.monthlyRatePct.toFixed(2)}%`:"—"})]})]})]})]}),e.jsx($K,{children:"Using external indices like FHFA and Zillow provides independent validation. When they align, confidence in your adjustment increases."})]}),e.jsxs("div",{className:"p-6 overflow-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold text-slate-800 flex items-center gap-2","data-testid":"text-external-pane-title",children:[e.jsx(Pl,{className:"w-5 h-5"}),"External Indices • Zillow ZHVI + FHFA HPI"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:[le?.name??"External data"," • ",V?.dateRange?`${Vi(new Date(V.dateRange.start),"MMM yyyy")} - ${Vi(new Date(V.dateRange.end),"MMM yyyy")}`:"—"]})]}),e.jsxs("div",{className:"flex bg-slate-100 rounded-lg p-1",children:[e.jsx("button",{onClick:()=>oe("table"),className:`px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${B==="table"?"bg-white text-slate-800 shadow-sm":"text-slate-600"}`,"data-testid":"external-table-tab",children:"Table"}),e.jsx("button",{onClick:()=>oe("chart"),className:`px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${B==="chart"?"bg-white text-slate-800 shadow-sm":"text-slate-600"}`,"data-testid":"external-chart-tab",children:"Chart"})]})]}),e.jsx(ja,{children:e.jsxs(Ta,{className:B==="chart"?"p-6":"p-0",children:[B==="chart"&&e.jsxs(e.Fragment,{children:[e.jsx(zK,{zillowAnalysis:x??null,fhfaAnalysis:s}),e.jsxs("div",{className:"mt-4 px-4 py-3 bg-slate-50 rounded-lg flex items-start gap-2",children:[e.jsx(Ng,{className:"w-4 h-4 text-slate-500 mt-0.5 flex-shrink-0"}),e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-medium",children:"Note:"})," External indices show broader market trends. Compare with your local data to validate your findings."]})]})]}),B==="table"&&(()=>{const de=new Map;
44(x?.adjustmentTable??[]).forEach(He=>{de.set(He.month,{month:He.month,zillowPriceLevel:He.priceIndexPct??null,zillowAdjustment:He.adjustmentPct??null,fhfaPriceLevel:null,fhfaAdjustment:null,isAnchor:!!He.isAnchor,sortKey:-He.monthsToEffective})}),(s?.adjustmentTable??[]).forEach(He=>{const Ie=de.get(He.month);Ie?(Ie.fhfaPriceLevel=He.priceIndexPct??null,Ie.fhfaAdjustment=He.adjustmentPct??null,Ie.isAnchor=Ie.isAnchor||!!He.isAnchor):de.set(He.month,{month:He.month,zillowPriceLevel:null,zillowAdjustment:null,fhfaPriceLevel:He.priceIndexPct??null,fhfaAdjustment:He.adjustmentPct??null,isAnchor:!!He.isAnchor,sortKey:-He.monthsToEffective})});const ge=Array.from(de.values()).sort((He,Ie)=>He.sortKey-Ie.sortKey),Be=(He,Ie=!1)=>{if(He==null)return"—";const ce=Ie?He>=0?"+":"":He>=0?"-":"",Pe=Ie?He:Math.abs(He);return`${ce}${Pe.toFixed(1)}%`};return e.jsxs(Gd,{children:[e.jsx(Hd,{children:e.jsxs(gi,{className:"bg-slate-50",children:[e.jsx(Ds,{className:"uppercase text-xs",children:"Month"}),e.jsx(Ds,{className:"uppercase text-xs text-right",children:"Zillow Price Level"}),e.jsx(Ds,{className:"uppercase text-xs text-right",children:"Zillow Adjustment"}),e.jsx(Ds,{className:"uppercase text-xs text-right",children:"FHFA Price Level"}),e.jsx(Ds,{className:"uppercase text-xs text-right",children:"FHFA Adjustment"})]})}),e.jsxs(Wd,{children:[ge.length===0&&e.jsx(gi,{children:e.jsx(ws,{colSpan:5,className:"text-center py-8 text-slate-400",children:"No external data available"})}),ge.map(He=>e.jsxs(gi,{children:[e.jsxs(ws,{className:"font-medium",children:[He.month,He.isAnchor&&e.jsx(kt,{className:"ml-2 bg-emerald-100 text-emerald-700 text-xs",children:"ANCHOR"})]}),e.jsx(ws,{className:`text-right ${He.zillowPriceLevel===null?"text-slate-400":He.zillowPriceLevel>=0?"text-red-600":"text-emerald-600"}`,children:Be(He.zillowPriceLevel)}),e.jsx(ws,{className:`text-right font-medium ${He.zillowAdjustment===null?"text-slate-400":He.zillowAdjustment>=0?"text-emerald-600":"text-red-600"}`,children:Be(He.zillowAdjustment,!0)}),e.jsx(ws,{className:`text-right ${He.fhfaPriceLevel===null?"text-slate-400":He.fhfaPriceLevel>=0?"text-red-600":"text-emerald-600"}`,children:Be(He.fhfaPriceLevel)}),e.jsx(ws,{className:`text-right font-medium ${He.fhfaAdjustment===null?"text-slate-400":He.fhfaAdjustment>=0?"text-emerald-600":"text-red-600"}`,children:Be(He.fhfaAdjustment,!0)})]},He.month))]})]})})()]})})]})]}),T==="reconcile"&&e.jsxs("div",{className:"max-w-3xl mx-auto py-12 px-6 space-y-8",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h2",{className:"text-2xl font-semibold text-slate-800",children:"How would you like to adjust for time?"}),e.jsx("p",{className:"text-slate-500 mt-2",children:"Choose the method that best fits your market data"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsxs("button",{onClick:()=>F("even"),className:`p-6 rounded-xl border-2 text-left transition-all ${C==="even"?"border-blue-500 bg-blue-50":"border-slate-200 hover:border-slate-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center ${C==="even"?"border-blue-500 bg-blue-500":"border-slate-300"}`,children:C==="even"&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-white"})}),e.jsx("span",{className:"font-semibold text-slate-800",children:"Even Rate"})]}),e.jsx("p",{className:"text-sm text-slate-600 mb-4",children:"Apply the same monthly rate to all comps. Best when the market moved consistently."}),W&&e.jsxs("p",{className:"text-xl font-mono font-semibold text-blue-600",children:[W.monthlyRatePct>=0?"+":"",W.monthlyRatePct.toFixed(2),"%/mo"]})]}),e.jsxs("button",{onClick:()=>F("monthly"),className:`p-6 rounded-xl border-2 text-left transition-all ${C==="monthly"?"border-blue-500 bg-blue-50":"border-slate-200 hover:border-slate-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center ${C==="monthly"?"border-blue-500 bg-blue-500":"border-slate-300"}`,children:C==="monthly"&&e.jsx("div",{className:"w-2 h-2 rounded-full bg-white"})}),e.jsx("span",{className:"font-semibold text-slate-800",children:"Follow the Trend"})]}),e.jsx("p",{className:"text-sm text-slate-600 mb-4",children:"Each comp adjusts based on its actual sale month. Best when the market had ups and downs."}),e.jsx("p",{className:"text-slate-500",children:"Varies by month"})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Using data from:"}),e.jsxs("div",{className:"flex bg-slate-100 rounded-lg p-1",children:[e.jsx("button",{onClick:()=>M("market"),className:`px-4 py-1.5 text-sm font-medium rounded-md transition-colors ${A==="market"?"bg-white text-slate-800 shadow-sm":"text-slate-600"}`,children:"Market"}),e.jsx("button",{onClick:()=>M("submarket"),className:`px-4 py-1.5 text-sm font-medium rounded-md transition-colors ${A==="submarket"?"bg-white text-slate-800 shadow-sm":"text-slate-600"}`,children:"Sub-Market"})]})]}),e.jsx(ja,{children:e.jsx(Ta,{className:"p-8 text-center",children:i.length===0?e.jsx("p",{className:"text-slate-500",children:"No comps selected yet. Select comps in Property Lab to see how they'll adjust."}):e.jsxs(Gd,{children:[e.jsx(Hd,{children:e.jsxs(gi,{children:[e.jsx(Ds,{children:"Address"}),e.jsx(Ds,{children:"Sale Date"}),e.jsx(Ds,{className:"text-right",children:"Months Ago"}),e.jsx(Ds,{className:"text-right",children:"Adjustment"})]})}),e.jsx(Wd,{children:pe.map(de=>e.jsxs(gi,{children:[e.jsx(ws,{className:"font-medium",children:de.address}),e.jsx(ws,{children:de.saleDate?Vi(new Date(de.saleDate),"MMM yyyy"):"—"}),e.jsx(ws,{className:"text-right",children:de.monthsAgo}),e.jsxs(ws,{className:`text-right font-medium ${de.adjustmentPct>=0?"text-emerald-600":"text-red-600"}`,children:[de.adjustmentPct>=0?"+":"",de.adjustmentPct.toFixed(1),"%"]})]},de.compId))})]})})}),e.jsx(VK,{children:"Fannie Mae accepts both even-rate and month-by-month adjustments when properly supported. Most appraisers use an even rate. Month-by-month is more precise but takes a bit more support in your report."})]}),T==="done"&&e.jsxs("div",{className:"max-w-4xl mx-auto py-8 px-6 space-y-6",children:[e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto",children:e.jsx(pc,{className:"w-8 h-8 text-emerald-600"})}),e.jsx("h2",{className:"text-2xl font-semibold text-slate-800",children:"Time Adjustments Applied"}),e.jsx("p",{className:"text-slate-600",children:"Your selected comparables have been adjusted for time based on your market analysis."})]}),e.jsx(ja,{children:e.jsx(Ta,{className:"p-6",children:e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold text-slate-800",children:i.length}),e.jsx("p",{className:"text-sm text-slate-500",children:"Comps Adjusted"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold text-slate-800",children:C==="even"?"Even Rate":"Monthly"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Method"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:`text-2xl font-semibold ${Z>=0?"text-emerald-600":"text-red-600"}`,children:[Z>
44=0?"+":"",Z.toFixed(2),"%"]}),e.jsx("p",{className:"text-sm text-slate-500",children:"Monthly Rate"})]})]})})}),e.jsxs("div",{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(gn,{className:"w-5 h-5 text-slate-600"}),e.jsx("h3",{className:"text-lg font-semibold text-slate-800",children:"Generate Report Narrative"})]}),e.jsx(_K,{effectiveDate:Vi(n,"yyyy-MM-dd"),windowMonths:12,marketAnalysis:t,submarketAnalysis:a,hpiAnalysis:b==="zillow"?x??null:s,hpiSource:b||"fhfa",hpiGeography:b==="zillow"?y?{type:y.type,name:y.name}:null:r?{type:r.type,name:r.name}:null,selectedDataset:A,adjustmentRate:Z.toFixed(2),rationale:"",marketLockCount:d?.length||0,submarketLockCount:p?.length||0,marketExcludedCount:u?.size||0,submarketExcludedCount:m?.size||0})]})]})]})]})}const YK=3;function GK(t){const a=t?.toLowerCase().trim()||"sold";return["sold","closed","clsd","cls"].includes(a)}function oI(t){if(t.length===0)return 0;const a=[...t].sort((r,n)=>r-n),s=Math.floor(a.length/2);return a.length%2!==0?a[s]:(a[s-1]+a[s])/2}function HK(t,a){const s=[];let r=0;for(const n of t){if(!GK(n.status)){r++;continue}let i=null;if(n.contractDate){const d=new Date(n.contractDate);isNaN(d.getTime())||(i=d)}if(!i&&n.closeDate){const d=new Date(n.closeDate);isNaN(d.getTime())||(i=d)}if(!i&&n.saleDate){const d=new Date(n.saleDate);isNaN(d.getTime())||(i=d)}if(!i){r++;continue}if(a.has(n.id))continue;const l=typeof n.salePrice=="string"?parseFloat(n.salePrice):n.salePrice;if(!l||isNaN(l)||l<=0)continue;const c=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}`;s.push({id:n.id,saleDate:i,salePrice:l,monthKey:c})}return s.sort((n,i)=>n.saleDate.getTime()-i.saleDate.getTime()),{points:s,autoExcludedCount:r}}function WK(t){const a=new Map;for(const r of t){if(!a.has(r.monthKey)){const[n,i]=r.monthKey.split("-").map(Number),l=new Date(n,i-1,15);a.set(r.monthKey,{monthKey:r.monthKey,label:l.toLocaleDateString("en-US",{month:"short",year:"numeric"}),date:l,prices:[],median:0,count:0,isLowConfidence:!1})}a.get(r.monthKey).prices.push(r.salePrice)}const s=Array.from(a.values());return s.forEach(r=>{r.median=oI(r.prices),r.count=r.prices.length,r.isLowConfidence=r.count<YK}),s.sort((r,n)=>r.date.getTime()-n.date.getTime())}function KK(t,a){if(t.length===0)return null;const s=`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}`,r=t.find(c=>c.monthKey===s);if(r&&!r.isLowConfidence)return{anchorMedian:r.median,anchorMonth:r.label,anchorIsLowConfidence:!1};const n=t.filter(c=>!c.isLowConfidence);if(n.length===0){const d=[...t].sort((p,u)=>Math.abs(p.date.getTime()-a.getTime())-Math.abs(u.date.getTime()-a.getTime()))[0];return{anchorMedian:d.median,anchorMonth:d.label+" (fallback)",anchorIsLowConfidence:!0}}const i=n.filter(c=>c.date<=a);if(i.length>0){const c=i[i.length-1];return{anchorMedian:c.median,anchorMonth:c.label,anchorIsLowConfidence:!1}}const l=n.filter(c=>c.date>a);if(l.length>0){const c=l[0];return{anchorMedian:c.median,anchorMonth:c.label,anchorIsLowConfidence:!1}}return null}function QK(t){const a=t.filter(x=>!x.isLowConfidence);if(a.length<2)return{annualizedRatePct:0,monthlyRatePct:0,isReasonable:!0,reliableMonthsCount:a.length};const s=[...a].sort((x,y)=>x.date.getTime()-y.date.getTime()),r=Math.ceil(s.length/2),n=s.slice(0,r),i=s.slice(r);if(n.length===0||i.length===0)return{annualizedRatePct:0,monthlyRatePct:0,isReasonable:!0,reliableMonthsCount:a.length};const l=n.map(x=>x.median),c=i.map(x=>x.median),d=oI(l),p=oI(c);if(d<=0)return{annualizedRatePct:0,monthlyRatePct:0,isReasonable:!0,reliableMonthsCount:a.length};const u=(p-d)/d*100,m=s[0].date,f=(s[s.length-1].date.getTime()-m.getTime())/(30.44*24*60*60*1e3);if(f<=0)return{annualizedRatePct:0,monthlyRatePct:0,isReasonable:!0,reliableMonthsCount:a.length};const v=u/f,S=v*12,N=Math.abs(S)<=15;return{annualizedRatePct:S,monthlyRatePct:v,isReasonable:N,reliableMonthsCount:a.length}}function ZK(t,a,s,r){const n=a.getTime(),i=30.44*24*60*60*1e3;return t.map(l=>{const c=Math.round((n-l.date.getTime())/i),d=s>0?(l.median-s)/s*100:0,p=s>0?(s-l.median)/l.median*100:0,u=l.label===r||l.label===r.replace(" (fallback)","");return{month:l.label,monthsToEffective:c,medianPrice:Math.round(l.median),priceIndexPct:parseFloat(d.toFixed(1)),adju
44stmentPct:parseFloat(p.toFixed(1)),salesCount:l.count,isLowConfidence:l.isLowConfidence,isAnchor:u}})}function JK(t){return t.map(a=>({month:a.label,medianPrice:a.isLowConfidence?null:Math.round(a.median),salesCount:a.count,isLowConfidence:a.isLowConfidence,rawMedian:Math.round(a.median)}))}function _S(t,a,s,r){const{points:n,autoExcludedCount:i}=HK(t,a),l=WK(n),c=KK(l,s),d=c?.anchorMedian??0,p=c?.anchorMonth??null,u=c?.anchorIsLowConfidence??!1,{annualizedRatePct:m,monthlyRatePct:h,isReasonable:f,reliableMonthsCount:v}=QK(l),S=ZK(l,s,d,p||""),N=JK(l),x=n.length>0?n[0].saleDate.toISOString():null,y=n.length>0?n[n.length-1].saleDate.toISOString():null,b=a.size+i,j=S.map(E=>({month:E.month.split(" ")[0],adjustment:E.adjustmentPct,label:E.month})),T=N.map(E=>({month:E.month.split(" ")[0],fullLabel:E.month,indexValue:100,medianPrice:E.rawMedian})),O=l.filter(E=>E.isLowConfidence).length;return{salesCount:n.length,excludedCount:b,dateRangeStart:x,dateRangeEnd:y,annualizedRatePct:m,monthlyRatePct:h,isReasonable:f,anchorMonth:p,anchorMedian:d,anchorIsLowConfidence:u,priceOverTime:N,adjustmentTable:S,yearOverYearPct:m,monthlyAdjustments:j,indexPoints:T,totalMonths:l.length,monthsWithLowConfidence:O,reliableMonthsCount:v}}function XK({text:t}){return e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(on,{className:"w-3.5 h-3.5 text-slate-400 cursor-help inline-block ml-1"})}),e.jsx(Wa,{className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:t})})]})})}function T1(t){if(t.includes("-Q")){const[a,s]=t.split("-Q"),r=parseInt(a,10),i=(parseInt(s,10)-1)*3+2;return new Date(r,i-1,15)}else{const a=parseInt(t,10);return new Date(a,6,1)}}function I1(t){if(t.includes("-Q")){const[a,s]=t.split("-Q"),r=parseInt(a,10),n=parseInt(s,10);return{start:new Date(r,(n-1)*3,1),end:new Date(r,(n-1)*3+2,28)}}else{const a=parseInt(t,10);return{start:new Date(a,0,1),end:new Date(a,11,31)}}}function C1(t,a){const s=t.series,n=t.metadata.isAnnual??!1;if(s.length===0)return{salesCount:0,dateRangeStart:null,dateRangeEnd:null,excludedCount:0,yearOverYearPct:0,monthlyRatePct:0,monthlyAdjustments:[],isReasonable:!0,reliableMonthsCount:0};const i=[...s].sort((N,x)=>N.period.localeCompare(x.period)),l=i.map(N=>{const x=T1(N.period),y=n?N.period:x.toLocaleDateString("en-US",{month:"short",year:"numeric"}),b=30.44*24*60*60*1e3,j=Math.round((a.getTime()-x.getTime())/b),T=N.indexValue-100,O=-T,E=Math.abs(N.indexValue-100)<.01;return{month:y,monthsToEffective:j,medianPrice:void 0,priceIndexPct:parseFloat(T.toFixed(1)),adjustmentPct:parseFloat(O.toFixed(1)),salesCount:0,isLowConfidence:!1,isAnchor:E}}),c=Math.floor(a.getMonth()/3)+1,d=n?String(a.getFullYear()):`${a.getFullYear()}-Q${c}`,p=i.find(N=>N.period===d),u=l.find(N=>N.isAnchor),m=i[0],h=i[i.length-1],{start:f}=I1(m.period),{end:v}=I1(h.period),S=i.map(N=>{const x=T1(N.period);return{month:n?N.period:x.toLocaleDateString("en-US",{month:"short",year:"numeric"}),medianPrice:N.indexValue,salesCount:0,isLowConfidence:!1,rawMedian:N.indexValue}});return{salesCount:0,dateRangeStart:f.toISOString(),dateRangeEnd:v.toISOString(),excludedCount:0,yearOverYearPct:t.changeTotalPct,monthlyRatePct:t.ratePctPerMonthApprox,monthlyAdjustments:l.map(N=>({month:N.month.split(" ")[0],adjustment:N.adjustmentPct,label:N.month})),annualizedRatePct:t.ratePctPerMonthApprox*12,isReasonable:Math.abs(t.ratePctPerMonthApprox*12)<=15,priceOverTime:S,adjustmentTable:l,totalMonths:i.length,monthsWithLowConfidence:0,reliableMonthsCount:i.length,anchorMonth:u?.month||null,anchorMedian:p?p.indexValue:null,anchorIsLowConfidence:!1}}function R1(t,a){const s=t.series;if(t.metadata,s.length===0)return{salesCount:0,dateRangeStart:null,dateRangeEnd:null,excludedCount:0,yearOverYearPct:0,monthlyRatePct:0,monthlyAdjustments:[],isReasonable:!0,reliableMonthsCount:0};const r=[...s].sort((h,f)=>h.period.localeCompare(f.period)),n=r.map(h=>{const[f,v]=h.period.split("-").map(Number),S=new Date(f,v-1,15),N=S.toLocaleDateString("en-US",{month:"short",year:"numeric"}),x=30.44*24*60*60*1e3,y=Math.round((a.getTime()-S.getTime())/x),b=h.indexValue-100,j=-b,T=Math.abs(h.indexValue-100)<.01;return{month:N,monthsToEffective:y,medianPrice:void 0,priceIndexPct:parseFloat(b.toFixed(1)),adju
44stmentPct:parseFloat(j.toFixed(1)),salesCount:0,isLowConfidence:!1,isAnchor:T}}),i=r[0],l=r[r.length-1],c=h=>{const[f,v]=h.split("-").map(Number);return new Date(f,v-1,1)},d=c(i.period),p=c(l.period),u=r.map(h=>{const[f,v]=h.period.split("-").map(Number);return{month:new Date(f,v-1,15).toLocaleDateString("en-US",{month:"short",year:"numeric"}),medianPrice:h.indexValue,salesCount:0,isLowConfidence:!1,rawMedian:h.indexValue}}),m=n.find(h=>h.isAnchor);return{salesCount:0,dateRangeStart:d.toISOString(),dateRangeEnd:p.toISOString(),excludedCount:0,yearOverYearPct:t.changeTotalPct,monthlyRatePct:t.ratePctPerMonthApprox,monthlyAdjustments:n.map(h=>({month:h.month.split(" ")[0],adjustment:h.adjustmentPct,label:h.month})),annualizedRatePct:t.ratePctPerMonthApprox*12,isReasonable:Math.abs(t.ratePctPerMonthApprox*12)<=15,priceOverTime:u,adjustmentTable:n,totalMonths:r.length,monthsWithLowConfidence:0,reliableMonthsCount:r.length,anchorMonth:m?.month||null,anchorMedian:null,anchorIsLowConfidence:!1}}function NM({marketContext:t,assignmentId:a,marketResultsCount:s=0,submarketResultsCount:r=0,marketResultIds:n=[],submarketResultIds:i=[],marketSalesData:l=[],submarketSalesData:c=[],subjectState:d,subjectZipCode:p,subjectMsaCode:u,parentMarketLocked:m=!1,parentSubMarketLocked:h=!1,selectedCompsForWizard:f=[]}){const{toast:v}=hc(),S=ku(),[N,x]=o.useState(()=>m||h?"analyze":"lock"),[y,b]=o.useState("market"),[j,T]=o.useState(()=>m&&s>0?{isLocked:!0,salesCount:s,lockedAt:null,resultIds:n}:{isLocked:!1,salesCount:0,lockedAt:null,resultIds:[]}),[O,E]=o.useState(()=>h&&r>0?{isLocked:!0,salesCount:r,lockedAt:null,resultIds:i}:{isLocked:!1,salesCount:0,lockedAt:null,resultIds:[]}),[R,G]=o.useState(new Set),[U,C]=o.useState(new Set),[F,A]=o.useState(!1),[M,B]=o.use
44State(null),[oe,ae]=o.useState(null),[D,_]=o.useState(!1),[$,z]=o.useState(null),[V,le]=o.useState(null),[W,me]=o.useState("zillow"),[Z,pe]=o.useState(12),[se,fe]=o.useState(null),[ue,be]=o.useState(""),[H,ye]=o.useState(""),[de,ge]=o.useState(!1),[Be,He]=o.useState("flat"),[Ie,ce]=o.useState(null),[Pe,We]=o.useState(!1),[Re,ne]=o.useState(""),[Me,lt]=o.useState(!1),[Tt,je]=o.useState(!0),[Le,ut]=o.useState([]),{data:st,isLoading:Xt,refetch:ua}=Vr({queryKey:["time-adj-session",a],queryFn:async()=>{if(!a)return null;const pt=await fetch(`/api/time-adj/sessions?assignmentId=${encodeURIComponent(a)}`,{credentials:"include"});if(pt.status===404)return null;if(!pt.ok)throw new Error("Failed to load session");return pt.json()},enabled:!!a}),Oa=pt=>Math.min(3e3*Math.pow(1.5,pt),3e4),Xa=120*1e3,qa=o.useRef({attempt:0,start:null}),os=o.useRef({attempt:0,start:null}),ya=o.useRef({attempt:0,start:null}),At=o.useRef({attempt:0,start:null}),[Fe,Oe]=o.useState(!1),[rt,$t]=o.useState(!1);o.useEffect(()=>{qa.current={attempt:0,start:null},os.current={attempt:0,start:null},ya.current={attempt:0,start:null},At.current={attempt:0,start:null},Oe(!1),$t(!1),Ua(!1),sa(!1)},[p,d,u]);const{data:na}=Vr({queryKey:["fhfa-cache-status"],queryFn:async()=>{const pt=await fetch("/api/fhfa/cache-status",{credentials:"include"});if(!pt.ok)throw new Error("Failed to check cache status");return pt.json()},refetchInterval:pt=>{if(pt.state.data?.allReady)return qa.current={attempt:0,start:null},!1;const re=qa.current;if(re.start===null&&(re.start=Date.now()),Date.now()-re.start>Xa)return Oe(!0),!1;const qe=Oa(re.attempt);return re.attempt+=1,qe},staleTime:5e3}),[zt,Ua]=o.useState(!1),{data:Ce,isLoading:St}=Vr({queryKey:["fhfa-hpi",p,d,u,Z,t?.effectiveDate],queryFn:async()=>{console.log("[FHFA] Query executing with:",{subjectZipCode:p,subjectState:d,subjectMsaCode:u,hpiTimeRange:Z});const pt=Z,re=t?.effectiveDate||new Date().toISOString().split("T")[0];let qe=!1;const Ze=async(It,Ne)=>{try{const Ue=await fetch(`/api/fhfa/series?geoType=${It}&geoId=${encodeURIComponent(Ne)}&months=${pt}&effectiveDate=${re}`,{credentials:"include"});if(!Ue.ok)return null;const ct=await Ue.json();if(ct?.status==="syncing")return qe=!0,null;if(ct?.series?.length>0)return console.log(`[FHFA] Using ${It.toUpperCase()} ${Ne} data`),ct}catch{}return null};if(p){const It=await Ze("zip",p);if(It)return Ua(!1),It}if(u){const It=await Ze("msa",u);if(It)return Ua(!1),It}if(d){const It=await Ze("state",d);if(It)return Ua(!1),It}return Ua(qe),null},enabled:!!(d||u||p)&&!!t,staleTime:1440*60*1e3,refetchInterval:()=>{if(!zt)return ya.current={attempt:0,start:null},!1;const pt=ya.current;if(pt.start===null&&(pt.start=Date.now()),Date.now()-pt.start>Xa)return Oe(!0),!1;const re=Oa(pt.attempt);return pt.attempt+=1,re}}),{data:vt}=Vr({queryKey:["zillow-cache-status"],queryFn:async()=>{const pt=await fetch("/api/zillow/cache-status",{credentials:"include"});if(!pt.ok)throw new Error("Failed to check Zillow cache status");return pt.json()},refetchInterval:pt=>{if(pt.state.data?.allReady)return os.current={attempt:0,start:null},!1;const re=os.current;if(re.start===null&&(re.start=Date.now()),Date.now()-re.start>Xa)return $t(!0),!1;const qe=Oa(re.attempt);return re.attempt+=1,qe},staleTime:5e3}),[Ve,sa]=o.useState(!1),{data:tt,isLoading:it}=Vr({queryKey:["zillow-zhvi",p,d,Z,t?.effectiveDate],queryFn:async()=>{console.log("[Zillow] Query executing with:",{subjectZipCode:p,subjectState:d,hpiTimeRange:Z});const pt=Z,re=t?.effectiveDate||new Date().toISOString().split("T")[0],qe=new URLSearchParams({months:String(pt),effectiveDate:re});p&&qe.append("zipCode",p),d&&qe.append("stateCode",d);const Ze=await fetch(`/api/zillow/cascade?${qe}`,{credentials:"include"});if(Ze.ok){const It=await Ze.json();if(It?.status==="syncing")return sa(!0),null;if(It?.series?.length>0)return console.log(`[Zillow] Using ${It.sourceLevel} level data: ${It.metadata?.geoName}`),sa(!1),It}return sa(!1),null},refetchInterval:()=>{if(!Ve)return At.current={attempt:0,start:null},!1;const pt=At.current;if(pt.start===null&&(pt.start=Date.now()),Date.now()-pt.start>Xa)return $t(!0),!1;const re=Oa(pt.attempt);return pt.attempt+=1,re},enabled:!!(d||p)&&!!t,staleTime:1440*60*1e3});o.useEffect(()=>{if(st){if(st.marketLockJson){const pt=st.marketLockJson;T({isLocked:!0,salesCount:pt.counts?.totalResultsCount||0,lockedAt:pt.lockedAt||null,resultIds:pt.resultIds||[]})}if(st.submarketLockJson){const pt=st.submarketLockJson;E({isLocked:!0,salesCount:pt.counts?.totalResultsCount||0,lockedAt:pt.lockedAt||null,resultIds:pt.resultIds||[]})}st.marketLockJson&&st.submarketLockJson&&x("analyze")}},[st]),o.useEffect(()=>{m&&!j.isLocked&&s>0&&T({isLocked:!0,salesCount:s,lockedAt:null,resultIds:n}),h&&!O.isLocked&&r>0&&E({isLocked:!0,salesCount:r,lockedAt:null,resultIds:i}),!m&&j.isLocked&&(T({isLocked:!1,salesCount:0,lockedAt:null,resultIds:[]}),B(null),G(new Set)),!h&&O.isLocked&&(E({isLocked:!1,salesCount:0,lockedAt:null,resultIds:[]}),ae(null),C(new Set)),m||h?N==="lock"&&x("analyze"):x("lock")},[m,h,s,r,n,i]);const Je=async()=>
44{if(!(!t||!a))try{let pt=st?.id;if(!pt){const qe=await fetch("/api/time-adj/sessions",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({assignmentId:a,effectiveDate:t.effectiveDate,scopeType:"market",geometryType:t.geometryType,geometryData:t.geometryData,filters:t.filters,windowMonths:t.windowMonths||12})});if(!qe.ok)throw new Error("Failed to create session");pt=(await qe.json()).id}if(!(await fetch(`/api/time-adj/sessions/${pt}/lock-market`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({geometryType:t.geometryType,geometryData:t.geometryData,filters:t.filters,datasource:"mls",totalResultsCount:s,closedEligibleCount:null,resultIds:n})})).ok)throw new Error("Failed to lock market");T({isLocked:!0,salesCount:s,lockedAt:new Date().toISOString(),resultIds:n}),v({title:"Market locked",description:`${s} sales frozen for analysis`}),ua()}catch{v({title:"Error",description:"Failed to lock market",variant:"destructive"})}},ht=async()=>{if(!(!t||!st?.id))try{if(!(await fetch(`/api/time-adj/sessions/${st.id}/lock-submarket`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({geometryType:t.geometryType,geometryData:t.geometryData,filters:t.filters,datasource:"mls",totalResultsCount:r,closedEligibleCount:null,resultIds:i})})).ok)throw new Error("Failed to lock sub-market");E({isLocked:!0,salesCount:r,lockedAt:new Date().toISOString(),resultIds:i}),v({title:"Sub-Market locked",description:`${r} sales frozen for analysis`}),x("analyze"),ua(),Kt()}catch{v({title:"Error",description:"Failed to lock sub-market",variant:"destructive"})}},Kt=()=>{_(!0);try{const pt=t?.windowMonths||12;if(l.length>0){const re=_S(l,R,ea,pt);B(re)}if(c.length>0){const re=_S(c,U,ea,pt);ae(re)}}catch{v({title:"Error",description:"Failed to analyze data",variant:"destructive"})}finally{_(!1)}},Sa=pt=>{A(!0);try{const re=t?.windowMonths||12;if(pt==="market"&&l.length>0){const qe=_S(l,R,ea,re);B(qe)}else if(pt==="submarket"&&c.length>0){const qe=_S(c,U,ea,re);ae(qe)}v({title:"Analysis updated",description:`${pt==="market"?"Market":"Sub-Market"} analysis recomputed with your exclusions`})}catch{v({title:"Error",description:"Failed to recompute analysis",variant:"destructive"})}finally{A(!1)}},Qt=async()=>{if(!(!st?.id||!se||Be==="flat"&&!ue)){ge(!0);try{const pt=Be==="flat"?parseFloat(ue):null;if(Be==="flat"&&(pt===null||isNaN(pt)))throw new Error("Invalid rate");const re=Be==="month-specific"?se==="market"?M?.adjustmentTable:oe?.adjustmentTable:null,qe=Be==="month-specific"?`Month-specific adjustments applied based on ${se} price index per Fannie Mae guidelines`:`Appraiser selected ${pt}% monthly rate based on ${se} analysis`;if(!(await fetch(`/api/time-adj/sessions/${st.id}/decision`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({selectedDataset:se,selectedMethod:Be==="month-specific"?"month-specific":"linear",overrideReason:H||qe,customRate:pt,rateMode:Be,adjustmentTable:re})})).ok)throw new Error("Failed to save decision");v({title:"Decision saved",description:"Your time adjustment decision has been recorded"}),ua()}catch{v({title:"Error",description:"Failed to save decision",variant:"destructive"})}finally{ge(!1)}}};o.useMemo(()=>Array.from(R).sort().join(","),[R]),o.useMemo(()=>Array.from(U).sort().join(","),[U]),o.useEffect(()=>{N==="analyze"&&(l.length>0||c.length>0)&&Kt()},[N,l.length,c.length]);const ea=o.useMemo(()=>t?.effectiveDate?new Date(t.effectiveDate):st?.effectiveDate?new Date(st.effectiveDate):new Date,[t,st]);o.useEffect(()=>{if(W==="zillow"&&tt&&ea){const pt=R1(tt,ea);z(pt),le({type:tt.metadata.geoType,name:tt.metadata.geoName,isMonthly:!0})}else if(W==="fhfa"&&Ce&&ea){const pt=C1(Ce,ea);z(pt),le({type:Ce.metadata.geoType,name:Ce.metadata.geoName,isAnnual:Ce.metadata.isAnnual??!1})}else(W==="zillow"&&!tt||W==="fhfa"&&!Ce)&&(z(null),le(null))},[Ce,tt,ea,W]);const tr=pt=>{const re=pt==="market"?M?.monthlyRatePct:oe?.monthlyRatePct;fe(pt);const qe=pt==="market"?"market":"sub-market";Be==="month-specific"?(ye(`Month-specific adjustments applied based on ${qe} price index per Fannie Mae guidelines. Non-linear price movement warranted individual month adjustments rather than a single flat rate.`),be("")):(ye(`Selected based on ${qe}
44 trend analysis`),re!=null&&(ce(re),Pe||be(re.toFixed(2))))};o.useEffect(()=>{if(se&&Be==="flat"){const pt=se==="market"?M?.monthlyRatePct:oe?.monthlyRatePct;pt!=null&&ce(pt)}},[se,M?.monthlyRatePct,oe?.monthlyRatePct,Be]),o.useEffect(()=>{se&&Ie!==null&&!H&&ye(`Selected based on ${se==="market"?"market":"sub-market"} trend analysis`)},[se,Ie]);const ir=pt=>{if(be(pt),Ie!==null){const re=parseFloat(pt);We(!isNaN(re)&&Math.abs(re-Ie)>.001)}},zs=async()=>{if(!(!se||Be==="flat"&&!ue)){lt(!0);try{const pt=new Date(ea);pt.setMonth(pt.getMonth()-(t?.windowMonths||12));const re=Be==="month-specific"?se==="market"?M?.adjustmentTable:oe?.adjustmentTable:null,qe={effectiveDate:Vi(ea,"yyyy-MM-dd"),windowStart:Vi(pt,"yyyy-MM-dd"),windowEnd:Vi(ea,"yyyy-MM-dd"),windowMonths:t?.windowMonths||12,marketSalesCount:j.salesCount-R.size,marketExcludedCount:R.size,marketRate:M?.monthlyRatePct??0,submarketSalesCount:O.salesCount-U.size,submarketExcludedCount:U.size,submarketRate:oe?.monthlyRatePct??0,hpiSource:$?W:null,hpiGeography:V?.name||null,hpiRate:$?.monthlyRatePct??null,selectedDataset:se,adjustmentRate:Be==="flat"?ue:null,rationale:H||"",rateMode:Be,adjustmentTable:re},Ze={marketConditions:!0,timeAdjustmentSupport:!0,reconciliation:M&&oe&&Math.sign(M.monthlyRatePct)!==Math.sign(oe.monthlyRatePct)},It=await fetch("/api/time-adj/narrative/generate",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({inputs:qe,sections:Ze})});if(It.ok){const Ne=await It.json();ne(Ne.narrative),v({title:"Narrative generated",description:"You can edit the text before saving."})}else{const Ne=await It.json().catch(()=>({error:"Unknown error"}));v({title:"Narrative generation failed",description:Ne.error||"Please try again or write your own narrative.",variant:"destructive"})}}catch(pt){console.error("Failed to generate narrative:",pt),v({title:"Narrative generation failed",description:"Network error. Please try again.",variant:"destructive"})}finally{lt(!1)}}},pr=(pt,re,qe)=>{ut(pt),He(re==="even"?"flat":"month-specific"),re==="even"&&be(qe.toFixed(2)),v({title:"Adjustments applied",description:`${pt.length} comps adjusted using ${re==="even"?"even rate":"month-by-month"} method`})};if(!(t?.isLocked??!1))return e.jsx(ja,{className:"border-slate-200",children:e.jsxs(Ta,{className:"p-6 text-center",children:[e.jsx(Hr,{className:"w-8 h-8 text-slate-400 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-slate-900 mb-2",children:"Lock Market First"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Draw your market area and apply filters in Property Lab, then lock to begin time adjustment analysis."})]})});const Ot=j.isLocked&&O.isLocked,_e=Ot&&(M||oe),ma=pt=>{pt==="analyze"&&!Ot||pt==="decide"&&!_e||x(pt)};return e.jsxs("div",{className:"h-full flex flex-col bg-slate-50 border-l-4 border-blue-500","data-testid":"embedded-time-vault",children:[!(Tt&&Ot)&&e.jsx("div",{className:"shrink-0 border-b border-slate-200 bg-gradient-to-r from-blue-50 to-white px-4 py-2",children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsxs("button",{onClick:()=>ma("lock"),className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium transition-colors ${N==="lock"?"bg-blue-100 text-blue-700":Ot?"bg-green-50 text-green-700 hover:bg-green-100":"text-slate-500"}`,"data-testid":"step-lock",children:[Ot?e.jsx(pc,{className:"w-3.5 h-3.5"}):e.jsx(Hr,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"1. Lock"})]}),e.jsx(fo,{className:"w-3.5 h-3.5 text-slate-300 shrink-0"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("button",{onClick:()=>ma("analyze"),disabled:!Ot,className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium transition-colors ${N==="analyze"?"bg-blue-100 text-blue-700":_e?"bg-green-50 text-green-700 hover:bg-green-100":Ot?"text-slate-500 hover:bg-slate-100":"text-slate-300 cursor-not-allowed"}`,"data-testid":"step-analyze",children:[_e?e.jsx(pc,{className:"w-3.5 h-3.5"}):e.jsx(Hh,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"2. Analyze"})]}),(N==="analyze"||N==="decide")&&e.jsxs("div",{className:"flex items-center gap-0.5 ml-1 p-0.5 bg-slate-100 rounded-md border border-slate-200",children:[e.jsxs("button",{onClick:()=>{b("market"),N==="decide"&&tr("market")},className:`px-2 py-1 text-xs font-medium rounded transition-colors ${y==="market"?"bg-white text-blue-700 shadow-sm":"text-slate-600 hover:text-slate-800"}`,"data-testid":"tab-market-inline",children:[e.jsx("span",{className:"hidden sm:inline",children:"Market"}),e.jsx("span",{className:"sm:hidden",children:"Mkt"}),e.jsx(kt,{variant:"secondary",className:"ml-1 text-[10px] px-1",children:l.length})]}),e.jsxs("button",{onClick:()=>{b("submarket"),N==="decide"&&tr("submarket")},className:`px-2 py-1 text-xs font-medium rounded transition-colors ${y==="submarket"?"bg-white text-blue-700 shadow-sm":"text-slate-600 hover:text-slate-800"}`,"data-testid":"tab-submarket-inline",children:[e.jsx("span",{className:"hidden sm:inline",children:"Sub-Mkt"}),e.jsx("span",{className:"sm:hidden",children:"Sub"}),e.jsx(kt,{variant:"secondary",className:"ml-1 text-[10px] px-1",children:c.length})]}),e.jsxs("button",{onClick:()=>b("hpi"),className:`px-2 py-1 text-xs font-medium rounded transition-colors ${y==="hpi"?"bg-white text-blue-700 shadow-sm":"text-slate-600 hover:text-slate-800"}`,"data-testid":"tab-hpi-inline",children:[e.jsx("span",{className:"hidden sm:inline",children:"Exter
44nal"}),e.jsx("span",{className:"sm:hidden",children:"HPI"})]})]})]}),e.jsx(fo,{className:"w-3.5 h-3.5 text-slate-300 shrink-0"}),e.jsxs("button",{onClick:()=>ma("decide"),disabled:!_e,className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium transition-colors ${N==="decide"?"bg-blue-100 text-blue-700":_e?"text-slate-500 hover:bg-slate-100":"text-slate-300 cursor-not-allowed"}`,"data-testid":"step-decide",children:[e.jsx(gn,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"3. Reconcile"})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto text-[10px] text-slate-400",children:[e.jsx("button",{onClick:()=>je(!Tt),className:`px-2 py-1 rounded text-xs font-medium transition-colors ${Tt?"bg-blue-100 text-blue-700":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,"data-testid":"toggle-wizard-mode",children:Tt?"Guided":"Classic"}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Vi(ea,"MMM d, yyyy")}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[t?.windowMonths||12,"mo"]}),st?.id&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{children:st.id.slice(0,8)})]})]})]})}),e.jsxs("div",{className:"flex-1 overflow-auto bg-slate-50",children:[Tt&&Ot&&e.jsx(qK,{marketAnalysis:M,submarketAnalysis:oe,externalAnalysis:Ce?C1(Ce,ea):null,externalSource:Ce?{name:Ce.metadata.geoName,type:Ce.metadata.geoType}:null,zillowAnalysis:tt?R1(tt,ea):null,zillowSource:tt?{name:tt.metadata.geoName,type:tt.metadata.geoType}:null,hpiSource:W,onHpiSourceChange:me,effectiveDate:ea,selectedComps:f,onApplyAdjustments:pr,isLoading:D,marketSalesData:l,submarketSalesData:c,marketExcludedIds:R,submarketExcludedIds:U,onMarketExclusionsChange:G,onSubmarketExclusionsChange:C,onRecomputeMarket:()=>Sa("market"),onRecomputeSubmarket:()=>Sa("submarket"),isRecomputing:F}),(!Tt||!Ot)&&e.jsxs("div",{className:"p-4",children:[N==="lock"&&e.jsxs("div",{className:"space-y-4 max-w-2xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-600",children:[e.jsx(Hr,{className:"w-4 h-4"}),e.jsx("span",{children:"Step 1: Lock your datasets"}),e.jsx(XK,{text:"Lock freezes your data so it won't change during analysis. You must lock both Market and Sub-Market before analyzing."})]}),e.jsx(ja,{className:j.isLocked?"border-green-200 bg-green-50":"",children:e.jsx(Ta,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Hh,{className:"w-5 h-5 text-slate-500"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-900",children:"Market"}),e.jsx("p",{className:"text-xs text-slate-500",children:j.isLocked?`${j.salesCount} sales locked`:`${s} sales available`})]})]}),j.isLocked?e.jsxs(kt,{className:"bg-green-100 text-green-700",children:[e.jsx(Hr,{className:"w-3 h-3 mr-1"}),"Locked"]}):e.jsxs(De,{size:"sm",onClick:Je,disabled:s===0,children:[e.jsx(Hr,{className:"w-3 h-3 mr-1"}),"Lock Market"]})]})})}),e.jsx(ja,{className:O.isLocked?"border-green-200 bg-green-50":"",children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(K0,{className:"w-5 h-5 text-slate-500"}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-slate-900",children:"Sub-Market"}),e.jsx("p",{className:"text-xs text-slate-500",children:O.isLocked?`${O.salesCount} sales locked`:`${r} sales available`})]})]}),O.isLocked?e.jsxs(kt,{className:"bg-green-100 text-green-700",children:[e.jsx(Hr,{className:"w-3 h-3 mr-1"}),"Locked"]}):e.jsxs(De,{size:"sm",onClick:ht,disabled:!j.isLocked||r===0,children:[e.jsx(Hr,{className:"w-3 h-3 mr-1"}),"Lock Sub-Market"]})]}),!j.isLocked&&e.jsx("p",{className:"text-xs text-slate-400 mt-2",children:"Lock Market first"})]})})]}),N==="analyze"&&e.jsxs("div",{className:"space-y-4",children:[y==="market"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(b1,{title:"Market Sales (Locked)",sales:l,excludedIds:R,onExclusionsChange:G,onRecompute:()=>Sa("market"),isRecomputing:F,lockedTotalCount:j.salesCount}),e.jsx(Dj,{data:M,isLoading:D||F,effectiveDate:ea})]}),y==="submarket"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(b1,{title:"Sub-Market Sales (Locked)",sales:c,excludedIds:U,onExclusionsChange:C,onRecompute:()=>Sa("submarket"),isRecomputing:F,lockedTotalCount:O.salesCount}),e.jsx(Dj,{data:oe,isLoading:D||F,effectiveDate:ea})]}),y==="hpi"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ja,{className:"bg-white border-slate-200",children:e.jsx(Ta,{className:"p-3",children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R0,{className:"w-4 h-4 text-slate-500"}),e.jsx("span",{className:"text-sm font-medium text-slate-700",children:"Source"}),e.jsxs("div",{className:"flex gap-1 p-1 bg-slate-100 rounded-lg",children:[e.jsx("button",{onClick:()=>me("zillow"),className:`px-2 py-1 text-xs font-medium rounded-md transition-colors ${W==="zillow"?"bg-white text-blue-700 shadow-sm":"text-slate-600 hover:text-slate-800"}`,"data-testid":"hpi-source-zillow",children:"Zillow"}),e.jsx("button",{onClick:()=>
44me("fhfa"),className:`px-2 py-1 text-xs font-medium rounded-md transition-colors ${W==="fhfa"?"bg-white text-blue-700 shadow-sm":"text-slate-600 hover:text-slate-800"}`,"data-testid":"hpi-source-fhfa",children:"FHFA"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-slate-700",children:"Range"}),e.jsxs("div",{className:"flex gap-1 p-1 bg-slate-100 rounded-lg",children:[e.jsx("button",{onClick:()=>pe(12),className:`px-2 py-1 text-xs font-medium rounded-md transition-colors ${Z===12?"bg-white text-blue-700 shadow-sm":"text-slate-600 hover:text-slate-800"}`,"data-testid":"hpi-range-1yr",children:"1-yr"}),e.jsx("button",{onClick:()=>pe(24),className:`px-2 py-1 text-xs font-medium rounded-md transition-colors ${Z===24?"bg-white text-blue-700 shadow-sm":"text-slate-600 hover:text-slate-800"}`,"data-testid":"hpi-range-2yr",children:"2-yr"}),e.jsx("button",{onClick:()=>pe(36),className:`px-2 py-1 text-xs font-medium rounded-md transition-colors ${Z===36?"bg-white text-blue-700 shadow-sm":"text-slate-600 hover:text-slate-800"}`,"data-testid":"hpi-range-3yr",children:"3-yr"})]})]})]})})}),e.jsx(ja,{className:"border-blue-200 bg-blue-50",children:e.jsx(Ta,{className:"p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(R0,{className:"w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium text-blue-800 text-sm",children:[W==="zillow"?"Zillow ZHVI":"FHFA HPI"," (",V?`${V.type==="zip"?"ZIP":V.type==="msa"||V.type==="metro"?"Metro":"State"}: ${V.name}${V.isAnnual?" (Annual)":V.isMonthly?" (Monthly)":""}`:"Loading...",")"]}),e.jsx("p",{className:"text-xs text-blue-700 mt-1",children:"This index reflects broader market trends and is provided for context. Final time adjustments should be supported by local sales when available."})]})]})})}),e.jsx(ja,{className:"bg-slate-50",children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(on,{className:"w-4 h-4 text-slate-500"}),e.jsxs("h4",{className:"font-medium text-slate-900 text-sm",children:["About ",W==="zillow"?"Zillow ZHVI":"FHFA HPI"]})]}),e.jsxs("ul",{className:"text-xs text-slate-600 space-y-1 list-disc list-inside",children:[W==="zillow"?e.jsxs(e.Fragment,{children:[e.jsxs("li",{children:["Source: Zillow Home Value Index — updated ",e.jsx("strong",{children:"monthly"})," (16th of each month)"]}),e.jsx("li",{children:"Data type: Modeled home values (AVM-based), not pure transaction data"}),e.jsxs("li",{children:["Geography: ",V?V.type==="zip"?"ZIP Code level (most granular)":V.type==="metro"?"Metro area":"State-level":"Loading..."]}),e.jsxs("li",{children:["Benefit: ",e.jsx("strong",{children:"Fresher data"})," — typically within 1 month of current date"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("li",{children:["Source: FHFA House Price Index — ",V?V.isAnnual?"annual":"quarterly":"—"," data"]}),e.jsx("li",{children:"Data type: Transaction-based (conforming loans only)"}),e.jsxs("li",{children:["Geography: ",V?V.type==="zip"?"ZIP Code level (most granular)":V.type==="msa"?"Metropolitan Statistical Area (MSA)":"State-level":"Loading..."]}),e.jsxs("li",{children:["Benefit: ",e.jsx("strong",{children:"Fannie Mae compliant"})," — regulator-backed data per B4-1.3-09"]}),V?.isAnnual&&e.jsx("li",{children:"Note: ZIP code data is annual — less precise than quarterly MLS data"})]}),e.jsxs("li",{children:["This is ",e.jsx("strong",{children:"reference data only"})," — not based on local MLS sales"]})]})]})}),(()=>{const pt=W==="zillow"?Ve||!vt?.allReady:zt||!na?.allReady,re=W==="zillow"?rt:Fe;return!re&&((W==="zillow"?it:St)||pt&&!$)?e.jsx(ja,{className:"border-blue-200 bg-blue-50/50",children:e.jsx(Ta,{className:"p-6 text-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-2 border-blue-400 border-t-transparent rounded-full animate-spin"}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium text-blue-900",children:["Loading ",W==="zillow"?"Zillow":"FHFA"," Data"]}),e.jsx("p",{className:"text-sm text-blue-700 mt-1",children:W==="zillow"?vt?.allReady?"Fetching ZHVI data for your location...":"Downloading Zillow data (first time only)...":na?.allReady?"Fetching index data for your location...":"Downloading FHFA data (first time only, may take 30-60 seconds)..."}),W==="zillow"&&!vt?.allReady&&e.jsxs("p",{className:"text-xs text-blue-500 mt-2",children:[vt?.stateReady?"✓ State data ready":"⏳ Loading state data..."," • ",vt?.zipReady?"✓ ZIP data ready":"⏳ Loading ZIP data..."]}),W==="fhfa"&&!na?.allReady&&e.jsxs("p",{className:"text-xs text-blue-500 mt-2",children:[na?.stateReady?"✓ State data ready":"⏳ Loading state data..."," • ",na?.zipReady?"✓ ZIP data ready":"⏳ Loading ZIP data..."]})]})]})})}):re&&!$?e.jsx(ja,{className:"border-amber-200 bg-amber-50/50","data-testid":"card-hpi-sync-timeout",children:e.jsxs(Ta,{className:"p-6 text-center",children:[e.jsx(Ns,{className:"w-8 h-8 text-amber-500 mx-auto mb-3"}
44),e.jsxs("h4",{className:"font-medium text-amber-900 mb-2",children:[W==="zillow"?"Zillow":"FHFA"," Data Sync Timed Out"]}),e.jsxs("p",{className:"text-sm text-amber-700",children:["We waited about 2 minutes for ",W==="zillow"?"Zillow ZHVI":"FHFA HPI"," data to finish syncing for this location and didn't get a response. The download may still be running in the background — try again in a moment."]}),e.jsx("button",{type:"button","data-testid":"button-hpi-sync-retry",className:"mt-4 inline-flex items-center px-3 py-1.5 text-xs font-medium rounded-md border border-amber-300 bg-white text-amber-800 hover:bg-amber-100",onClick:()=>{W==="zillow"?(os.current={attempt:0,start:null},At.current={attempt:0,start:null},$t(!1),sa(!0),S.invalidateQueries({queryKey:["zillow-cache-status"]}),S.invalidateQueries({queryKey:["zillow-zhvi"]})):(qa.current={attempt:0,start:null},ya.current={attempt:0,start:null},Oe(!1),Ua(!0),S.invalidateQueries({queryKey:["fhfa-cache-status"]}),S.invalidateQueries({queryKey:["fhfa-hpi"]}))},children:"Retry"})]})}):$?e.jsx(Dj,{data:$,isLoading:!1,effectiveDate:ea,isHpiData:!0}):e.jsx(ja,{children:e.jsxs(Ta,{className:"p-6 text-center",children:[e.jsx(Ns,{className:"w-8 h-8 text-amber-500 mx-auto mb-3"}),e.jsx("h4",{className:"font-medium text-slate-900 mb-2",children:"External HPI Unavailable"}),e.jsx("p",{className:"text-sm text-slate-500",children:!d&&!u&&!p?"Subject property location is required to fetch HPI data.":`${W==="zillow"?"Zillow ZHVI":"FHFA HPI"} data is not available for this location.`}),W==="zillow"&&e.jsx("p",{className:"text-xs text-slate-400 mt-2",children:"Try switching to FHFA HPI for broader coverage"})]})})})()]}),e.jsx("div",{className:"flex items-center justify-center",children:e.jsxs("p",{className:"text-xs text-slate-400",children:[e.jsx(Hr,{className:"w-3 h-3 inline mr-1"}),"Datasets locked. Click ",e.jsx("span",{className:"font-medium",children:"3. Reconcile"})," above when ready."]})})]}),N==="decide"&&e.jsx("div",{className:"h-full",children:e.jsxs("div",{className:"grid grid-cols-12 gap-4 h-full",children:[e.jsxs("div",{className:"col-span-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[e.jsx("h3",{className:"text-sm font-medium text-slate-700",children:"Select Dataset"}),e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("button",{className:"text-slate-400 hover:text-slate-600","data-testid":"tooltip-trend-info",children:e.jsx(on,{className:"w-3.5 h-3.5"})})}),e.jsxs(Wa,{side:"right",className:"max-w-xs text-xs",children:[e.jsx("p",{className:"font-medium mb-1",children:"Trend Classification"}),e.jsx("p",{children:"Monthly rates within ±0.25% are considered stable. Rates above or below this range suggest increasing or declining conditions. Appraiser judgment governs final conclusions."})]})]})})]}),e.jsx(ja,{className:`cursor-pointer transition-all ${se==="market"?"border-blue-500 ring-2 ring-blue-200 bg-blue-50":"hover:border-slate-300"}`,onClick:()=>tr("market"),"data-testid":"card-dataset-market",children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Hh,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"font-medium text-slate-900",children:"Market"}),se==="market"&&e.jsx(pc,{className:"w-4 h-4 text-blue-600 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-xs text-slate-600",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Sales included:"}),e.jsx("span",{className:"font-medium",children:j.salesCount-R.size})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Monthly rate:"}),e.jsxs("span",{className:`font-medium ${(M?.monthlyRatePct??0)>=0?"text-green-600":"text-red-600"}`,children:[M?.monthlyRatePct?.toFixed(2)||"0.00","%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Reliable months:"}),e.jsx("span",{className:"font-medium",children:M?.reliableMonthsCount??"—"})]})]})]})}),e.jsx(ja,{className:`cursor-pointer transition-all ${se==="submarket"?"border-blue-500 ring-2 ring-blue-200 bg-blue-50":"hover:border-slate-300"}`,onClick:()=>tr("submarket"),"data-testid":"card-dataset-submarket",children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(K0,{className:"w-4 h-4 text-purple-600"}),e.jsx("span",{className:"font-medium text-slate-900",children:"Sub-Market"}),se==="submarket"&&e.jsx(pc,{className:"w-4 h-4 text-blue-600 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-xs text-slate-600",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Sales included:"}),e.jsx("span",{className:"font-medium",children:O.salesCount-U.size})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Monthly rate:"}),e.jsxs("span",{className:`font-medium ${(oe?.monthlyRatePct??0)>=0?"text-green-600":"text-red-600"}`,children:[oe?.monthlyRatePct?.toFixed(2)||"0.00","%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Reliable months:"}),e.jsx("span",{className:"font-medium",children:oe?.reliableMonthsCount??"—"})]})]})]})}),$&&e.jsx(ja,{className:"border-dashed opacity-75",children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(R0,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"font-medium text-slate-700 text-sm",children:[W==="zillow"?"Zillow":"FHFA"," Reference"]})]}),e.jsxs("div",{className:"space-y-1 text-xs text-slate-500",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Geography:"}),e.jsx("span",{className:"font-medium",children:V?.name||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Monthly rate:"}),e.jsxs("span",{className:"font-medium",children:[$.monthlyRatePct?.toFixed(2)||"0.00","%"]})]})]}),e.jsx("p",{className:"text-xs text-slate-400 mt-2 italic",children:"For reference only — not selectable"})]})})]}),e.jsxs("div",{className:"col-span-5 space-y-4",children:[e.jsx(ja,{children:e.jsxs(Ta,{className:"p-4",children:[e.jsx(Ja,{className:"text-sm font-medium mb-3 block",children:"Adjustment Mode"}),e.jsxs(D$,{value:Be,onValueChange:pt=>{const re=pt;if(He(re),!!se)if(re==="month-specific")ye(`Month-specific adjustments applied based on ${se==="market"?"market":"sub-market"} price index per Fannie Mae guidelines. Non-linear price movement warranted individual month adjustments rather than a single flat rate.`),be("");else{const qe=se==="market"?M?.monthlyRatePct:oe?.monthlyRatePct;qe!=null&&(ce(qe),Pe||be(qe.toFixed(2))),ye(`Selected based on ${se==="market"?"market":"sub-market"}
44 trend analysis`)}},className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(YE,{value:"flat",id:"rate-flat"}),e.jsx(Ja,{htmlFor:"rate-flat",className:"font-normal cursor-pointer text-sm",children:"Flat Monthly Rate"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(YE,{value:"month-specific",id:"rate-specific"}),e.jsx(Ja,{htmlFor:"rate-specific",className:"font-normal cursor-pointer text-sm",children:"Month-Specific (from table)"})]})]})]})}),Be==="flat"&&e.jsx(ja,{children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(Ja,{htmlFor:"adjustment-rate",className:"text-sm font-medium",children:"Monthly Adjustment Rate"}),Pe&&e.jsxs(kt,{variant:"outline",className:"text-amber-600 border-amber-300 bg-amber-50",children:[e.jsx(SI,{className:"w-3 h-3 mr-1"}),"Override"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{id:"adjustment-rate",type:"number",step:"0.01",placeholder:"0.00",value:ue,onChange:pt=>ir(pt.target.value),className:`w-28 text-lg font-medium ${Pe?"border-amber-300":""}`,"data-testid":"input-rate"}),e.jsx("span",{className:"text-sm text-slate-500",children:"% per month"})]}),se&&Ie!==null&&e.jsxs("p",{className:"text-xs text-slate-400 mt-2",children:["Auto-filled from ",se==="market"?"Market":"Sub-Market",": ",Ie.toFixed(2),"%/mo"]}),!se&&e.jsx("p",{className:"text-xs text-amber-600 mt-2",children:"Select a dataset to auto-fill the rate"})]})}),Be==="month-specific"&&e.jsx(ja,{children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx(Ja,{className:"text-sm font-medium",children:"Month-by-Month Adjustments"}),se&&e.jsxs(kt,{variant:"secondary",className:"text-xs",children:[se==="market"?"Market":"Sub-Market"," Dataset"]})]}),se?e.jsx("div",{className:"max-h-48 overflow-y-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-slate-50 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-2 font-medium",children:"Month"}),e.jsx("th",{className:"text-right p-2 font-medium",children:"Adjustment"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Direction"})]})}),e.jsx("tbody",{children:(se==="market"?M?.adjustmentTable:oe?.adjustmentTable)?.map((pt,re)=>e.jsxs("tr",{className:`border-t ${pt.isAnchor?"bg-blue-50 font-medium":""}`,children:[e.jsxs("td",{className:"p-2",children:[pt.month,pt.isAnchor&&e.jsx("span",{className:"ml-1 text-blue-600",children:"(Anchor)"})]}),e.jsxs("td",{className:`p-2 text-right font-medium ${pt.adjustmentPct>0?"text-green-600":pt.adjustmentPct<0?"text-red-600":"text-slate-600"}`,children:[pt.adjustmentPct>0?"+":"",pt.adjustmentPct.toFixed(1),"%"]}),e.jsx("td",{className:"p-2 text-slate-500",children:pt.isAnchor?"—":pt.adjustmentPct>0?"Add to older sales":pt.adjustmentPct<0?"Subtract from newer":"No adjustment"})]},re))||e.jsx("tr",{children:e.jsx("td",{colSpan:3,className:"p-2 text-slate-400 text-center",children:"No adjustment data available"})})})]})}):e.jsx("p",{className:"text-xs text-amber-600",children:"Select a dataset (Market or Sub-Market) to see month-by-month adjustments"}),e.jsx("p",{className:"text-xs text-slate-400 mt-3",children:"Apply each month's adjustment based on comparable's contract date. Effective date month = 0%."})]})}),e.jsx(ja,{children:e.jsxs(Ta,{className:"p-4",children:[e.jsx(Ja,{htmlFor:"rationale",className:"text-sm font-medium",children:"Rationale (optional)"}),e.jsx(yi,{id:"rationale",placeholder:"Why this rate makes sense for the subject property...",value:H,onChange:pt=>ye(pt.target.value),className:"mt-2",rows:2,"data-testid":"input-rationale"})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(De,{variant:"outline",size:"sm",onClick:zs,disabled:!se||Be==="flat"&&!ue||Me,"data-testid":"btn-generate-narrative",children:[Me?"Generating...":"Generate Narrative",e.jsx(gn,{className:"w-3 h-3 ml-1"})]}),e.jsxs(De,{size:"sm",onClick:Qt,disabled:!se||Be==="flat"&&!ue||de,"data-testid":"btn-save-decision",children:[de?"Saving...":"Save Decision",e.jsx(pc,{className:"w-3 h-3 ml-1"})]})]})]}),e.jsx("div",{className:"col-span-4",children:e.jsx(ja,{className:"h-full",children:e.jsxs(Ta,{className:"p-4 h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx(Ja,{className:"text-sm font-medium",children:"Generated Narrative"}),Re&&e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>navigator.clipboard.writeText(Re),className:"h-6 text-xs",children:"Copy"})]}),Re?e.jsx(yi,{value:Re,onChange:pt=>ne(pt.target.value),className:"flex-1 min-h-[200px] text-sm",placeholder:"Narrative will appear here after generation...","data-testid":"textarea-narrative"}):e.jsx("div",{className:"flex-1 flex items-center justify-center text-center p-6 bg-slate-50 rounded-lg border border-dashed border-slate-200",children:e.jsxs("div",{children:[e.jsx(gn,{className:"w-8 h-8 text-slate-300 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-slate-500",children:'Select a dataset and click "Generate Narrative" to create your report text.'})]})})]})})})]})})]})]})]})}const e9={C1:"C1 – New",C2:"C2 – Like New",C3:"C3 – Good",C4:"C4 – Average",C5:"C5 – Fair",C6:"C6 – Poor"},t9={Q1:"Q1 – Luxury",Q2:"Q2 – High",Q3:"Q3 – Above Avg",Q4:"Q4 – Average",Q5:"Q5 – Fair",Q6:"Q6 – Basic"},a9=["C1","C2","C3","C4","C5","C6"],s9=["Q1","Q2","Q3","Q4","Q5","Q6"];function r9(t){const a=t.match(/\d/);return a?parseInt(a[0],10):3}function n9(t){return{high:"bg-green-100 text-green-700 border-green-200",medium:"bg-amber-100 text-amber-700 border-amber-200",low:"bg-red-100 text-red-700 border-red-200"}[t]}function i9(t,a){const s=a==="condition"?a9:s9,r={};
44return s.forEach(n=>r[n]=[]),t.forEach(n=>{const i=a==="condition"?n.condition:n.quality;i&&r[i]!==void 0&&n.price>0&&r[i].push(n.price)}),s.map(n=>{const l=[...r[n]||[]].sort((p,u)=>p-u),c=l.length>0?l[Math.floor(l.length/2)]:0,d=l.length>0?Math.round(l.reduce((p,u)=>p+u,0)/l.length):0;return{rating:n,count:l.length,medianPrice:c,avgPrice:d}})}function o9({active:t,payload:a,label:s}){if(!t||!a?.length)return null;const r=a[0]?.payload;return r?e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg shadow-lg p-3 text-xs",children:[e.jsx("div",{className:"font-semibold text-slate-800 mb-1",children:r.rating}),e.jsxs("div",{className:"text-slate-600",children:["Median Price: ",e.jsxs("span",{className:"font-medium",children:["$",r.medianPrice.toLocaleString()]})]}),e.jsxs("div",{className:"text-slate-500",children:[r.count," sale",r.count!==1?"s":""]})]}):null}function l9({avmResults:t,advisorData:a,selectedComps:s,onLockRate:r,lockedConditionRate:n,lockedQualityRate:i}){const[l,c]=o.useState("condition"),[d,p]=o.useState("chart"),[u,m]=o.useState(!1),[h,f]=o.useState(""),[v,S]=o.useState(""),N=t?.adjustmentRates,x=N?.medianPrice||t?.marketStats?.medianPrice||0,y=t?.verifiedSubject?.condition||"C3",b=t?.verifiedSubject?.quality||"Q3",j=N?.conditionStats,T=N?.qualityStats,O=x<3e5,E=x>=3e5&&x<8e5,R=o.useMemo(()=>{if(O)return 7500;const se=N?.conditionPercentPerLevel||0;return N?.conditionDollarPerLevel||Math.round(x*se)},[N,x,O]),G=o.useMemo(()=>{if(O)return 6e3;const se=N?.qualityPercentPerLevel||0;return N?.qualityDollarPerLevel||Math.round(x*se)},[N,x,O]),U=j?.confidence||"medium",C=T?.confidence||"medium",F=l==="condition"?R:G,A=l==="condition"?U:C,M=l==="condition"?y:b,B=l==="condition"?e9:t9,oe=l==="condition"?j?.sampleSize||0:T?.sampleSize||0,ae=o.useMemo(()=>{const se=s.map(fe=>({condition:fe.condition||"C3",quality:fe.quality||"Q3",price:fe.price||fe.salePrice||0}));return t?.rankedComps&&t.rankedComps.forEach(fe=>{se.find(ue=>ue.price===fe.salePrice)||se.push({condition:"C3",quality:"Q3",price:fe.salePrice})}),se},[s,t]),D=o.useMemo(()=>i9(ae,l),[ae,l]),_=o.useMemo(()=>l==="condition"?s.map(se=>se.condition||"C3"):s.map(se=>se.quality||"Q3"),[s,l]),$=o.useMemo(()=>{const se=_.map(r9);return se.length===0?{min:3,max:3}:{min:Math.min(...se),max:Math.max(...se)}},[_]),z=o.useMemo(()=>l==="condition"?O?"Low tier (<$300K): Fixed $7,500/level":E?`Mid tier ($300K–$800K): 6% of median = $${Math.round(x*.06).toLocaleString()}/level`:`High tier (>$800K): 7% of median = $${Math.round(x*.07).toLocaleString()}/level`:O?"Low tier (<$300K): Fixed $6,000/level":E?`Mid tier ($300K–$800K): 5% of median = $${Math.round(x*.05).toLocaleString()}/level`:`High tier (>$800K): 6% of median = $${Math.round(x*.06).toLocaleString()}/level`,[l,O,E,x]),V=o.useMemo(()=>{const se=A==="high"?.25:A==="medium"?.35:.5;return{low:Math.round(F*(1-se)),high:Math.round(F*(1+se))}},[F,A]),le=se=>{l==="condition"?f(se):S(se)},W=()=>{const fe=parseInt(l==="condition"?h:v,10),ue=!isNaN(fe)&&fe>0?fe:F;r?.(l,ue)},me=l==="condition"?h:v,Z=l==="condition"?n:i,pe=Z!=null;return t?e.jsxs("div",{className:"p-6 space-y-6","data-testid":"embedded-condition-analysis",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold text-slate-800 flex items-center gap-2",children:["CONDITION & QUALITY",e.jsxs(kt,{className:Q("text-xs",n9(A)),"data-testid":"condqual-confidence",children:[A.charAt(0).toUpperCase()+A.slice(1)," Confidence"]})]}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:["UAD-based adjustment rates by price tier • Subject: ",y,", ",b]})]}),e.jsx(up,{value:l,onValueChange:se=>c(se),children:e.jsxs(pp,{className:"h-8",children:[e.jsx($n,{value:"condition",className:"text-xs px-3 py-1","data-testid":"toggle-condition",children:"Condition"}),e.jsx($n,{value:"quality",className:"text-xs px-3 py-1","data-testid":"toggle-quality",children:"Quality"})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx("div",{className:"lg:col-span-2 space-y-4",children:e.jsx(ja,{className:"border-slate-200",children:e.jsxs(Ta,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"text-3xl font-bold text-slate-900","data-testid":"condqual-rate",children:["$",F.toLocaleStr
44ing(),e.jsx("span",{className:"text-base font-normal text-slate-500",children:"/level"})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2 leading-relaxed","data-testid":"condqual-plain-english",children:l==="condition"?`In this market, each condition level difference (e.g., C3 to C4) is worth about $${F.toLocaleString()}`:`In this market, each quality level difference (e.g., Q3 to Q4) is worth about $${F.toLocaleString()}`})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-sm",children:[e.jsxs("div",{className:"bg-slate-50 rounded-lg px-3 py-2 text-center",children:[e.jsx("div",{className:"text-xs text-slate-500",children:"Subject"}),e.jsx("div",{className:"font-semibold text-slate-800","data-testid":"condqual-subject-rating",children:M})]}),e.jsx("div",{className:"text-slate-400",children:"vs"}),e.jsxs("div",{className:"bg-slate-50 rounded-lg px-3 py-2 text-center",children:[e.jsx("div",{className:"text-xs text-slate-500",children:"Comps"}),e.jsx("div",{className:"font-semibold text-slate-800","data-testid":"condqual-comp-range",children:l==="condition"?`C${$.min} – C${$.max}`:`Q${$.min} – Q${$.max}`})]})]}),e.jsxs("button",{onClick:()=>m(!u),className:"w-full flex items-center justify-between text-xs text-slate-500 hover:text-slate-700 pt-2 border-t","data-testid":"condqual-toggle-details",children:[e.jsx("span",{children:"See derivation details"}),u?e.jsx(Du,{className:"w-3 h-3"}):e.jsx(Rr,{className:"w-3 h-3"})]}),u&&e.jsxs("div",{className:"space-y-2 text-xs text-slate-600 bg-slate-50 rounded-lg p-3","data-testid":"condqual-details",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Derivation"}),e.jsx("span",{className:"font-medium",children:"UAD Tiered Policy"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Market Median"}),e.jsxs("span",{className:"font-medium",children:["$",x.toLocaleString()]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Price Tier"}),e.jsx("span",{className:"font-medium",children:O?"Low (<$300K)":E?"Mid ($300K–$800K)":"High (>$800K)"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Sample Size"}),e.jsxs("span",{className:"font-medium",children:[oe," sales"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"90% Confidence Range"}),e.jsxs("span",{className:"font-medium",children:["$",V.low.toLocaleString()," – $",V.high.toLocaleString(),"/level"]})]}),e.jsxs("div",{className:"mt-2 text-[11px] text-slate-500 italic",children:[z,". You're statistically supported to use any rate in this range."]})]})]})})}),e.jsx("div",{className:"lg:col-span-3",children:e.jsx(ja,{className:"border-slate-200",children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"text-xs font-medium text-slate-500",children:[l==="condition"?"Condition":"Quality"," Rating Distribution"]}),e.jsx(up,{value:d,onValueChange:se=>p(se),children:e.jsxs(pp,{className:"h-7",children:[e.jsxs($n,{value:"chart",className:"text-xs px-2 py-1 h-5",children:[e.jsx(Pl,{className:"w-3 h-3 mr-1"}),"Chart"]}),e.jsxs($n,{value:"table",className:"text-xs px-2 py-1 h-5",children:[e.jsx(SN,{className:"w-3 h-3 mr-1"}),"Table"]})]})})]}),d==="chart"?e.jsxs("div",{"data-testid":"condqual-chart",children:[e.jsx(cc,{width:"100%",height:280,children:e.jsxs(QS,{data:D,margin:{top:20,right:20,left:10,bottom:20},children:[e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0",vertical:!1}),e.jsx(dc,{dataKey:"rating",tick:{fontSize:11,fill:"#64748b"},axisLine:{stroke:"#cbd5e1"}}),e.jsx(ql,{tick:{fontSize:10,fill:"#64748b"},axisLine:{stroke:"#cbd5e1"},tickFormatter:se=>se>=1e3?`$${(se/1e3).toFixed(0)}K`:`$${se}`,width:55}),e.jsx(uc,{content:e.jsx(o9,{})}),e.jsx(Rh,{dataKey:"medianPrice",radius:[4,4,0,0],maxBarSize:48,children:D.map(se=>{const fe=se.rating===M,ue=_.includes(se.rating);return e.jsx($x,{fill:fe?"#f59e0b":ue?"#3b82f6":se.count>0?"#94a3b8":"#e2e8f0",stroke:fe?"#d97706":ue?"#2563eb":"transparent",strokeWidth:fe||ue?2:0},se.rating)})}),D.map(se=>se.count>0?e.jsx(wu,{x:se.rating,stroke:"transparent",ifOverflow:"extendDomain",children:e.jsx(C0,{value:`n=${se.count}`,position:"top",fill:"#64748b",fontSize:9})},`label-${se.rating}`):null)]})}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[10px] text-slate-500 mt-1 border-t pt-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-amber-500"}),e.jsxs("span",{children:["Subject (",M,")"]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-blue-500"}),e.jsx("span",{children:"Grid Comps"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-3 rounded bg-slate-400"}),e.jsx("span",{children:"Market Pool"})]})]})]}):e.jsx(Qd,{className:"h-[300px]","data-testid":"condqual-table",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 px-3 text-xs font-medium text-slate-500",children:"Rating"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"Sales"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"Median Price"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"Avg Price"})]})}),e.jsx("tbody",{children:D.map(se=>{const fe=se.rating===M,ue=_.includes(se.rating);return e.jsxs("tr",{className:Q("border-b",fe&&"bg-amber-50",ue&&!fe&&"bg-blue-50"),children:[e.jsxs("td",{className:"py-2 px-3 text-slate-700",children:[B[se.rating]||se.rating,fe&&e.jsx(kt,{variant:"outline",className:"ml-2 text-[9px] px-1 py-0 bg-amber-100 text-amber-700 border-amber-300",children:"Subject"}),ue&&!fe&&e.jsx(kt,{variant:"outline",className:"ml-2 text-[9px] px-1 py-0 bg-blue-100 text-blue-700 border-blue-300",children:"Comp"})]}),e.jsx("td",{className:"py-2 px-3 text-right text-slate-600",children:se.count}),e.jsx("td",{className:"py-2 px-3 text-right font-medium text-slate-800",children:se.medianPrice>
440?`$${se.medianPrice.toLocaleString()}`:"—"}),e.jsx("td",{className:"py-2 px-3 text-right text-slate-600",children:se.avgPrice>0?`$${se.avgPrice.toLocaleString()}`:"—"})]},se.rating)})})]})})]})})})]}),e.jsx(ja,{className:"border-slate-200 bg-slate-50","data-testid":"condqual-reconciliation",children:e.jsxs(Ta,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(kr,{className:"w-4 h-4 text-green-600"}),e.jsx("span",{className:"text-sm font-semibold text-slate-800",children:"Selected Adjustment"}),pe&&e.jsxs(kt,{className:"bg-green-100 text-green-700 border-green-200 text-[10px]",children:[e.jsx(Hr,{className:"w-3 h-3 mr-1"}),"Locked"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"text-xs text-slate-500 mb-1 block",children:[l==="condition"?"Condition":"Quality"," Rate ($/level)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ze,{type:"number",value:me||String(F),onChange:se=>le(se.target.value),className:"h-9 text-sm font-mono w-32","data-testid":`input-${l}-rate`}),e.jsxs("div",{className:"flex-1",children:[e.jsx(IN,{value:[parseInt(me||String(F),10)||F],min:V.low,max:V.high,step:Math.max(100,Math.round((V.high-V.low)/50)),onValueChange:([se])=>le(String(Math.round(se))),className:"w-full","data-testid":`slider-${l}-rate`}),e.jsxs("div",{className:"flex justify-between text-[9px] text-slate-400 mt-0.5",children:[e.jsxs("span",{children:["$",V.low.toLocaleString()]}),e.jsxs("span",{children:["$",V.high.toLocaleString()]})]})]})]})]}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx("span",{className:"text-[10px] text-slate-400",children:"Evidence:"}),e.jsx(kt,{variant:"outline",className:"text-[9px] px-1.5 py-0 border-indigo-200 text-indigo-600",children:"UAD Policy"}),oe>0&&e.jsxs(kt,{variant:"outline",className:"text-[9px] px-1.5 py-0 border-blue-200 text-blue-600",children:[oe," Sales"]})]})}),e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{onClick:W,size:"sm",variant:pe?"secondary":"default",className:"shrink-0","data-testid":`button-lock-${l}-rate`,children:pe?e.jsxs(e.Fragment,{children:[e.jsx(kr,{className:"w-3.5 h-3.5 mr-1"}),"Locked: $",(Z||0).toLocaleString(),"/level"]}):e.jsxs(e.Fragment,{children:[e.jsx(Hr,{className:"w-3.5 h-3.5 mr-1"}),"Use This Rate"]})})}),e.jsx(Wa,{children:e.jsxs("p",{className:"text-xs",children:["Lock $",F.toLocaleString(),"/level for ",l," adjustments"]})})]})})]})]})]})}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 flex items-start gap-2",children:[e.jsx(on,{className:"w-4 h-4 text-blue-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-blue-700",children:[e.jsx("strong",{children:"How it works:"})," Condition and quality rates follow Fannie Mae's UAD tiered methodology. Each level difference between subject and comp is multiplied by the rate.",l==="condition"?` For example, if the subject is C3 and a comp is C5, the adjustment = 2 levels × $${F.toLocaleString()} = $${(F*2).toLocaleString()}.`:` For example, if the subject is Q4 and a comp is Q2, the adjustment = 2 levels × $${F.toLocaleString()} = $${(F*2).toLocaleString()}.`]})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 gap-3","data-testid":"condqual-no-data",children:[e.jsx(Di,{className:"w-10 h-10 text-slate-300"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Run AVM analysis first to see condition & quality data."})]})}function c9(t){return{high:"bg-green-100 text-green-700 border-green-200",medium:"bg-amber-100 text-amber-700 border-amber-200",low:"bg-red-100 text-red-700 border-red-200"}[t]}function d9(t){return`$${Math.abs(Math.round(t)).toLocaleString()}`}function u9({advisorData:t,adjustmentRates:a,verifiedSubject:s,selectedComps:r,marketLocked:n,onRateChange:i,glaBand:l}){const[c,d]=o.useState(!1),[p,u]=o.useState("chart"),m=a?.glaDollarPerSqft??0,h=t?.rateDetails?.gla,f=t?.marketPoolScatter??[],v=t?.regressionLine,S=o.useMemo(()=>
44{if(h){const A=h.rSquared??0;return A>=.5&&h.sampleSize>=30?"high":A>=.2&&h.sampleSize>=10?"medium":"low"}return t&&t.marketPoolSize>=30?"medium":"low"},[h,t]),N=o.useMemo(()=>{if(h?.confidenceRange)return h.confidenceRange;const A=S==="high"?.15:S==="medium"?.25:.4;return{low:Math.round(m*(1-A)),high:Math.round(m*(1+A))}},[h,m,S]),[x,y]=o.useState(Math.round(m)),b=s?.gla??0,j=o.useMemo(()=>{if(r.length===0)return{min:0,max:0};const A=r.map(M=>M.gla||0).filter(M=>M>0);return{min:Math.min(...A),max:Math.max(...A)}},[r]),T=o.useMemo(()=>{const A=[];if(f.forEach(M=>{M.gla>0&&M.price>0&&A.push({gla:M.gla,price:M.price,type:"market"})}),r.forEach(M=>{const B=M.gla||0,oe=M.price||M.salePrice||M.closePrice||0;if(B>0&&oe>0){const ae=(M.address||"").split(",")[0].replace(/^\d+\s/,"").slice(0,15);A.push({gla:B,price:oe,label:ae,type:"comp"})}}),b>0){const M=s?.lastSalePrice??(a?t?.medianPrice??0:0);M>0&&A.push({gla:b,price:M,label:"Subject",type:"subject"})}return A},[f,r,b,s,a,t]),O=o.useMemo(()=>{if(!v)return[];const A=T.map(_=>_.gla).filter(_=>_>0);if(A.length===0)return[];const M=Math.min(...A),B=Math.max(...A),oe=20,ae=(B-M)/oe,D=[];for(let _=0;_<=oe;_++){const $=M+ae*_;D.push({gla:Math.round($),regressionPrice:Math.round(v.intercept+v.slope*$)})}return D},[v,T]),E=o.useMemo(()=>{const A=T.map(B=>B.gla).filter(B=>B>0);if(A.length===0)return[0,5e3];const M=(Math.max(...A)-Math.min(...A))*.1||200;return[Math.max(0,Math.min(...A)-M),Math.max(...A)+M]},[T]),R=o.useMemo(()=>{const A=T.map(B=>B.price).filter(B=>B>0);if(A.length===0)return[0,1e6];const M=(Math.max(...A)-Math.min(...A))*.1||5e4;return[Math.max(0,Math.min(...A)-M),Math.max(...A)+M]},[T]),G=T.filter(A=>A.type==="market"),U=T.filter(A=>A.type==="comp"),C=T.filter(A=>A.type==="subject"),F=A=>{y(A),i?.(A)};return n?a?e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 p-6","data-testid":"gla-analysis",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ko,{className:"text-base flex items-center gap-2",children:[e.jsx(Um,{className:"w-5 h-5 text-blue-600"}),"GLA Adjustment"]}),e.jsxs(kt,{className:Q("text-xs capitalize",c9(S)),"data-testid":"badge-gla-confidence",children:[S," Confidence"]})]})}),e.jsxs(Ta,{className:"space-y-4",children:[e.jsxs("div",{className:"text-center","data-testid":"text-gla-rate",children:[e.jsxs("div",{className:"text-4xl font-bold text-slate-900",children:["$",Math.round(m).toLocaleString(),e.jsx("span",{className:"text-lg font-normal text-slate-500",children:"/sqft"})]}),e.jsxs("p",{className:"text-sm text-slate-600 mt-2","data-testid":"text-gla-plain-english",children:["We analyzed ",t?.marketPoolSize??h?.sampleSize??0," sales and found each square foot difference is worth about $",Math.round(m).toLocaleString()]})]}),e.jsx("div",{className:"bg-slate-50 rounded-lg p-3 border","data-testid":"text-gla-subject-range",children:e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500",children:"Subject: "}),e.jsxs("span",{className:"font-semibold text-slate-800",children:[b.toLocaleString()," sqft"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500",children:"Comps: "}),e.jsx("span",{className:"font-semibold text-slate-800",children:j.min>0?`${j.min.toLocaleString()} – ${j.max.toLocaleString()} sqft`:"N/A"})]})]})}),e.jsxs("div",{children:[e.jsxs("button",{className:"flex items-center gap-1 text-xs font-medium text-blue-600 hover:text-blue-700",onClick:()=>d(!c),"data-testid":"button-toggle-gla-details",children:[c?e.jsx(Du,{className:"w-3.5 h-3.5"}):e.jsx(Rr,{className:"w-3.5 h-3.5"}),c?"Hide details":"Show details"]}),c&&e.jsxs("div",{className:"mt-3 space-y-2 text-xs text-slate-600 bg-slate-50 rounded-lg p-3 border","data-testid":"gla-detail-section",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Sample Size"}),e.jsx("span",{className:"font-medium text-slate-800",children:h?.sampleSize??t?.marketPoolSize??"—"})]}),h?.rSquared!==void 0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"R² Correlation"}),e.jsxs("span",{className:"font-medium text-slate-800",children:[(h.rSquared*100).toFixed(1),"%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"90% Confidence Range"}),e.jsxs("span",{className:"font-medium text-slate-800",children:["$",N.low.toLocaleStr
44ing()," – $",N.high.toLocaleString(),"/sqft"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Source"}),e.jsx("span",{className:"font-medium text-slate-800",children:h?.source??"Market regression"})]}),e.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded p-2 mt-2",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(on,{className:"w-3.5 h-3.5 text-blue-500 shrink-0 mt-0.5"}),e.jsxs("span",{className:"text-blue-700",children:["You're statistically supported to use any rate in the $",N.low.toLocaleString()," – $",N.high.toLocaleString()," range."]})]})})]})]})]})]}),e.jsxs(ja,{"data-testid":"gla-reconciliation",children:[e.jsx(Do,{className:"pb-3",children:e.jsxs(ko,{className:"text-sm flex items-center gap-2",children:[e.jsx(kr,{className:"w-4 h-4 text-green-600"}),"Selected Adjustment"]})}),e.jsxs(Ta,{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-xs text-slate-500 mb-1 block",children:"Rate ($/sqft)"}),e.jsx(ze,{type:"number",value:x,onChange:A=>{const M=parseInt(A.target.value,10);isNaN(M)||y(M)},onBlur:()=>F(x),onKeyDown:A=>{A.key==="Enter"&&F(x)},className:"h-9 text-center font-mono font-semibold","data-testid":"input-gla-rate"})]})}),N.low!==N.high&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between text-[10px] text-slate-400 mb-1",children:[e.jsxs("span",{children:["$",N.low.toLocaleString()]}),e.jsxs("span",{children:["$",N.high.toLocaleString()]})]}),e.jsx(IN,{value:[x],min:Math.max(0,N.low),max:N.high,step:1,onValueChange:([A])=>{y(A),F(A)},className:"w-full","data-testid":"slider-gla-rate"})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-2",children:[e.jsx(kt,{variant:"outline",className:"text-[10px] bg-blue-50 text-blue-700 border-blue-200","data-testid":"pill-evidence-regression",children:"Regression Analysis"}),(h?.sampleSize??0)>0&&e.jsxs(kt,{variant:"outline",className:"text-[10px] bg-slate-50 text-slate-600 border-slate-200","data-testid":"pill-evidence-sample",children:[h?.sampleSize??t?.marketPoolSize??0," sales"]})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-sm font-medium text-slate-700",children:"GLA vs Sale Price"}),e.jsx(up,{value:p,onValueChange:A=>u(A),children:e.jsxs(pp,{className:"h-7",children:[e.jsxs($n,{value:"chart",className:"text-xs px-2 py-1 h-5","data-testid":"tab-gla-chart",children:[e.jsx(Pl,{className:"w-3 h-3 mr-1"}),"Chart"]}),e.jsxs($n,{value:"table",className:"text-xs px-2 py-1 h-5","data-testid":"tab-gla-table",children:[e.jsx(SN,{className:"w-3 h-3 mr-1"}),"Table"]})]})})]}),p==="chart"?e.jsx(ja,{children:e.jsxs(Ta,{className:"pt-4 pb-2",children:[e.jsx(cc,{width:"100%",height:420,children:e.jsxs(Fh,{margin:{top:15,right:20,left:15,bottom:20},children:[e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"gla",type:"number",domain:E,tick:{fontSize:10,fill:"#64748b"},axisLine:{stroke:"#cbd5e1"},tickFormatter:A=>`${(A/1e3).toFixed(1)}k`,label:{value:"GLA (sqft)",position:"bottom",offset:0,fontSize:11,fill:"#94a3b8"}}),e.jsx(ql,{dataKey:"price",type:"number",domain:R,tick:{fontSize:10,fill:"#64748b"},axisLine:{stroke:"#cbd5e1"},tickFormatter:A=>`$${(A/1e3).toFixed(0)}k`,width:55,label:{value:"Sale Price",angle:-90,position:"insideLeft",offset:-5,fontSize:11,fill:"#94a3b8"}}),e.jsx(uc,{content:({active:A,payload:M})=>{if(!A||!M?.length)return null;const B=M[0]?.payload;return B?e.jsxs("div",{className:"bg-white border rounded-lg shadow-lg p-2 text-xs",children:[B.label&&e.jsx("div",{className:"font-semibold text-slate-800 mb-1",children:B.label}),e.jsxs("div",{children:["GLA: ",B.gla.toLocaleString()," sqft"]}
44),e.jsxs("div",{children:["Price: $",B.price.toLocaleString()]})]}):null}}),l&&e.jsxs(e.Fragment,{children:[e.jsx(LA,{x1:l.yellowLowRange[0],x2:l.yellowHighRange[1],fill:"rgba(245, 158, 11, 0.06)",ifOverflow:"hidden"}),e.jsx(LA,{x1:l.greenRange[0],x2:l.greenRange[1],fill:"rgba(16, 185, 129, 0.10)",ifOverflow:"hidden"}),e.jsx(wu,{x:l.greenRange[0],stroke:"rgba(16, 185, 129, 0.4)",strokeDasharray:"3 3",strokeWidth:1}),e.jsx(wu,{x:l.greenRange[1],stroke:"rgba(16, 185, 129, 0.4)",strokeDasharray:"3 3",strokeWidth:1}),e.jsx(wu,{x:l.yellowLowRange[0],stroke:"rgba(245, 158, 11, 0.3)",strokeDasharray:"3 3",strokeWidth:1}),e.jsx(wu,{x:l.yellowHighRange[1],stroke:"rgba(245, 158, 11, 0.3)",strokeDasharray:"3 3",strokeWidth:1})]}),j.min>0&&e.jsx(LA,{x1:j.min,x2:j.max,fill:"rgba(59, 130, 246, 0.06)",stroke:"rgba(59, 130, 246, 0.2)",strokeDasharray:"4 4"}),O.length>=2&&e.jsx(_h,{name:"Regression",data:O,dataKey:"regressionPrice",line:{stroke:"#f59e0b",strokeWidth:2,strokeDasharray:"6 3"},shape:e.jsx(e.Fragment,{}),legendType:"none",isAnimationActive:!1}),G.length>0&&e.jsx(_h,{name:"Market Pool",data:G,dataKey:"price",fill:"#94a3b8",opacity:.4,shape:"circle",isAnimationActive:!1,children:G.map((A,M)=>e.jsx($x,{r:3},M))}),U.length>0&&e.jsx(_h,{name:"Grid Comps",data:U,dataKey:"price",fill:"#3b82f6",isAnimationActive:!1,children:U.map((A,M)=>e.jsx($x,{r:6},M))}),C.length>0&&e.jsx(_h,{name:"Subject",data:C,dataKey:"price",fill:"#f59e0b",shape:"diamond",isAnimationActive:!1,children:C.map((A,M)=>e.jsx($x,{r:8},M))})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[10px] text-slate-500 mt-1 border-t pt-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-400 opacity-60"}),e.jsx("span",{children:"Market Sales"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-blue-500"}),e.jsx("span",{children:"Grid Comps"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-2.5 h-2.5 bg-amber-500 rotate-45"}),e.jsx("span",{children:"Subject"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-4 h-0.5 bg-amber-500",style:{borderTop:"2px dashed #f59e0b"}}),e.jsxs("span",{children:["Regression ($",Math.round(m),"/sqft)"]})]}),j.min>0&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-2 bg-blue-500/10 border border-blue-500/30 border-dashed"}),e.jsx("span",{children:"Comp Range"})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-2 bg-emerald-500/15 border border-emerald-500/30"}),e.jsx("span",{children:"Green Band"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-3 h-2 bg-amber-500/10 border border-amber-500/20"}),e.jsx("span",{children:"Yellow Band"})]})]})]})]})}):e.jsx(ja,{children:e.jsx(Ta,{className:"p-0",children:e.jsx(Qd,{className:"h-[460px]",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 px-3 text-xs font-medium text-slate-500",children:"Property"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"GLA"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"Sale Price"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"$/sqft"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"GLA Diff"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"Adj"})]})}),e.jsxs("tbody",{children:[b>0&&e.jsxs("tr",{className:"border-b bg-amber-50",children:[e.jsxs("td",{className:"py-2 px-3 font-medium text-amber-800",children:["Subject",e.jsx(kt,{className:"ml-2 text-[9px] px-1 py-0 bg-amber-100 text-amber-700 border-amber-300",children:"Subject"})]}),e.jsx("td",{className:"py-2 px-3 text-right font-mono",children:b.toLocaleStr
44ing()}),e.jsx("td",{className:"py-2 px-3 text-right text-slate-400",children:"—"}),e.jsx("td",{className:"py-2 px-3 text-right text-slate-400",children:"—"}),e.jsx("td",{className:"py-2 px-3 text-right text-slate-400",children:"—"}),e.jsx("td",{className:"py-2 px-3 text-right text-slate-400",children:"—"})]}),r.map((A,M)=>{const B=A.gla||0,oe=A.price||A.salePrice||0,ae=B>0?Math.round(oe/B):0,D=b-B,_=D*x;return e.jsxs("tr",{className:"border-b hover:bg-slate-50","data-testid":`row-gla-comp-${M}`,children:[e.jsx("td",{className:"py-2 px-3",children:e.jsx("div",{className:"truncate max-w-[180px] text-slate-700",title:A.address,children:(A.address||"").split(",")[0]})}),e.jsx("td",{className:"py-2 px-3 text-right font-mono text-slate-700",children:B.toLocaleString()}),e.jsxs("td",{className:"py-2 px-3 text-right font-mono text-slate-700",children:["$",oe.toLocaleString()]}),e.jsxs("td",{className:"py-2 px-3 text-right font-mono text-slate-500",children:["$",ae.toLocaleString()]}),e.jsx("td",{className:"py-2 px-3 text-right font-mono",children:e.jsxs("span",{className:D>0?"text-green-600":D<0?"text-red-600":"text-slate-400",children:[D>0?"+":"",D.toLocaleString()]})}),e.jsx("td",{className:"py-2 px-3 text-right font-mono font-medium",children:e.jsxs("span",{className:_>0?"text-green-600":_<0?"text-red-600":"text-slate-400",children:[_>0?"+":"",d9(_)]})})]},A.id||M)})]})]})})})})]})]}):e.jsx(ja,{className:"w-full","data-testid":"gla-analysis-no-data",children:e.jsxs(Ta,{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-100 mb-4",children:e.jsx(Um,{className:"w-8 h-8 text-slate-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-2",children:"No GLA Data"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-sm mx-auto",children:"Run AVM analysis first to generate GLA adjustment rates."})]})}):e.jsx(ja,{className:"w-full","data-testid":"gla-analysis-locked",children:e.jsxs(Ta,{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-amber-100 mb-4",children:e.jsx(Di,{className:"w-8 h-8 text-amber-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-2","data-testid":"text-gla-lock-message",children:"Lock Your Market First"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-sm mx-auto",children:"Define and lock your market boundaries to generate GLA adjustment data."})]})})}function p9(t){switch(t){case"high":return{label:"High",className:"bg-green-100 text-green-700 border-green-200"};case"medium":return{label:"Medium",className:"bg-amber-100 text-amber-700 border-amber-200"};case"low":return{label:"Low",className:"bg-red-100 text-red-700 border-red-200"}}}function m9(t){return t===0?"$0":`${t>=0?"+":"-"}$${Math.abs(Math.round(t)).toLocaleString()}`}function h9({cx:t,cy:a,payload:s}){return!t||!a||!s?.isGridComp?null:e.jsx("circle",{cx:t,cy:a,r:6,fill:"#3b82f6",stroke:"#1d4ed8",strokeWidth:1.5})}function f9({cx:t,cy:a,payload:s}){return!t||!a||s?.isGridComp||s?.isSubject?null:e.jsx("circle",{cx:t,cy:a,r:3,fill:"#94a3b8",fillOpacity:.5,stroke:"#64748b",strokeWidth:.5})}function g9({cx:t,cy:a,payload:s}){return!t||!a||!s?.isSubject?null:e.jsx("g",{children:e.jsx("polygon",{points:`${t},${a-8} ${t+7},${a+4} ${t-7},${a+4}`,fill:"#f59e0b",stroke:"#d97706",strokeWidth:1.5})})}function x9({subjectEls:t,comps:a,marketPool:s=[],ratePerPoint:r,rSquared:n,sampleSize:i,confidence:l,regressionSlope:c,regressionIntercept:d,confidenceRange:p,isMarketLocked:u,onLockRate:m,lockedRate:h}){const[f,v]=o.useState("chart"),[S,N]=o.useState(!1),[x,y]=o.useState(h??r),[b,j]=o.useState(!1),T=p9(l),O=o.useMemo(()=>{const A=a.filter(M=>M.elsScore>0).map(M=>M.elsScore);return A.length===0?{min:0,max:100}:{min:Math.min(...A),max:Math.max(...A)}},[a]),E=o.useMemo(()=>{if(p)return p;const A=Math.max(Math.abs(r)*.5,100);return{low:Math.round(r-A),high:Math.round(r+A)}},[p,r]),R=o.useMemo(()=>{const A=[];if(s.forEach(M=>{M.elsScore>0&&M.price>0&&A.push({els:M.elsScore,price:M.price,isGridComp:!1,isSubject:!1})}),a.forEach(M=>{M.elsScore>0&&M.salePrice>0&&A.push({els:M.elsScore,price:M.salePrice,isGridComp:M.isGridComp,isSubject:!1,label:M.address.split(",")[0].replace(/^\d+\s/,"").slice(0,15)})}),t>0){const M=a.length>0&&[...a].sort((B,oe)=>B.salePrice-oe.salePrice)[Math.floor(a.length/2)]?.salePrice||0;M>0&&A.push({els:t,price:M,isGridComp:!1,isSubject:!0,label:"Subject"})}return A},[a,s,t]),G=o.useMemo(()=>
44{if(!c||!d)return[];const A=R.map(_=>_.els).filter(_=>_>0);if(A.length===0)return[];const M=Math.min(...A)-5,B=Math.max(...A)+5,oe=20,ae=(B-M)/oe,D=[];for(let _=0;_<=oe;_++){const $=M+_*ae;D.push({els:Math.round($*10)/10,price:d+c*$})}return D},[c,d,R]),U=o.useMemo(()=>{const A=R.map(M=>M.els);return A.length===0?[0,100]:[Math.max(0,Math.min(...A)-10),Math.min(100,Math.max(...A)+10)]},[R]),C=()=>{m?.(x)},F=h!=null;return u?i===0||r===0?e.jsx(ja,{className:"w-full",children:e.jsxs(Ta,{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-100 mb-4",children:e.jsx(Wl,{className:"w-8 h-8 text-slate-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-2","data-testid":"text-location-no-data",children:"No Location Data Available"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-sm mx-auto",children:"Not enough ELS score variation in your market to calculate location adjustments. Scores may be too similar across comps."})]})}):e.jsxs("div",{className:"flex flex-col h-full","data-testid":"embedded-location-analysis",children:[e.jsx("div",{className:"flex-1 overflow-auto p-6",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ko,{className:"text-base flex items-center gap-2",children:[e.jsx(Wl,{className:"w-5 h-5 text-purple-600"}),"LOCATION ADJUSTMENT"]}),e.jsx(kt,{className:T.className,"data-testid":"badge-location-confidence",children:T.label})]})}),e.jsxs(Ta,{className:"space-y-4",children:[e.jsx("div",{className:"text-center py-3 bg-purple-50 rounded-lg border border-purple-100",children:e.jsxs("div",{className:"text-3xl font-bold text-purple-700","data-testid":"text-location-rate",children:["$",Math.round(r).toLocaleString(),e.jsx("span",{className:"text-lg font-normal text-purple-500",children:"/point"})]})}),e.jsxs("p",{className:"text-sm text-slate-600 leading-relaxed","data-testid":"text-location-summary",children:["We analyzed ",e.jsx("span",{className:"font-semibold",children:i})," sales and found each Echo Location Score (ELS) point difference is worth about"," ",e.jsxs("span",{className:"font-semibold",children:["$",Math.round(r).toLocaleString()]}),". Higher ELS scores indicate better location quality."]}),e.jsxs("div",{className:"flex items-center justify-between text-sm bg-slate-50 rounded-lg p-3 border",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500",children:"Subject ELS:"})," ",e.jsx("span",{className:"font-semibold text-purple-700","data-testid":"text-subject-els",children:t})]}),e.jsx("div",{className:"text-slate-300",children:"|"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500",children:"Comps:"})," ",e.jsxs("span",{className:"font-semibold text-slate-700","data-testid":"text-comp-els-range",children:[O.min," – ",O.max]})]})]}),e.jsxs("button",{onClick:()=>N(!S),className:"flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800 transition-colors w-full justify-center","data-testid":"button-toggle-location-detail",children:[S?e.jsx(Du,{className:"w-3 h-3"}):e.jsx(Rr,{className:"w-3 h-3"}),S?"Hide details":"See the data"]}),S&&e.jsxs("div",{className:"bg-slate-50 rounded-lg border p-3 space-y-2 text-sm animate-in slide-in-from-top-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 text-xs",children:"Sample Size"}),e.jsxs("div",{className:"font-semibold","data-testid":"text-location-sample-size",children:[i," sales"]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 text-xs",children:"R² Correlation"}),e.jsxs("div",{className:"font-semibold","data-testid":"text-location-r-squared",children:[(n*100).toFixed(1),"%"]})]})]}),p&&e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 text-xs",children:"90% Confidence Range"}),e.jsxs("div",{className:"font-semibold","data-testid":"text-location-conf-range",children:["$",Math.round(p.low).toLocaleStr
44ing()," – $",Math.round(p.high).toLocaleString(),"/point"]}),e.jsx("p",{className:"text-xs text-slate-500 mt-1",children:"You're statistically supported to use any rate in this range"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 text-xs",children:"What this means"}),e.jsxs("p",{className:"text-xs text-slate-600 mt-0.5",children:["The R² of ",(n*100).toFixed(1),"% indicates how well ELS scores explain price differences.",n>.3?" This is a strong relationship — location clearly matters in this market.":n>.1?" This is a moderate relationship — location has some effect on value.":" This is a weak relationship — other factors may matter more than location here."]})]})]})]})]})}),e.jsx("div",{className:"space-y-4",children:e.jsxs(ja,{children:[e.jsx(Do,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ko,{className:"text-sm font-medium text-slate-600",children:"ELS Score vs Sale Price"}),e.jsx(up,{value:f,onValueChange:A=>v(A),children:e.jsxs(pp,{className:"h-7",children:[e.jsxs($n,{value:"chart",className:"text-xs px-2 py-1 h-5",children:[e.jsx(Pl,{className:"w-3 h-3 mr-1"}),"Chart"]}),e.jsxs($n,{value:"table",className:"text-xs px-2 py-1 h-5",children:[e.jsx(SN,{className:"w-3 h-3 mr-1"}),"Table"]})]})})]})}),e.jsx(Ta,{children:f==="chart"?e.jsxs("div",{children:[e.jsx(cc,{width:"100%",height:320,children:e.jsxs(Fh,{margin:{top:20,right:20,left:10,bottom:20},children:[e.jsx($d,{strokeDasharray:"3 3",stroke:"#e2e8f0"}),e.jsx(dc,{dataKey:"els",type:"number",domain:U,tick:{fontSize:10,fill:"#64748b"},axisLine:{stroke:"#cbd5e1"},name:"ELS Score",children:e.jsx(C0,{value:"ELS Score",position:"bottom",offset:0,style:{fontSize:11,fill:"#94a3b8"}})}),e.jsx(ql,{dataKey:"price",type:"number",tick:{fontSize:10,fill:"#64748b"},axisLine:{stroke:"#cbd5e1"},tickFormatter:A=>`$${(A/1e3).toFixed(0)}K`,width:55,children:e.jsx(C0,{value:"Sale Price",angle:-90,position:"insideLeft",offset:-5,style:{fontSize:11,fill:"#94a3b8"}})}),e.jsx(uc,{content:({payload:A})=>{if(!A||A.length===0)return null;const M=A[0]?.payload;return M?e.jsxs("div",{className:"bg-white border rounded-lg shadow-lg p-2 text-xs",children:[M.label&&e.jsx("div",{className:"font-semibold text-slate-700 mb-1",children:M.label}),e.jsxs("div",{children:["ELS: ",e.jsx("span",{className:"font-medium",children:M.els})]}
44),e.jsxs("div",{children:["Price: ",e.jsxs("span",{className:"font-medium",children:["$",M.price?.toLocaleString()]})]}),M.isSubject&&e.jsx("div",{className:"text-amber-600 font-medium mt-1",children:"Subject Property"}),M.isGridComp&&e.jsx("div",{className:"text-blue-600 font-medium mt-1",children:"Grid Comp"})]}):null}}),t>0&&e.jsx(wu,{x:t,stroke:"#f59e0b",strokeWidth:1.5,strokeDasharray:"4 4",children:e.jsx(C0,{value:`Subject (${t})`,position:"top",fill:"#d97706",fontSize:9,fontWeight:600})}),O.min>0&&O.max>0&&e.jsxs(e.Fragment,{children:[e.jsx(wu,{x:O.min,stroke:"#3b82f6",strokeWidth:1,strokeDasharray:"3 3"}),e.jsx(wu,{x:O.max,stroke:"#3b82f6",strokeWidth:1,strokeDasharray:"3 3"})]}),G.length>0&&e.jsx(np,{data:G,dataKey:"price",stroke:"#7c3aed",strokeWidth:2,dot:!1,type:"linear",legendType:"none",isAnimationActive:!1}),e.jsx(_h,{data:R.filter(A=>!A.isGridComp&&!A.isSubject),fill:"#94a3b8",shape:e.jsx(f9,{}),isAnimationActive:!1}),e.jsx(_h,{data:R.filter(A=>A.isGridComp),fill:"#3b82f6",shape:e.jsx(h9,{}),isAnimationActive:!1}),e.jsx(_h,{data:R.filter(A=>A.isSubject),fill:"#f59e0b",shape:e.jsx(g9,{}),isAnimationActive:!1})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[10px] text-slate-500 mt-2 border-t pt-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-400"}),e.jsx("span",{children:"Market Sales"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-blue-500"}),e.jsx("span",{children:"Grid Comps"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-0 h-0 border-l-[4px] border-r-[4px] border-b-[7px] border-l-transparent border-r-transparent border-b-amber-500"}),e.jsx("span",{children:"Subject"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"w-4 h-0.5 bg-purple-600"}),e.jsx("span",{children:"Regression ($/point)"})]})]})]}):e.jsx(Qd,{className:"h-[340px]",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 sticky top-0",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 px-3 text-xs font-medium text-slate-500",children:"Property"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"ELS"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"Sale Price"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"ELS Diff"}),e.jsx("th",{className:"text-right py-2 px-3 text-xs font-medium text-slate-500",children:"Adj"})]})}),e.jsx("tbody",{children:a.filter(A=>A.isGridComp).sort((A,M)=>M.elsScore-A.elsScore).map(A=>{const M=t-A.elsScore,B=M*x;return e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 px-3",children:e.jsx("div",{className:"text-slate-700 truncate max-w-[140px]",children:A.address.split(",")[0]})}),e.jsx("td",{className:"py-2 px-3 text-right font-mono",children:A.elsScore}),e.jsxs("td",{className:"py-2 px-3 text-right font-mono",children:["$",A.salePrice.toLocaleString()]}),e.jsxs("td",{className:Q("py-2 px-3 text-right font-mono",M>0?"text-green-600":M<0?"text-red-600":"text-slate-400"),children:[M>0?"+":"",M]}),e.jsx("td",{className:Q("py-2 px-3 text-right font-mono font-medium",B>0?"text-green-600":B<0?"text-red-600":"text-slate-400"),children:m9(B)})]},A.id)})})]})})})]})})]})}),e.jsxs("div",{className:"shrink-0 border-t bg-slate-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(kr,{className:"w-4 h-4 text-purple-600"}),e.jsx("span",{className:"text-sm font-semibold text-slate-700",children:"Selected Adjustment"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Rate per ELS point:"}),b?e.jsx(ze,{type:"number",value:x,onChange:A=>y(Number(A.target.value)||0),onBlur:()=>j(!1),onKeyDown:A=>{A.key==="Enter"&&j(!1)},autoFocus:!0,className:"h-7 w-28 text-sm font-mono","data-testid":"input-location-rate"}):e.jsxs("button",{onClick:()=>j(!0),className:"font-mono font-semibold text-purple-700 hover:text-purple-900 underline-offset-2 hover:underline","data-testid":"button-edit-location-rate",children:["$",Math.round(x).toLocaleStr
44ing(),"/point"]})]}),e.jsx(IN,{value:[x],min:E.low,max:E.high,step:Math.max(1,Math.round((E.high-E.low)/100)),onValueChange:([A])=>y(Math.round(A)),className:"w-full","data-testid":"slider-location-rate"}),e.jsxs("div",{className:"flex justify-between text-[10px] text-slate-400 mt-1",children:[e.jsxs("span",{children:["$",Math.round(E.low).toLocaleString()]}),e.jsxs("span",{children:["$",Math.round(E.high).toLocaleString()]})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(kt,{variant:"outline",className:"text-[10px] bg-purple-50 text-purple-600 border-purple-200",children:"Regression"})})]}),e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(De,{onClick:C,className:"w-full",size:"lg",variant:F?"secondary":"default","data-testid":"button-lock-location-rate",children:F?e.jsxs(e.Fragment,{children:[e.jsx(kr,{className:"w-4 h-4 mr-2"}),"Locked: $",Math.round(h).toLocaleString(),"/point"]}):e.jsxs(e.Fragment,{children:[e.jsx(Hr,{className:"w-4 h-4 mr-2"}),"Use This Rate"]})})}),e.jsx(Wa,{children:e.jsxs("p",{children:["Lock $",Math.round(x).toLocaleString(),"/ELS point as the location adjustment rate"]})})]})}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 flex items-start gap-2",children:[e.jsx(on,{className:"w-4 h-4 text-blue-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-blue-700",children:[e.jsx("strong",{children:"How it works:"})," The Echo Location Score (ELS) quantifies location quality based on proximity to amenities, schools, parks, transit, and environmental factors. Each point difference between subject and comp generates a dollar adjustment."]})]})]})]}):e.jsx(ja,{className:"w-full",children:e.jsxs(Ta,{className:"py-12 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-amber-100 mb-4",children:e.jsx(Di,{className:"w-8 h-8 text-amber-600"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-2","data-testid":"text-location-lock-first",children:"Lock Your Market First"}),e.jsx("p",{className:"text-sm text-slate-500 max-w-sm mx-auto",children:"Define and lock your market boundaries to generate location adjustment data."})]})})}function b9(t){const{isSubjectReportOpen:a,setIsSubjectReportOpen:s,subjectAddress:r,listingDetails:n,propDetails:i,isLoadingSubjectData:l,showMarketModal:c,setShowMarketModal:d,marketLocked:p,subMarketLocked:u,lockedUrarStats:m,urarStats:h,lockedForm1004mcStats:f,form1004mcStats:v,handleLockMarket:S,handleLockSubMarket:N,isLoading:x,propertiesInArea:y,subMarketPropertiesCount:b,neighborhoodInfo:j,setNeighborhoodInfo:T,setNeighborhoodAiGenerated:O,onNeighborhoodAiGenerated:E,onUrarStatsChange:R,parsedSubjectCity:G,subjectState:U,radiusMiles:C,isGeneratingNeighborhood:F,neighborhoodAiGenerated:A,showAdjustModal:M,setShowAdjustModal:B,adjustModalTab:oe,setAdjustModalTab:ae,avmMarketLocked:D,avmSubMarketLocked:_,previousTab:$,setRightPanelTab:z,avmResults:V,advisorData:le,advisorLoading:W,fetchAdvisorData:me,lockedTimeAdjRate:Z,verifiedSubject:pe,assignmentId:se,comparisonDataSource:fe,lockedSubmarketSalesData:ue,lockedMarketSalesData:be,activeUtilityBands:H,marketContext:ye,lockedMarketCount:de,lockedSubMarketCount:ge,lockedMarketResultIds:Be,lockedSubmarketResultIds:He,subjectZipCode:Ie,selectedComps:ce,setPendingAdvisorApply:Pe,showDerivationPanel:We,setShowDerivationPanel:Re,derivationState:ne,setDerivationState:Me}=t,{toast:lt}=hc(),Tt={isLoading:x,marketDefinition:{radiusMiles:C},selectedComps:ce};return e.jsxs(e.Fragment,{children:[e.jsx(xi,{open:a,onOpenChange:s,children:e.jsxs(bi,{className:"max-w-7xl w-[98vw] h-[95vh] p-0 gap-0 flex flex-col bg-white overflow-hidden z-[100]",children:[e.jsxs($i,{className:"px-6 py-4 border-b border-border bg-gradient-to-r from-slate-50 to-blue-50 flex-shrink-0",children:[e.jsx(si,{className:"text-lg font-serif font-bold text-slate-800",children:"Subject Property Report"}),e.jsxs(pl,{className:"text-xs text-slate-500 font-mono mt-1 flex items-center gap-2",children:[e.jsx(Wl,{className:"w-3 h-3"}),r]})]}),e.jsx(Qd,{className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsx("div",{className:"aspect-video max-h-64 bg-muted rounded-lg overflow-hidden",children:n?.ph
44otos?.[0]?e.jsx("img",{src:n.photos[0],alt:"Subject Property",className:"w-full h-full object-cover"}):i?.photos?.[0]?e.jsx("img",{src:i.photos[0],alt:"Subject Property",className:"w-full h-full object-cover"}):e.jsxs("div",{className:"w-full h-full bg-gradient-to-br from-slate-100 to-slate-200 flex flex-col items-center justify-center",children:[e.jsx(Fo,{className:"w-12 h-12 text-slate-300 mb-2"}),e.jsx("span",{className:"text-sm text-slate-400",children:"No photo on record"})]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(kt,{className:Q("text-xs font-bold px-3 py-1",(()=>{const je=n?.status,Le=(typeof je=="string"?je:"").toLowerCase();return Le.includes("sold")||Le.includes("clos")?"bg-red-100 text-red-700 border-red-200":Le.includes("activ")?"bg-green-100 text-green-700 border-green-200":Le.includes("pend")?"bg-amber-100 text-amber-700 border-amber-200":"bg-slate-100 text-slate-600 border-slate-200"})()),children:typeof n?.status=="string"?n.status:n?.status?.Type||"Not on Market"}),n?.listingId&&e.jsxs("span",{className:"text-xs text-slate-500 font-mono",children:["MLS# ",n.listingId]})]}),e.jsx(oK,{score:null,isLoading:l})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(xv,{className:"w-4 h-4"}),e.jsx("span",{className:"text-xs font-medium uppercase",children:n?.soldPrice?"Sold Price":"List Price"})]}),e.jsx("p",{className:"text-2xl font-bold text-slate-800",children:n?.soldPrice?`$${n.soldPrice.toLocaleString()}`:n?.listPrice?`$${n.listPrice.toLocaleString()}`:"-"})]}),e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 mb-1",children:[e.jsx(mc,{className:"w-4 h-4"}),e.jsx("span",{className:"text-xs font-medium uppercase",children:n?.soldDate?"Sold Date":"List Date"})]}),e.jsx("p",{className:"text-2xl font-bold text-slate-800",children:n?.soldDate||n?.listDate?new Date(n?.soldDate||n?.listDate||"").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"-"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 md:grid-cols-6 gap-3",children:[e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg p-3 text-center",children:[e.jsx(hv,{className:"w-5 h-5 mx-auto text-slate-400 mb-1"}),e.jsx("p",{className:"text-lg font-bold text-slate-800",children:n?.bedrooms||i?.bedrooms||"-"}),e.jsx("p",{className:"text-[10px] uppercase text-slate-500",children:"Beds"})]}),e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg p-3 text-center",children:[e.jsx(H0,{className:"w-5 h-5 mx-auto text-slate-400 mb-1"}),e.jsx("p",{className:"text-lg font-bold text-slate-800",children:n?.bathrooms||i?.bathrooms||"-"}),e.jsx("p",{className:"text-[10px] uppercase text-slate-500",children:"Baths"})]}),e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg p-3 text-center",children:[e.jsx(Um,{className:"w-5 h-5 mx-auto text-slate-400 mb-1"}),e.jsx("p",{className:"text-lg font-bold text-slate-800",children:n?.squareFeet?.toLocaleString()||i?.squareFeet?.toLocaleString()||"-"}),e.jsx("p",{className:"text-[10px] uppercase text-slate-500",children:"Sq Ft"})]}),e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg p-3 text-center",children:[e.jsx(Fo,{className:"w-5 h-5 mx-auto text-slate-400 mb-1"}),e.jsx("p",{className:"text-lg font-bold text-slate-800",children:n?.yearBuilt||i?.yearBuilt||"-"}),e.jsx("p",{className:"text-[10px] uppercase text-slate-500",children:"Year Built"})]}),e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg p-3 text-center",children:[e.jsx(FO,{className:"w-5 h-5 mx-auto text-slate-400 mb-1"}),e.jsx("p",{className:"text-lg font-bold text-slate-800",children:n?.garageSpaces||i?.garageSpaces||"-"}),e.jsx("p",{className:"text-[10px] uppercase text-slate-500",children:"Garage"})]}),e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg p-3 text-center",children:[e.jsx(Hh,{className:"w-5 h-5 mx-auto text-slate-400 mb-1"}),e.jsx("p",{className:"text-lg font-bold text-slate-800",children:n?.stories||i?.stories||"-"}),e.jsx("p",{className:"text-[10px] uppercase text-slate-500",children:"Stories"})]})]}),(n?.lotSize||i?.lotSize||n?.lotSizeAcres||i?.lotSizeAcres)&&e.jsxs("div",{className:"bg-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsx("span",{className:"text-xs font-medium uppercase text-slate-500",children:"Lot Size"}),e.jsx("p",{className:"text-lg font-bold text-slate-800",children:n?.lotSize?`${n.lotSize.toLocaleStr
44ing()} sf`:i?.lotSize?`${i.lotSize.toLocaleString()} sf`:n?.lotSizeAcres?`${n.lotSizeAcres.toFixed(2)} acres`:i?.lotSizeAcres?`${i.lotSizeAcres.toFixed(2)} acres`:"-"})]}),n?.description&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-bold uppercase text-slate-500",children:"MLS Description"}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed bg-slate-50 rounded-lg p-4 border border-slate-200",children:n.description})]})]})})]})}),e.jsx(xi,{open:c,onOpenChange:d,children:e.jsxs(bi,{hideClose:!0,className:"max-w-[95vw] w-[95vw] max-h-[95vh] p-0 flex flex-col",children:[e.jsxs($i,{className:"sr-only",children:[e.jsx(si,{children:"Market Data"}),e.jsx(pl,{children:"Market and neighborhood analysis data"})]}),e.jsxs("div",{className:"flex flex-col h-[90vh]",children:[e.jsx("div",{className:"shrink-0 border-b px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"w-5 h-5 text-blue-600"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Market Data"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p&&e.jsxs(kt,{className:"bg-green-100 text-green-700 border-green-200 text-xs gap-1",children:[e.jsx(Hr,{className:"w-3 h-3"}),"Market Locked"]}),u&&e.jsxs(kt,{className:"bg-green-100 text-green-700 border-green-200 text-xs gap-1",children:[e.jsx(Hr,{className:"w-3 h-3"}),"Sub-Market Locked"]})]})]}),e.jsx(De,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 shrink-0",onClick:()=>d(!1),"data-testid":"button-close-market-modal",children:e.jsx(ur,{className:"w-4 h-4"})})]})}),e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx(uK,{urarStats:p&&m||h,form1004mcStats:u&&f||v,marketLocked:p,subMarketLocked:u,onLockMarket:S,onLockSubMarket:N,isLoading:Tt.isLoading,marketCount:y,submarketCount:b,neighborhoodInfo:j,onNeighborhoodInfoChange:T,onNeighborhoodManualEdit:()=>{O(!1),E?.(!1)},onStatsChange:R,subjectAddress:r,subjectCity:G,subjectCounty:i?.county,subjectState:U,radiusMiles:Tt.marketDefinition?.radiusMiles,isGeneratingNeighborhood:F,neighborhoodAiGenerated:A})})]})]})}),e.jsx(xi,{open:M,onOpenChange:je=>{B(je),je||z($)},children:e.jsxs(bi,{hideClose:!0,className:"max-w-[95vw] w-[95vw] max-h-[95vh] p-0 flex flex-col",children:[e.jsxs($i,{className:"sr-only",children:[e.jsx(si,{children:"Adjustment Lab"}),e.jsx(pl,{children:"Time and square footage adjustments for comparable properties"})]}),e.jsxs("div",{className:"flex flex-col h-[90vh]",children:[e.jsx("div",{className:"shrink-0 border-b px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(up,{value:oe,onValueChange:je=>{ae(je),je==="advisor"&&!le&&!W&&me()},className:"flex-1",children:e.jsxs(pp,{className:"grid grid-cols-6 w-full max-w-3xl",children:[e.jsxs($n,{value:"avm",className:"text-sm gap-1.5","data-testid":"tab-avm-adjust-modal",children:[e.jsx(ul,{className:"w-4 h-4"}),"AVM",V&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 ml-1"})]}),e.jsxs($n,{value:"advisor",className:"text-sm gap-1.5","data-testid":"tab-advisor-adjust-modal",children:[e.jsx(Ql,{className:"w-4 h-4"}),"Advisor",le&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-blue-500 ml-1"})]}),e.jsxs($n,{value:"timeadj",className:"text-sm gap-1.5","data-testid":"tab-timeadj-modal",children:[e.jsx(mc,{className:"w-4 h-4"}),"Time",Z!==null&&e.jsx(Hr,{className:"w-3 h-3 text-green-600 ml-1"})]}),e.jsxs($n,{value:"gla",className:"text-sm gap-1.5","data-testid":"tab-gla-modal",children:[e.jsx(Um,{className:"w-4 h-4"}),"GLA",V?.adjustmentRates?.glaDollarPerSqft&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 ml-1"})]}),e.jsxs($n,{value:"condqual",className:"text-sm gap-1.5","data-testid":"tab-condqual-modal",children:[e.jsx(pc,{className:"w-4 h-4"}),"Cond/Qual",(V?.adjustmentRates?.conditionPercentPerLevel||V?.adjustmentRates?.qualityPercentPerLevel)&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 ml-1"})]}),e.jsxs($n,{value:"location",className:"text-sm gap-1.5","data-testid":"tab-location-modal",children:[e.jsx(Wl,{className:"w-4 h-4"}),"Location",V?.adjustmentRates?.locationDollarPerPoint&&e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 ml-1"})]})]})}),!1,e.jsx(De,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 shrink-0",onClick:()=>{B(!1),z($)},"data-testid":"button-close-adjust-modal",children:e.jsx(ur,{className:"w-4 h-4"})})]})}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[oe==="avm"&&e.jsx("div",{className:"p-6",children:V?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-800",children:"AVM Adjustment Rates"}),e.jsxs("p",{className:"text-sm text-slate-500 mt-1",children:["Calculated from ",V.marketStats?.totalCompsAnalyzed||0," comparable sales"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[(()=>{const je=V.adjustmentRates?.timeStats,Le=V.adjustmentRates?.timeRateMonthly||0,ut=je?.sampleSize||0,st=je?.source||"default",Xt=st==="default"||ut===0,ua=st?.includes("fhfa"),Oa=je?.rSquared||0,Xa=Xt?void 0:{adjustmentType:"time",rate:Le,unit:"%/month",derivationMethod:ua?"published_data":"regression",confidence:je?.confidence||"low",confidenceScore:Oa?Math.round(Oa*100):void 0,evidence:ua?[{type:"published_data",source:"FHFA_HPI",dataPoint:"State HPI",value:Le*12*100,asOfDate:new Date().toISOString().split("T")[0],geography:"State level"}]:Oa>
440?[{type:"regression",sampleSize:ut,rSquared:Oa,coefficient:Le*100,dataRange:{min:0,max:12}}]:[],narrative:ua?`Time adjustment of ${(Le*100).toFixed(2)}% per month derived from FHFA House Price Index data for the subject's state, representing broad market appreciation trends over the prior 12 months.`:`Time adjustment of ${(Le*100).toFixed(2)}% per month derived from linear regression of ${ut} comparable sales (R²=${(Oa*100).toFixed(1)}%). This ${je?.confidence||"low"}-confidence rate reflects local market price movement.`,shortDescription:`${(Le*100).toFixed(2)}%/mo from ${st} data`,isDefault:!1,dataRecency:new Date().toLocaleDateString(),methodologyNotes:ua?"FHFA publishes quarterly House Price Indices by state. Monthly rate calculated from annual appreciation.":"Time trend derived from regression of sale prices vs. sale dates within the defined market area.",assumptions:["Market conditions consistent during analysis period","Sample representative of subject market segment"]};return e.jsx(Fp,{icon:e.jsx(mc,{className:"w-5 h-5 text-blue-600"}),title:"Time",rate:Xt?"$0":`${Le>=0?"+":""}${(Le*100).toFixed(2)}%/mo`,description:Xt?`Default rate used. Insufficient sales data (${ut} comps) for reliable time trend analysis.`:`Annual: ${Le>=0?"+":""}${(Le*12*100).toFixed(1)}%. ${ut} sales. ${st}.`,confidence:Xt?void 0:je?.confidence,support:Xa,testId:"avm-rate-time"})})(),(()=>{const je=V.adjustmentRates?.glaStats,Le=V.adjustmentRates?.glaDollarPerSqft||0,ut=V.adjustmentRates?.glaPercentPerSqft||0,st=V.adjustmentRates?.medianPrice||0,Xt=je?.sampleSize||0,ua=Xt>0&&Le>0,Oa=Math.abs(je?.correlation||je?.rSquared||0),Xa=ut>0&&st>0?`Formula: ${(ut*100).toFixed(4)}% × $${st.toLocaleString()} median = $${Math.round(Le)}/sqft`:"",qa=ua?{adjustmentType:"gla",rate:Le,unit:"$/sqft",derivationMethod:"regression",confidence:je?.confidence||"low",confidenceScore:Math.round(Oa*100),evidence:[{type:"regression",sampleSize:Xt,rSquared:Oa,coefficient:Le,dataRange:{min:je?.min||0,max:je?.max||0}}],narrative:`GLA adjustment of $${Math.round(Le)}/sqft was derived from regression analysis of ${Xt} sales. Each square foot difference represents approximately ${(ut*100).toFixed(4)}% of median value ($${st.toLocaleString()}). Subject: ${V.verifiedSubject?.gla?.toLocaleString()||0} SF.`,shortDescription:`$${Math.round(Le)}/sqft from ${Xt} sales`,isDefault:!1,methodologyNotes:`Regression analysis: Sale price vs GLA across ${Xt} comparable sales. ${Xa}`,assumptions:["Property size affects value in this market","Marginal value per SF is consistent within this size range"]}:void 0;return e.jsx(Fp,{icon:e.jsx(Um,{className:"w-5 h-5 text-green-600"}),title:"GLA (Size)",rate:Le>0?`$${Math.round(Le)}/sqft`:"$0",description:ua?`From ${Xt} comparable sales. Subject: ${V.verifiedSubject?.gla?.toLocaleString()||0} SF.`:Xt===0?"Insufficient data to derive adjustment.":"No adjustment needed - similar sizes among comparables.",confidence:ua?je?.confidence:void 0,support:qa,testId:"avm-rate-gla"})})(),(()=>{const je=V.adjustmentRates?.locationStats,Le=V.adjustmentRates?.locationRegression,ut=je?.dollarPerPoint||Le?.dollarPerPoint||0,st=V.adjustmentRates?.locationPercentPerPoint||0,Xt=V.adjustmentRates?.medianPrice||0,ua=je?.sampleSize||Le?.sampleSize||0,Oa=je?.rSquared||Le?.rSquared||0,Xa=je?.elsSD||Le?.elsSD||0,qa=ua>0&&ut>0,os=ua>0&&Xa<5?`ELS scores range only ${Xa.toFixed(1)} points among comps - too similar to derive rate.`:"",ya=st>0&&Xt>0?`Formula: ${(st*100).toFixed(4)}% × $${Xt.toLocaleString()} = $${Math.round(ut)}/point`:"",At=qa?{adjustmentType:"location",rate:ut,unit:"$/ELS point",derivationMethod:"regression",confidence:je?.confidence||"low",confidenceScore:Math.round(Oa*100),evidence:[{type:"regression",sampleSize:ua,rSquared:Oa,coefficient:ut,dataRange:{min:0,max:100}}],narrative:`Location adjustment of $${Math.round(ut).toLocaleString()} per ELS point was derived from regression analysis of ${ua} sales (R²=${(Oa*100).toFixed(1)}%). Each point difference in Echo Location Score represents approximately ${(st*100).toFixed(4)}% of median value.`,shortDescription:`$${Math.round(ut).toLocaleStr
44ing()}/point from ${ua} sales`,isDefault:!1,methodologyNotes:`Regression analysis: Sale price vs Echo Location Score (ELS) across ${ua} sales. ${ya}`,assumptions:["Location quality (as measured by ELS) affects property value","ELS captures relevant location factors (parks, highways, schools, walkability)"]}:void 0;return e.jsx(Fp,{icon:e.jsx(Wl,{className:"w-5 h-5 text-purple-600"}),title:"Location (ELS)",rate:ut>0?`$${Math.round(ut).toLocaleString()}/pt`:"$0",description:qa?`From ${ua} comparable sales. R²=${(Oa*100).toFixed(1)}%.`:ua===0?"Insufficient location data to derive adjustment.":os||"No adjustment needed - similar locations among comparables (ELS scores within ±5 points).",confidence:qa?je?.confidence:void 0,support:At,testId:"avm-rate-location"})})(),(()=>{const je=V.adjustmentRates?.conditionStats,Le=V.adjustmentRates?.conditionPercentPerLevel||0,ut=V.adjustmentRates?.conditionPerLevel||V.adjustmentRates?.conditionDollarPerLevel||0,st=V.adjustmentRates?.medianPrice||0,Xt=je?.sampleSize||0,ua=V.verifiedSubject?.condition||"C3",Oa=Xt>0&&Le>0,Xa=Xt>0&&je?.variance===0,qa=st<3e5,os=st>=3e5&&st<8e5,ya=qa?"Low tier (<$300K): Fixed $7,500/level":os?`Mid tier ($300K-$800K): 6% of median = $${Math.round(st*.06).toLocaleString()}/level`:`High tier (>$800K): 7% of median = $${Math.round(st*.07).toLocaleString()}/level`,At=Oa?{adjustmentType:"condition",rate:qa?7500:ut,unit:"$/level",derivationMethod:"uad_scale",confidence:"high",evidence:[],narrative:`Condition adjustment uses Fannie Mae UAD tiered methodology with policy-based rates. ${ya}. Subject is rated ${ua} (scale: C1 best to C6 needs repairs). Rate is applied for each condition level difference between subject and comparable.`,shortDescription:`$${ut.toLocaleString()}/level (UAD policy)`,isDefault:!1,methodologyNotes:`UAD Three-Tier Scale (Fannie Mae policy rates - not derived from sales): • Low tier (<$300K): Fixed $7,500/level • Mid tier ($300K-$800K): 6% of median • High tier (>$800K): 7% of median. Current market median ($${st.toLocaleString()}) uses: ${ya}`,assumptions:["UAD condition scale (C1-C6) accurately captures condition differences","Fannie Mae tiered rates reflect typical market value relationships"]}:void 0,Fe=qa?"$7,500/level":Le>0?`${(Le*100).toFixed(1)}%/level`:"$0";return e.jsx(Fp,{icon:e.jsx(pc,{className:"w-5 h-5 text-amber-600"}),title:"Condition",rate:Oa?Fe:"$0",description:Oa?`UAD policy rate: $${ut.toLocaleString()}/level. Subject: ${ua}.`:Xt===0?"Insufficient condition data - using UAD policy rate.":Xa?"All comparables have same condition rating - no variance.":"No adjustment needed - similar condition among comparables.",confidence:Oa?je?.confidence:void 0,support:At,testId:"avm-rate-condition"})})(),(()=>{const je=V.adjustmentRates?.qualityStats,Le=V.adjustmentRates?.qualityPercentPerLevel||0,ut=V.adjustmentRates?.qualityPerLevel||V.adjustmentRates?.qualityDollarPerLevel||0,st=V.adjustmentRates?.medianPrice||0,Xt=je?.sampleSize||0,ua=V.verifiedSubject?.quality||"Q3",Oa=Xt>0&&Le>0,Xa=Xt>0&&je?.variance===0,qa=st<3e5,os=st>=3e5&&st<8e5,ya=qa?"Low tier (<$300K): Fixed $6,000/level":os?`Mid tier ($300K-$800K): 5% of median = $${Math.round(st*.05).toLocaleString()}/level`:`High tier (>$800K): 6% of median = $${Math.round(st*.06).toLocaleString()}/level`,At=Oa?{adjustmentType:"quality",rate:qa?6e3:ut,unit:"$/level",derivationMethod:"uad_scale",confidence:"high",evidence:[],narrative:`Quality adjustment uses Fannie Mae UAD tiered methodology with policy-based rates. ${ya}. Subject is rated ${ua} (scale: Q1 highest to Q6 basic). Rate is applied for each quality level difference between subject and comparable.`,shortDescription:`$${ut.toLocaleString()}/level (UAD policy)`,isDefault:!1,methodologyNotes:`UAD Three-Tier Scale (Fannie Mae policy rates - not derived from sales): • Low tier (<$300K): Fixed $6,000/level • Mid tier ($300K-$800K): 5% of median • High tier (>$800K): 6% of median. Current market median ($${st.toLocaleString()}) uses: ${ya}`,assumptions:["UAD quality scale (Q1-Q6) accurately captures quality differences","Fannie Mae tiered rates reflect typical market value relationships"]}:void 0,Fe=qa?"$6,000/level":Le>0?`${(Le*100).toFixed(1)}%/level`:"$0";return e.jsx(Fp,{icon:e.jsx(ul,{className:"w-5 h-5 text-indigo-600"}),title:"Quality",rate:Oa?Fe:"$0",description:Oa?`UAD policy rate: $${ut.toLocaleStr
44ing()}/level. Subject: ${ua}.`:Xt===0?"Insufficient quality data - using UAD policy rate.":Xa?"All comparables have same quality rating - no variance.":"No adjustment needed - similar quality among comparables.",confidence:Oa?je?.confidence:void 0,support:At,testId:"avm-rate-quality"})})(),(()=>{const je=V.adjustmentRates?.bedroomStats,Le=V.adjustmentRates?.multicollinearity,ut=Le?.suppressBedBathDollar===!0,st=V.adjustmentRates?.bedroomDollar||0,Xt=V.adjustmentRates?.bedroomPercentPerUnit||0,ua=V.adjustmentRates?.medianPrice||0,Oa=je?.sampleSize||0,Xa=V.verifiedSubject?.bedrooms||0,qa=Oa>0&&st>0&&!ut,os=Xt>0&&ua>0?`Formula: ${(Xt*100).toFixed(2)}% × $${ua.toLocaleString()} median = $${st.toLocaleString()}/bed`:"",ya=Le?.glaVsBeds,At=ut&&ya?`Suppressed: GLA↔Beds VIF=${ya.vif.toFixed(1)}, r=${Math.abs(ya.correlation).toFixed(2)}. Bedroom count is correlated with GLA — adjusting both would double-count value. Bed match used for comp weighting instead (2× boost).`:"",Fe=qa?{adjustmentType:"bedrooms",rate:st,unit:"$/bedroom",derivationMethod:"regression",confidence:je?.confidence||"medium",evidence:[{type:"regression",sampleSize:Oa,rSquared:je?.rSquared||.5,coefficient:st,dataRange:{min:1,max:6}}],narrative:`Bedroom adjustment of $${st.toLocaleString()} per bedroom was derived from regression analysis of ${Oa} sales. Each additional bedroom adds approximately ${(Xt*100).toFixed(2)}% to property value (at median price $${ua.toLocaleString()}). Subject property has ${Xa} bedrooms.`,shortDescription:`$${st.toLocaleString()}/bed from ${Oa} sales`,isDefault:!1,methodologyNotes:`Regression analysis: Price vs bedroom count across ${Oa} comparable sales. ${os}`,assumptions:["Bedroom count affects property value in this market","Marginal value per bedroom is consistent within market segment"]}:void 0;return e.jsx(Fp,{icon:e.jsx(hv,{className:"w-5 h-5 text-rose-600"}),title:ut?"Bedrooms (Tier 2 — Weighting)":"Bedrooms",rate:ut?"$0 (suppressed)":st>0?`$${st.toLocaleString()}/bed`:"$0",description:ut?At:qa?`From ${Oa} comparable sales. Subject: ${Xa} beds.`:Oa===0?"Insufficient data to derive adjustment.":"No adjustment needed - similar bedroom counts among comparables.",confidence:ut?"high":qa?je?.confidence:void 0,support:Fe,testId:"avm-rate-beds"})})(),(()=>{const je=V.adjustmentRates?.bathroomStats,Le=V.adjustmentRates?.multicollinearity,ut=Le?.suppressBedBathDollar===!0,st=V.adjustmentRates?.bathroomDollar||0,Xt=V.adjustmentRates?.bathroomPercentPerUnit||0,ua=V.adjustmentRates?.medianPrice||0,Oa=je?.sampleSize||0,Xa=V.verifiedSubject?.bathrooms||0,qa=Oa>0&&st>0&&!ut,os=Xt>0&&ua>0?`Formula: ${(Xt*100).toFixed(2)}% × $${ua.toLocaleString()} median = $${st.toLocaleString()}/bath`:"",ya=Le?.glaVsBaths,At=ut&&ya?`Suppressed: GLA↔Baths VIF=${ya.vif.toFixed(1)}, r=${Math.abs(ya.correlation).toFixed(2)}. Bathroom count is correlated with GLA — adjusting both would double-count value. Bath match used for comp weighting instead (2× boost).`:"",Fe=qa?{adjustmentType:"bathrooms",rate:st,unit:"$/bathroom",derivationMethod:"regression",confidence:je?.confidence||"medium",evidence:[{type:"regression",sampleSize:Oa,rSquared:je?.rSquared||.5,coefficient:st,dataRange:{min:1,max:5}}],narrative:`Bathroom adjustment of $${st.toLocaleString()} per bathroom was derived from regression analysis of ${Oa} sales. Each additional bathroom adds approximately ${(Xt*100).toFixed(2)}% to property value (at median price $${ua.toLocaleString()}). Subject property has ${Xa} bathrooms.`,shortDescription:`$${st.toLocaleString()}/bath from ${Oa} sales`,isDefault:!1,methodologyNotes:`Regression analysis: Price vs bathroom count across ${Oa} comparable sales. ${os}`,assumptions:["Bathroom count affects property value in this market","Marginal value per bathroom is consistent within market segment"]}:void 0;return e.jsx(Fp,{icon:e.jsx(H0,{className:"w-5 h-5 text-cyan-600"}),title:ut?"Bathrooms (Tier 2 — Weighting)":"Bathrooms",rate:ut?"$0 (suppressed)":st>0?`$${st.toLocaleString()}/bath`:"$0",description:ut?At:qa?`From ${Oa} comparable sales. Subject: ${Xa} baths.`:Oa===0?"Insufficient data to derive adjustment.":"No adjustment needed - similar bathroom counts among comparables.",confidence:ut?"high":qa?je?.confidence:void 0,support:Fe,testId:"avm-rate-baths"})})(),(()=>{const je=V.adjustmentRates?.basementStats,Le=V.adjustmentRates?.basementFinishedPerSqft||0,ut=je?.sampleSize||0,st=V.adjustmentRates?.glaDollarPerSqft||0,Xt=ut>0&&Le>0,ua=Xt?{adjustmentType:"basement",rate:Le,unit:"$/sqft finished",derivationMethod:"mass_data",confidence:je?.confidence||"medium",evidence:[{type:"mass_data",sampleSize:ut,metric:"Finished basement adju
44stment",value:Le,range:{min:0,max:st},methodology:"Compared properties with different basement finishes"}],narrative:`Basement adjustment of $${Math.round(Le)}/sqft for finished area was calculated by comparing ${ut} recent sales. Finished basement space typically adds less value than above-ground living space.`,shortDescription:`$${Math.round(Le)}/sqft from ${ut} sales`,isDefault:!1,methodologyNotes:"Rate calculated by comparing sale prices of similar properties with different basement configurations.",assumptions:["Finished basement adds value but less than above-grade space"]}:void 0;return e.jsx(Fp,{icon:e.jsx(lp,{className:"w-5 h-5 text-slate-600"}),title:"Basement",rate:Le>0?`$${Math.round(Le)}/sqft`:"$0",description:Xt?`From ${ut} comparable sales. Finished area rate.`:ut===0?"Insufficient basement data to derive adjustment.":"No adjustment needed - similar basements among comparables.",confidence:Xt?je?.confidence:void 0,support:ua,testId:"avm-rate-basement"})})(),(()=>{const je=V.adjustmentRates?.siteStats,Le=V.adjustmentRates?.lotSizePerAcre||0,ut=je?.sampleSize||0,st=V.verifiedSubject?.lotSizeAcres||0,Xt=ut>0&&Le>0,ua=Xt?{adjustmentType:"lot_size",rate:Le,unit:"$/acre",derivationMethod:"mass_data",confidence:je?.confidence||"medium",evidence:[{type:"mass_data",sampleSize:ut,metric:"Lot size adjustment",value:Le,range:{min:0,max:5},methodology:"Compared properties with different lot sizes"}],narrative:`Lot size adjustment of $${Le.toLocaleString()}/acre was calculated by comparing ${ut} sales with different lot sizes. Larger lots generally add value, though extra land beyond typical neighborhood sizes adds less value per acre. Subject lot: ${st.toFixed(2)} acres.`,shortDescription:`$${Le.toLocaleString()}/acre from ${ut} sales`,isDefault:!1,methodologyNotes:"Rate calculated by comparing how lot size differences affect sale prices.",assumptions:["Lot size affects property value in this market"]}:void 0;return e.jsx(Fp,{icon:e.jsx(ub,{className:"w-5 h-5 text-emerald-600"}),title:"Lot Size",rate:Le>0?`$${Le.toLocaleString()}/acre`:"$0",description:Xt?`From ${ut} comparable sales. Subject: ${st.toFixed(2)} acres.`:ut===0?"Insufficient lot data to derive adjustment.":"No adjustment needed - similar lot sizes among comparables.",confidence:Xt?je?.confidence:void 0,support:ua,testId:"avm-rate-lot"})})(),(()=>{const je=V.adjustmentRates?.ageStats,Le=V.adjustmentRates?.agePerYear||0,ut=je?.sampleSize||0,st=(V.adjustmentRates?.conditionPercentPerLevel||0)>0,Xt=(V.adjustmentRates?.qualityPercentPerLevel||0)>0,ua=(st||Xt)&&Le===0,Oa=ut>0&&Le>0,Xa=Oa?{adjustmentType:"age",rate:Le*100,unit:"%/year",derivationMethod:"regression",confidence:je?.confidence||"low",evidence:[{type:"mass_data",sampleSize:ut,metric:"Age depreciation",value:Le*100,range:{min:0,max:100},methodology:"Compared properties of different ages"}],narrative:`Age adjustment of ${(Le*100).toFixed(2)}% per year was calculated by comparing ${ut} sales of properties built in different years. Newer homes typically sell for more than older homes.`,shortDescription:`${(Le*100).toFixed(2)}%/year from ${ut} sales`,isDefault:!1,methodologyNotes:"Rate calculated by comparing how property age affects sale price.",assumptions:["Property age affects value in this market"]}:void 0;return e.jsx(Fp,{icon:e.jsx(mc,{className:"w-5 h-5 text-gray-600"}),title:"Age",rate:Le>0?`${(Le*100).toFixed(2)}%/yr`:"$0",description:ua?"Included in Condition/Quality adjustments - no separate age adjustment needed.":Oa?`From ${ut} comparable sales.`:ut===0?"Insufficient age data to derive adjustment.":"No adjustment needed - similar ages among comparables.",confidence:Oa?je?.confidence:void 0,support:Xa,testId:"avm-rate-age"})})()]}),e.jsxs("div",{className:"mt-6 bg-blue-50 border border-blue-200 rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold text-blue-800 mb-2",children:"How We Calculate Adjustments"}),e.jsxs("ul",{className:"text-sm text-blue-700 space-y-1",children:[e.jsx("li",{children:"• All rates are market-derived from properties within your defined boundaries"}),e.jsx("li",{children:"• Click any card to see how it was derived and the supporting evidence"}),e.jsx("li",{children:"• Cards showing $0 indicate insufficient market data to derive that adju
44stment"}),e.jsx("li",{children:"• Adjustments compensate for differences between subject and comparable properties"})]})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full text-slate-500",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ul,{className:"w-12 h-12 mx-auto text-slate-300 mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No AVM Results"}),e.jsx("p",{className:"text-sm",children:"Run the AVM analysis first to see calculated adjustment rates"})]})})}),oe==="timeadj"&&e.jsx(NM,{marketContext:ye,assignmentId:se,marketResultsCount:p?de??0:0,submarketResultsCount:u?ge??0:0,marketResultIds:p?Be??[]:[],submarketResultIds:u?He??[]:[],marketSalesData:p?be:[],submarketSalesData:u?ue:[],subjectState:U,subjectZipCode:Ie,parentMarketLocked:p,parentSubMarketLocked:u,selectedCompsForWizard:Tt.selectedComps.map(je=>({id:je.snapshotId||je.id,address:je.address,saleDate:je.saleDate||null}))}),oe==="gla"&&e.jsx(u9,{advisorData:le,adjustmentRates:V?.adjustmentRates??null,verifiedSubject:pe,selectedComps:Tt.selectedComps,marketLocked:p,glaBand:(()=>{if(!H)return null;const je=H.glaBySource;if(je){if(fe==="mls"&&je.mls)return je.mls;if(fe==="public-record"&&je.pr)return je.pr;if(fe==="ai"&&je.ai)return je.ai}return H.gla})()}),oe==="condqual"&&e.jsx(l9,{avmResults:V?{adjustmentRates:V.adjustmentRates,verifiedSubject:V.verifiedSubject,rankedComps:V.rankedComps||[],marketStats:V.marketStats}:null,advisorData:le,selectedComps:Tt.selectedComps.map(je=>({id:je.snapshotId||je.id,address:je.address||"",price:je.price||je.salePrice||je.closePrice||0,condition:je.condition||"C3",quality:je.quality||"Q3"}))}),oe==="location"&&(()=>{const je=V?.adjustmentRates?.locationStats,Le=V?.adjustmentRates?.locationRegression,ut=je?.dollarPerPoint||Le?.dollarPerPoint||V?.adjustmentRates?.locationDollarPerPoint||0,st=je?.rSquared||Le?.rSquared||V?.adjustmentRates?.locationRSquared||0,Xt=je?.sampleSize||Le?.sampleSize||0,ua=je?.confidence||Le?.confidence||V?.adjustmentRates?.locationConfidence||"low",Oa=V?.verifiedSubject?.elsScore||pe?.elsScore||50,Xa=Tt.selectedComps.map(Oe=>({id:Oe.snapshotId||Oe.id,address:Oe.address||Oe.fullAddress||"",elsScore:Oe.echoLocationScore?.score||Oe.elsScore||0,salePrice:Oe.price||Oe.salePrice||Oe.closePrice||0,isGridComp:!0})),os=(u&&ue.length>0?ue:p&&be.length>0?be:[]).filter(Oe=>(Oe.echoLocationScore?.score||Oe.elsScore||0)>0&&(Oe.salePrice||Oe.price||0)>0).slice(0,200).map(Oe=>({elsScore:Oe.echoLocationScore?.score||Oe.elsScore||0,price:Oe.salePrice||Oe.price||0})),ya=ut,At=Xt>0&&st>0?(()=>{const Oe=[...Xa.filter(zt=>zt.salePrice>0).map(zt=>zt.salePrice),...os.map(zt=>zt.price)],rt=[...Xa.filter(zt=>zt.elsScore>0).map(zt=>zt.elsScore),...os.map(zt=>zt.elsScore)];if(Oe.length===0||rt.length===0)return 0;const $t=Oe.reduce((zt,Ua)=>zt+Ua,0)/Oe.length,na=rt.reduce((zt,Ua)=>zt+Ua,0)/rt.length;return $t-ya*na})():0,Fe=ut>0?{low:Math.round(ut*(ua==="high"?.75:ua==="medium"?.5:.25)),high:Math.round(ut*(ua==="high"?1.25:ua==="medium"?1.5:2))}:void 0;return e.jsx(x9,{subjectEls:Oa,comps:Xa,marketPool:os,ratePerPoint:ut,rSquared:st,sampleSize:Xt,confidence:ua,regressionSlope:ya,regressionIntercept:At,confidenceRange:Fe,isMarketLocked:p})})(),oe==="advisor"&&e.jsx("div",{className:"p-6",children:e.jsx(vK,{data:le,loading:W,utilityBands:H,glaBand:(()=>{const je=H;if(!je)return null;const Le=je.glaBySource;if(Le){if(fe==="mls"&&Le.mls)return Le.mls;if(fe==="public-record"&&Le.pr)return Le.pr;if(fe==="ai"&&Le.ai)return Le.ai}return je.gla})(),onApplyAdjustments:je=>{let Le=0;je.forEach(({compId:ut,adjustments:st})=>{Object.entries(st).forEach(([Xt,ua])=>{ua!==0&&Le++})}),Pe(je),B(!1),lt({title:"Adjustments Applied",description:`Applied ${Le} adjustment${Le!==1?"s":""} across ${je.length} comp${je.length!==1?"s":""}. Review and modify as needed.`})}})})]})]})]})}),e.jsx(TK,{open:We,onClose:()=>Re(!1),assignmentId:se||"",marketLocked:p,subMarketLocked:u,verifiedSubject:pe,selectedComps:Tt.selectedComps.map(je=>({id:je.id||je.mlsNumber,snapshotId:je.snapshotId,address:je.address,price:je.price,sqft:je.gla,btN
44ormalizedGla:je.btNormalizedGla,lotSqft:je.lotSize,yearBuilt:je.yearBuilt,garageSpaces:je.garageSpaces,baths:je.baths,conditionRating:je.conditionRating,basementFinishedSf:je.basementFinishedSf||0,basementSqft:je.basementSqft||0})),advisorRateDetails:le?.compSuggestions?.length?(()=>{const je={},Le=le.compSuggestions[0];return Le?.adjustments&&Le.adjustments.forEach(ut=>{ut.rate!=null&&(je[ut.factor]={rate:ut.rate,confidence:ut.rateConfidence,unit:ut.unit})}),Object.keys(je).length>0?je:null})():null,onStateChange:Me,initialState:ne,onApplyAdjustments:je=>{let Le=0;je.forEach(({adjustments:st})=>{Object.values(st).forEach(({amount:Xt})=>{Xt!==0&&Le++})});const ut=je.map(st=>({compId:st.compId,adjustments:Object.fromEntries(Object.entries(st.adjustments).map(([Xt,ua])=>[Xt,ua.amount]))}));Pe(ut),Re(!1),lt({title:"Regression Adjustments Applied",description:`Applied ${Le} adjustment${Le!==1?"s":""} across ${je.length} comp${je.length!==1?"s":""}. Review and modify as needed.`})}})]})}function y9(t){return!!t.polygon&&t.type!=="custom"&&!t.id.startsWith("drawn-area-")}function AM(t){return t.type==="custom"||t.id.startsWith("drawn-area-")}function S9(t){const a=t.filter(y9);if(a.length>0)return{label:a.length===1?a[0].name:`${a.length} areas`,kind:"named",ids:a.map(n=>n.id)};const s=t.filter(AM);return s.length>0?{label:s.length>1?`${s.length} drawn areas`:"drawn area",kind:"drawn",ids:s.map(n=>n.id)}:null}function v9(t){if(!t.polygon)return null;try{const a=t.polygon.type==="MultiPolygon"?vI(t.polygon.coordinates):NI(t.polygon.coordinates),s=rL(a,{reverse:!1});return{id:t.id,poly:s}}catch{return null}}function N9(t,a,s){const r={};if(a.length===0)return r;const n=s===null?null:new Set(s),i=[];for(const l of a){if(AM(l)){if(!n)continue;let d=0;for(const p of t){const u=p.snapshotId||p.id;u&&n.has(u)&&d++}r[l.id]=d;continue}const c=v9(l);c&&i.push(c)}if(i.length===0)return r;for(const l of i)r[l.id]=0;for(const l of t){if(!l.coordinates)continue;const c=bv([l.coordinates.lng,l.coordinates.lat]);for(const d of i)try{aT(c,d.poly)&&(r[d.id]=(r[d.id]??0)+1)}catch{}}return r}function A9({isPreloading:t,hasAnySortedProperties:a,headerPropertiesCount:s,appliedBoundaries:r,onClearScope:n,hasActiveClientFilter:i=!1}){if(t&&!a&&!i&&s===null||s===null)return e.jsx("span",{className:"font-normal text-[#62748E] shrink-0 whitespace-nowrap","data-testid":"text-property-count",children:"Loading properties..."});const c=S9(r),d=c?`${s} properties in ${c.label}`:`${s} properties`,p=c?.kind==="drawn"?c.ids.length===1?"this drawn area":"these drawn areas":c&&c.ids.length===1?"this boundary":"these boundaries";return e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-normal text-[#62748E] shrink-0 whitespace-nowrap","data-testid":"text-property-count",children:d}),c&&e.jsx("button",{type:"button",className:"inline-flex items-center text-[#90A1B9] hover:text-[#5A6C82] focus:outline-none focus:ring-2 focus:ring-[#C5A572] rounded",onClick:()=>n(c.ids),title:`Showing properties inside ${c.label} (selected comps you've added stay visible even if outside). Click to clear ${p} and restore the broader radius results.`,"aria-label":`Clear boundary scope (${c.label})`,"data-testid":"button-clear-boundary-scope",children:e.jsx(on,{className:"w-3 h-3"})})]})}function sN({providers:t}){const[a,s]=o.useState(!1);if(!t)return null;const r=t.providerDiag||null,n=t.queried||[],i=t.errors||{},l=t.finalRadiusMiles,c=n.map(d=>{const p=r?.[d],u=i[d];return{name:d,radiusTried:p?.radiusTried??l,compsReturned:p?.compsReturned??0,status:u||p?.status||"ok"}});return c.length===0?null:e.jsxs("div",{className:"mt-4 w-full max-w-xs","data-testid":"str-sources-disclosure",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1 text-xs text-slate-400 hover:text-slate-600 mx-auto",onClick:()=>s(d=>!d),"data-testid":"str-sources-toggle",children:[a?e.jsx(Du,{className:"w-3 h-3"}):e.jsx(Rr,{className:"w-3 h-3"}),"Sources"]}),a&&e.jsx("div",{className:"mt-2 border border-slate-200 rounded overflow-hidden text-xs",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-slate-50 text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-2 py-1 text-left font-medium",children:"Provider"}),e.jsx("th",{className:"px-2 py-1 text-right font-medium",children:"Radius"}),e.jsx("th",{className:"px-2 py-1 text-right font-medium",children:"Comps"}),e.jsx("th",{className:"px-2 py-1 text-left font-medium",children:"Status"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:c.map(d=>e.jsxs("tr",{className:"bg-white",children:[e.jsx("td",{className:"px-2 py-1 text-slate-700 font-medium",children:d.name}),e.jsx("td",{className:"px-2 py-1 text-right text-slate-500",children:d.radiusTried!=null?`${d.radiusTried} mi`:"—"}),e.jsx("td",{className:"px-2 py-1 text-right text-slate-500",children:d.compsReturned}),e.jsx("td",{className:"px-2 py-1 text-slate-500 truncate max-w-[120px]",children:d.status==="ok"?e.jsx("span",{className:"text-green-600",children:"ok"}
44):d.status.startsWith("NO_DATA")?e.jsx("span",{className:"text-blue-600",children:"no data"}):d.status.startsWith("API_FAILURE")?e.jsx("span",{className:"text-red-500",children:"API error"}):d.status.includes("not configured")||d.status.includes("API key")?e.jsx("span",{className:"text-amber-600",children:"not configured"}):e.jsx("span",{className:"text-slate-400 truncate",children:d.status.slice(0,30)})})]},d.name))})]})})]})}function j9({strAggregatorProviders:t}){const a=t?Object.entries(t.errors):[],s=a.filter(([,d])=>d.includes("not configured")||d.includes("API key")||d.includes("Missing"));if(s.length>0&&t?.queried.every(d=>a.some(([p,u])=>p===d&&(u.includes("not configured")||u.includes("API key")||u.includes("Missing")))))return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center px-6","data-testid":"str-empty-state",children:[e.jsx(Di,{className:"w-10 h-10 text-amber-400 mb-3"}),e.jsx("p",{className:"text-sm font-semibold text-amber-700 mb-1",children:"STR data service unavailable"}),e.jsx("p",{className:"text-xs text-amber-600 max-w-xs",children:"Short-term rental data providers are not configured for this environment. Contact your administrator to set up the required API credentials."}),e.jsxs("div",{className:"mt-3 text-xs text-amber-700 bg-amber-50 border border-amber-200 rounded px-3 py-2 max-w-xs text-left","data-testid":"str-credentials-missing",children:[e.jsx("span",{className:"font-medium",children:"Missing credentials for:"})," ",s.map(([d])=>d).join(", ")]}),e.jsx(sN,{providers:t})]});const n=a.filter(([,d])=>d.startsWith("NO_DATA:")),i=a.filter(([,d])=>d.startsWith("API_FAILURE:")),l=t?.finalRadiusMiles,c=n.map(([d])=>d).join(", ");return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center px-6","data-testid":"str-empty-state",children:[e.jsx(lp,{className:"w-10 h-10 text-slate-300 mb-3"}),e.jsx("p",{className:"text-sm font-medium text-slate-600 mb-1",children:"No short-term rental listings found"}),n.length>0&&l!=null?e.jsxs("p",{className:"text-xs text-slate-500 max-w-xs","data-testid":"str-no-data-message",children:[c," found no STR comps within ",l," mi of the subject. Try expanding the boundary or adding comps manually."]}):n.length>0?e.jsxs("p",{className:"text-xs text-slate-500 max-w-xs","data-testid":"str-no-data-message",children:["No STR comps returned by ",c,". Try expanding the boundary or adding comps manually."]}):i.length>0?e.jsxs("p",{className:"text-xs text-slate-500 max-w-xs","data-testid":"str-api-fail-message",children:["STR sources temporarily unavailable (",i.map(([d])=>d).join(", "),"). Data will reload automatically — try again in a few minutes."]}):e.jsx("p",{className:"text-xs text-slate-400 max-w-xs",children:"No STR rental comps were found in this area. Try expanding the search boundary or adding comps manually via CSV import."}),i.length>0&&n.length===0&&e.jsx("div",{className:"mt-3 text-xs text-slate-500 bg-slate-50 border border-slate-200 rounded px-3 py-2 max-w-xs","data-testid":"str-providers-temporarily-unavailable",children:"Retry will happen automatically. If the issue persists, contact your administrator."}),s.length>0&&e.jsxs("div",{className:"mt-3 text-xs text-amber-600 bg-amber-50 border border-amber-200 rounded px-3 py-2 max-w-xs","data-testid":"str-credentials-missing",children:["STR data service unavailable — missing API credentials for: ",s.map(([d])=>d).join(", ")]}),e.jsx(sN,{providers:t})]})}function T9({value:t}){const a=t>=80?"#10b981":t>=60?"#f59e0b":"#ef4444",s=11,r=2*Math.PI*s,n=r-t/100*r;return e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsxs("div",{className:"relative",children:[e.jsxs("svg",{width:26,height:26,className:"-rotate-90",children:[e.jsx("circle",{cx:13,cy:13,r:s,fill:"none",stroke:"#f1f5f9",strokeWidth:2.5}),e.jsx("circle",{cx:13,cy:13,r:s,fill:"none",stroke:a,strokeWidth:2.5,strokeDasharray:r,strokeDashoffset:n,strokeLinecap:"round"})]}),e.jsx("span",{className:"absolute inset-0 flex items-center justify-center text-[8px] font-bold",style:{color:a},children:t})]}),e.jsx("span",{className:"text-[6px] text-slate-400 uppercase mt-0.5",children:"Loc"})]})}function E1({label:t,value:a}){const r=parseInt(a.replace(/\D/g,""))<=2;return e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:Q("h-[17.5px] px-1.5 rounded flex items-center",r?"bg-[#ECFDF5]":"bg-[#FFFBEB]"),children:e.jsx("span",{className:Q("text-[9px] font-bold",r?"text-[#007A55]":"text-[#BB4D00]"),children:a})}),e.jsx("span",{className:"text-[6px] text-[#90A1B9] uppercase mt-0.5",children:t})]})}const I9={CLSD:{label:"Sold",bg:"bg-red-500",text:"text-white",overlay:"bg-red-500/90"},ACTV:{label:"Active",bg:"bg-emerald-500",text:"text-white",overlay:"bg-emerald-500/90"},PEND:{label:"Pending",bg:"bg-amber-500",text:"text-white",overlay:"bg-amber-500/90"},CTG:{label:"Contingent",bg:"bg-indigo-500",text:"text-white",overlay:"bg-indigo-500/90"},AUC:{label:"Active Under Contract",bg:"bg-blue-500",text:"text-white",overlay:"bg-blue-500/90"},CSOON:{label:"Coming Soon",bg:"bg-teal-500",text:"text-white",overlay:"bg-teal-500/90"}
44,HOLD:{label:"Hold",bg:"bg-orange-500",text:"text-white",overlay:"bg-orange-500/90"},WDRN:{label:"Withdrawn",bg:"bg-slate-400",text:"text-white",overlay:"bg-slate-400/90"},EXPD:{label:"Expired",bg:"bg-slate-400",text:"text-white",overlay:"bg-slate-400/90"},CAN:{label:"Canceled",bg:"bg-slate-400",text:"text-white",overlay:"bg-slate-400/90"},NEW:{label:"New Listing",bg:"bg-emerald-500",text:"text-white",overlay:"bg-emerald-500/90"},PCHG:{label:"Price Change",bg:"bg-sky-500",text:"text-white",overlay:"bg-sky-500/90"},BOMK:{label:"Back on Market",bg:"bg-emerald-500",text:"text-white",overlay:"bg-emerald-500/90"},RACT:{label:"Reactivated",bg:"bg-emerald-500",text:"text-white",overlay:"bg-emerald-500/90"},STR:{label:"Rental",bg:"bg-purple-500",text:"text-white",overlay:"bg-purple-500/90"},Rental:{label:"Rental",bg:"bg-purple-500",text:"text-white",overlay:"bg-purple-500/90"}};function w1(t){return t?t>=1e6?`$${(t/1e6).toFixed(1)}M`:t>=1e3?`$${Math.round(t/1e3)}K`:`$${t.toLocaleString()}`:"–"}const C9=o.memo(function({property:a,isSelected:s,isHovered:r=!1,onSelectProperty:n,onDeselectProperty:i,onClickProperty:l,onHoverProperty:c,onFocusOnMap:d,comparisonDataSource:p,compact:u=!1,orderId:m=null,isSemanticMatch:h=!1,cachesPending:f=!1}){const[v,S]=o.useState(0),[N,x]=o.useState(!1),y=XV(m),b=a.id,j=y.get(b)||null,T=!!j,O=!!a.isSameAsSubject&&!a.isSubject,E=DI(a),R=Array.isArray(a.photos)&&a.photos.length>0?a.photos:a.photoUrl?[a.photoUrl]:[],G=I9[a.status]||{label:a.status,text:"text-white",overlay:"bg-slate-500/90"},U=a.status==="CLSD",C=a.status==="STR"||a.status==="Rental",F=U?a.price:a.listPrice||a.price;return e.jsxs("div",{className:Q("bg-white rounded-xl shadow-sm border cursor-pointer overflow-hidden group transition-all duration-200 ease-out relative",r?"border-[#C5A572] shadow-lg ring-2 ring-[#C5A572]/30 scale-[1.01] -translate-y-0.5":s?"border-[#C5A572] shadow-md ring-1 ring-[#C5A572]/20 bg-[#C5A572]/[0.03]":"border-slate-200 hover:border-slate-300 hover:shadow-md hover:scale-[1.005]",T&&"opacity-60 grayscale border-l-4 border-l-slate-500",O&&!s&&!r&&"border-indigo-300 ring-1 ring-indigo-200 bg-[#FAF0E6]/60"),onClick:()=>l(a),onMouseEnter:()=>c(a.id),onMouseLeave:()=>c(null),"data-testid":`short-card-${a.id}`,children:[e.jsxs("div",{className:Q("relative",u?"h-[120px]":"h-[160px]"),children:[e.jsx(k$,{src:R.length>0?rb(R[v]):"",alt:a.address,className:"w-full h-full",photosStatus:a.photosStatus,fallbackSrc:a.photoUrl&&R.length>0?rb(a.photoUrl):void 0}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 via-trans
44parent to-transparent"}),e.jsxs("div",{className:"absolute top-2 left-2 flex items-center gap-1.5",children:[a.isSubject?e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-bold uppercase shadow-sm bg-sky-500/90 text-white","data-testid":`short-subject-badge-${a.id}`,children:"Subject"}):O?e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-bold uppercase shadow-sm bg-indigo-500/90 text-white",title:"This listing is the subject property.","data-testid":`badge-same-as-subject-${a.id}`,children:"Same as Subject"}):e.jsx("span",{className:Q("px-2 py-0.5 rounded-md text-[10px] font-bold uppercase shadow-sm",G.overlay,G.text),"data-testid":`short-status-${a.id}`,children:G.label}),E.isMultiUnitBuilding&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-bold uppercase shadow-sm bg-indigo-500/90 text-white","data-testid":`short-property-scope-${a.id}`,children:"Building"}),E.isUnit&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-bold uppercase shadow-sm bg-slate-500/90 text-white","data-testid":`short-property-scope-${a.id}`,children:"Unit"}),E.isMultiUnitBuilding&&E.unitCount!=null&&e.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-bold uppercase shadow-sm bg-violet-500/90 text-white","data-testid":`short-unit-count-${a.id}`,children:[E.unitCount," units"]}),E.unitCountConflict&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-bold uppercase shadow-sm bg-amber-500/90 text-white","data-testid":`short-unit-count-conflict-${a.id}`,"aria-label":`Unit count conflict: ${E.unitCountAlternatives?.filter((A,M,B)=>B.findIndex(oe=>oe.value===A.value)===M)?.map(A=>`${A.value} (${A.label||A.source})`).join(" vs ")}`,title:E.unitCountAlternatives?.filter((A,M,B)=>B.findIndex(oe=>oe.value===A.value)===M)?.map(A=>`${A.value} (${A.label||A.source})`).join(" vs "),children:"Count conflict"}),T&&e.jsxs("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-bold uppercase shadow-sm bg-slate-700/90 text-white flex items-center gap-1","data-testid":`badge-excluded-${a.id}`,title:j?.reasonLabel,children:[e.jsx(QR,{size:10})," Not Used"]}),h&&e.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-bold uppercase shadow-sm bg-violet-500/90 text-white",title:"Remarks are similar in meaning to your keyword (no exact match).","data-testid":`badge-semantic-match-${a.id}`,children:"Similar match"})]}),e.jsx("button",{onClick:A=>{A.stopPropagation(),s?i(a):n(a)},className:Q("absolute top-2 right-2 w-6 h-6 rounded-md flex items-center justify-center shadow-sm transition-all duration-200",s?"bg-[#C5A572] text-white scale-110":"bg-white/80 text-slate-500 hover:bg-white hover:text-slate-700 opacity-0 group-hover:opacity-100 hover:scale-110"),"data-testid":`btn-select-short-${a.id}`,children:e.jsx(Bs,{size:14,strokeWidth:s?3:2})}),e.jsxs("div",{className:"absolute bottom-2 left-2 right-2 flex items-end justify-between",children:[e.jsx("div",{className:"text-white font-black text-lg leading-tight drop-shadow-md","data-testid":`short-price-${a.id}`,children:C&&F?`${w1(F)}/nt`:w1(F)}),U&&a.saleDate&&e.jsx("div",{className:"text-white/80 text-[9px] font-medium drop-shadow",children:new Date(a.saleDate).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"2-digit"})})]}),R.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:A=>{A.stopPropagation(),S((v-1+R.length)%R.length)},className:"absolute left-1 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-black/40 hover:bg-black/60 flex items-center justify-center text-white opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(oy,{size:12})}),e.jsx("button",{onClick:A=>{A.stopPropagation(),S((v+1)%R.length)},className:"absolute right-1 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-black/40 hover:bg-black/60 flex items-center justify-center text-white opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(fo,{size:12})}),e.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 flex gap-1",children:R.slice(0,5).map((A,M)=>e.jsx("div",{className:Q("w-1.5 h-1.5 rounded-full transition-all",M===v?"bg-white":"bg-white/40")},M))})]})]}),e.jsxs("div",{className:"p-[13px]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-[12px] font-bold text-[#1D293D] truncate leading-[15px]","data-testid":`short-address-${a.id}`,children:[C&&a.strListingName?a.strListingName:a.address,e.jsx(y$,{info:{source:a.derivedAddressSource,confidence:a.derivedAddressConfidence},testIdScope:`short-${a.id}`})]}),e.jsx("div",{className:"text-[10px] text-[#90A1B9] truncate leading-[15px] mt-0.5","data-testid":`short-sublocation-${a.id}`,children:C&&a.strListingName?`${a.address?`${a.address} · `:""}${a.city||""}${a.state?`, ${a.state}`:""}`:`${a.city||""}${a.state?`, ${a.state}`:""} ${a.zip||""}`})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[d&&e.jsx("button",{className:"p-1 rounded text-[#90A1B9] hover:text-[#62748E] hover:bg-slate-100",onClick:A=>{A.stopPropagation(),d(a)},"data-testid":`btn-focus-map-${a.id}`,children:e.jsx(Wl,{size:12})}),e.jsx("button",{className:"p-1 rounded text-[#90A1B9] hover:text-[#62748E] hover:bg-slate-100",onClick:A=>{A.stopPropagation(),l(a)},"data-testid":`btn-expand-${a.id}`,children:e.jsx(ub,{size:12})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-medium text-[#45556C] mt-2 leading-[15px] flex-wrap",children:[E.isMultiUnitBuilding?e.jsxs(e.Fragment,{children:[e.jsxs("span",{"data-testid":`short-building-unit-count-${a.id}`,children:[E.unitCount??"–"," units"]}),e.jsx("span",{"data-testid":`short-building-area-${a.id}`,children:E.buildingAreaSqft!=null?`${E.buildingAreaSqft.toLocaleStr
44ing()} building sf`:"– building sf"}),e.jsx(e$,{property:a,scope:E,className:"text-slate-500",testId:`short-unit-mix-${a.id}`})]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[a.beds??"–"," ",E.isUnit?"unit bd":"bd"]}),e.jsxs("span",{children:[yg(a.fullBathrooms,a.halfBathrooms,a.baths)," ",E.isUnit?"unit ba":"ba"]}),!C&&e.jsx("span",{children:E.isUnit?E.unitAreaSqft!=null?`${E.unitAreaSqft.toLocaleString()} unit sf`:"– unit sf":a.sqft?`${a.sqft.toLocaleString()} sf`:"– sf"})]}),C?e.jsxs(e.Fragment,{children:[e.jsx("span",{title:"Occupancy rate (last 12 months)",children:a.strOccupancyRate!=null?`${Math.round(Number(a.strOccupancyRate)*(Number(a.strOccupancyRate)<=1?100:1))}% occ`:"– occ"}),e.jsx("span",{title:"Gross revenue (last 12 months)",children:a.strGrossRevenue12mo?`$${Math.round(Number(a.strGrossRevenue12mo)/1e3)}K/yr`:"– /yr"}),a.strRating!=null&&e.jsxs("span",{className:"text-[#BB4D00]",title:`${a.strReviewCount??0} reviews`,children:["★ ",Number(a.strRating).toFixed(1),a.strReviewCount?` (${a.strReviewCount})`:""]})]}):e.jsxs("span",{children:[a.yearBuilt??"–"," yr"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 px-[13px] pb-[13px]",children:[a.echoLocationScore&&e.jsx(T9,{value:a.echoLocationScore.score}),a.qualityRating&&e.jsx(E1,{label:"Qlty",value:a.qualityRating}),a.conditionRating&&e.jsx(E1,{label:"Cond",value:a.conditionRating}),f&&!a.echoLocationScore&&!a.qualityRating&&!a.conditionRating&&e.jsxs("div",{className:"flex items-center gap-1.5 animate-pulse","aria-hidden":!0,children:[e.jsx("div",{className:"h-[26px] w-[26px] rounded-full bg-slate-100"}),e.jsx("div",{className:"h-4 w-8 rounded bg-slate-100"}),e.jsx("div",{className:"h-4 w-8 rounded bg-slate-100"})]}),(a.matchScore??a.similarityScore)!=null&&e.jsx("div",{className:"flex flex-col items-center ml-auto","data-testid":`match-badge-${a.id}`,children:e.jsxs("div",{className:"h-[22px] px-2.5 bg-[#FFFBEB] border border-[#FEE685] rounded-full flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-[9px] font-bold text-[#BB4D00] leading-[11px]",children:[a.matchScore??a.similarityScore,"%"]}),e.jsx("span",{className:"text-[7px] text-[#90A1B9] leading-[9px]",children:"Match"})]})})]}),N&&e.jsx("div",{className:"px-[13px] pb-[13px] grid grid-cols-3 gap-x-2 gap-y-0.5 border-t border-[#F1F5F9] pt-1.5",children:(C?[{label:"ADR",value:a.strAverageDailyRate?`$${Math.round(Number(a.strAverageDailyRate))}`:"–"},{label:"Occ",value:a.strOccupancyRate!=null?`${Math.round(Number(a.strOccupancyRate)*(Number(a.strOccupancyRate)<=1?100:1))}%`:"–"},{label:"Annual",value:a.strGrossRevenue12mo?`$${Math.round(Number(a.strGrossRevenue12mo)/1e3)}K`:"–"},{label:"Monthly",value:a.strGrossRevenue12mo?`$${Math.round(Number(a.strGrossRevenue12mo)/12/100)/10}K`:"–"},{label:"Guests",value:a.strMaxGuests?`${a.strMaxGuests}`:"–"},{label:"Reviews",value:a.strReviewCount!=null?`${a.strReviewCount}`:"–"},{label:"Dist",value:a.distance!=null&&Number.isFinite(Number(a.distance))?`${Number(a.distance).toFixed(1)} mi`:"–"},{label:"Match",value:(a.matchScore??a.similarityScore)!=null?`${a.matchScore??a.similarityScore}%`:"–"}]:[{label:"DOM",value:a.dom?.toString()??"–"},{label:"Lot",value:a.lotSqft?a.lotSqft.toLocaleString():"–"},{label:"Garage",value:a.garageSpaces?`${a.garageSpaces}-car`:"–"},{label:"Style",value:a.style??"–"},{label:"Stories",value:a.stories?.toString()??"–"},{label:"Dist",value:a.distance!=null&&Number.isFinite(Number(a.distance))?`${Number(a.distance).toFixed(1)} mi`:"–"},{label:"Match",value:(a.matchScore??a.similarityScore)!=null?`${a.matchScore??a.similarityScore}%`:"–"}]).map(A=>e.jsxs("div",{className:"text-center py-0.5",children:[e.jsx("div",{className:"text-[7px] text-[#90A1B9] uppercase",children:A.label}),e.jsx("div",{className:"text-[10px] font-semibold leading-tight text-slate-700",children:A.value})]},A.label))}),e.jsxs("div",{className:"flex items-center justify-between px-[13px] py-1.5 border-t border-[#F1F5F9]",children:[e.jsxs("button",{onClick:A=>{A.stopPropagation(),x(!N)},className:"flex items-center gap-1 text-[8px] text-[#90A1B9] hover:text-[#62748E]","data-testid":`btn-more-fields-${a.id}`,children:[e.jsx(jr,{size:9,className:"text-[#90A1B9]"}),N?"Less":"+7 more"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[m&&e.jsx(kI,{orderId:m,compId:b,compAddress:`${a.address}${a.city?`, ${a.city}`:""}${a.state?`, ${a.state}`:""}`,compAddressLine:a.address,compCity:a.city,compState:a.state,compZip:a.zip||a.zipCode||null,existing:j,compListingStatus:a.status,compSaleDate:a.saleDate,trigger:e.jsxs("button",{onClick:A=>A.stopPropagation(),className:Q("flex items-center gap-1 h-[21.5px] px-2 rounded text-[9px] font-semibold border transition-colors",T?"bg-slate-700 text-white border-slate-700 hover:bg-slate-800":"bg-white text-slate-600 border-slate-300 hover:bg-slate-50"),title:T?`Excluded: ${j?.reasonLabel}`:"Mark as Not Used","data-testid":`button-not-used-${a.id}`,children:[e.jsx(QR,{size:9})," ",T?"Excluded":"Not Used"]})}),e.jsxs("button",{onClick:A=>{A.stopPropagation(),s?i(a):n(a)},className:Q("flex items-center gap-1 h-[21.5px] px-3 rounded text-[9px] font-semibold transition-all duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.1)]",s?"bg-[#C5A572] text-white hover:bg-[#A18A60]":"bg-[#072034] text-white hover:bg-[#0a2f4c]"),"data-testid":`btn-add-comp-${a.id}`,children:[e.jsx(Bs,{size:9,strokeWidth:s?2.5:2})," ",s?"Selected":"Add"]})]})]})]})});function R9(t,a){return t<=0?1:a?t>=640?2:1:t>=1150?4:t>=850?3:t>=550?2:1}function E9({properties:t,showMapPanel:a,hoveredPropertyId:s,isCompSelected:r,handleSelectProperty:n,handleDeselectProperty:i,handleClickProperty:l,handleHoverProperty:c,comparisonDataSource:d,assignmentId:p,semanticOnlyIds:u,cac
44hesPending:m,strProviders:h}){const f=o.useRef(null),[v,S]=o.useState(0);o.useLayoutEffect(()=>{const j=f.current;if(!j)return;S(j.clientWidth);const T=new ResizeObserver(O=>{for(const E of O)S(E.contentRect.width)});return T.observe(j),()=>T.disconnect()},[]);const N=R9(v,a),x=o.useMemo(()=>{const j=[];for(let T=0;T<t.length;T+=N)j.push(t.slice(T,T+N));return j},[t,N]),y=x.length+(h?1:0),b=t2({count:y,getScrollElement:()=>f.current,estimateSize:()=>300,overscan:4});return e.jsx("div",{ref:f,className:"flex-1 overflow-y-auto","data-testid":"virtualized-card-grid",children:e.jsx("div",{style:{height:b.getTotalSize(),position:"relative",width:"100%"},className:"px-3 pt-3",children:b.getVirtualItems().map(j=>{const T=j.index>=x.length,O=T?[]:x[j.index];return e.jsx("div",{"data-index":j.index,ref:b.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${j.start}px)`},children:T?e.jsx("div",{className:"flex justify-center pt-2 pb-3",children:e.jsx(sN,{providers:h})}):e.jsx("div",{className:"grid gap-3 pb-3",style:{gridTemplateColumns:`repeat(${N}, minmax(0, 1fr))`},children:O.map(E=>e.jsx(C9,{property:E,isSelected:r(E),isHovered:s===E.id,onSelectProperty:n,onDeselectProperty:i,onClickProperty:l,onHoverProperty:c,comparisonDataSource:d,orderId:p||null,isSemanticMatch:!!(u&&(u.has(E.snapshotId||E.id)||u.has(E.id))),cachesPending:m},E.id))})},j.key)})})})}function w9(t){const{isPreloading:a,sortedProperties:s,headerPropertiesCount:r,appliedBoundaries:n,setAppliedBoundaries:i,setBoundaryRenderWarning:l,setBoundaryRenderFallbackActive:c,selectedCount:d,reportGridCount:p,reportSlotsAvailable:u,enableStr:m,propertyTypeFilter:h,setPropertyTypeFilter:f,strProperties:v,enableUad36:S,compSelectionMode:N,setCompSelectionMode:x,semanticOnlyIds:y,semanticSearchDegraded:b=!1,cachesPending:j=!1,cardsHydrating:T=!1,heavyCachePending:O=!1,comparisonDataSource:E,setComparisonDataSource:R,showMapPanel:G,onBack:U,handleProceedToCleanup:C,strAggregatorLoading:F,strCompResults:A,strRentalComps:M,strAggregatorProviders:B,labViewMode:oe,geometrySearchMeta:ae,geometrySearchInFlight:D,geometrySearchEmpty:_,hasDrawnShapes:$,lastGeometrySearchRef:z,currentShapes:V,displayProperties:le,state:W,searchInFlightRef:me,hasCachedState:Z,shapesInitialized:pe,subjectCoordinates:se,loadingPhase:fe,preloadStageLabel:ue,isCompSelected:be,handleSelectProperty:H,handleDeselectProperty:ye,handleClickProperty:de,handleHoverProperty:ge,assignmentId:Be,setShowToolbarFilterPanel:He,selectedCompIdSet:Ie,handleSortChange:ce,columnSort:Pe,setColumnSort:We,handleFocusPropertyOnMap:Re,subjectElsFactors:ne,handleElsOverride:Me,visibleColumns:lt,setVisibleColumns:Tt,handleSaveColumnsAsDefault:je,showSelectedOnly:Le,setShowSelectedOnly:ut,subjectRowData:st,aiAnalysisReady:Xt,bgCqPollingComplete:ua,batchScoresLoaded:Oa,isResultsRefreshing:Xa,selectionPending:qa=!1,backgroundPinCount:os,isBgWidenLoading:ya=!1}=t,At=Xa??(W.isLoading||m&&F&&h==="rentals");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"h-[50px] shrink-0 bg-white flex items-center px-[13px]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] whitespace-nowrap",children:[e.jsx(A9,{isPreloading:a,hasAnySortedProperties:s.length>0,headerPropertiesCount:ya?null:r,appliedBoundaries:n,hasActiveClientFilter:typeof W.filters.remarksSearch=="string"&&W.filters.remarksSearch.trim().length>0,onClearScope:Fe=>{const Oe=new Set(Fe);i(rt=>rt.filter($t=>!Oe.has($t.id))),l(null),c(!1)}}),typeof os=="number"&&os>0&&e.jsxs("span",{className:"font-normal text-[#90A1B9] shrink-0",title:"Muted gray pins on the map are nearby comps from the broader library. They are not part of the results list.","data-testid":"text-background-pin-count",children:["+",os," nearby on map"]}),e.jsx("span",{className:"text-[#90A1B9] shrink-0",children:"|"}),e.jsxs("span",{className:"font-normal text-[#C5A572] shrink-0",children:[d," selected"]}),u!==void 0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[#90A1B9] shrink-0",children:"|"}),e.jsxs("span",{className:"text-[11px] text-slate-500 shrink-0",children:[p??d," in grid",e.jsx("span",{className:"mx-1",children:"|"}),"Available: ",e.jsx("span",{className:u===0?"text-red-500 font-medium":"text-slate-700 font-medium",children:u})]})]})]}),m&&e.jsx("div",{className:"flex items-center gap-2 ml-4",children:e.jsxs("div",{className:"flex items-center border rounded-md overflow-hidden text-xs",children:[e.jsxs("button",{className:Q("px-2 py-1",h==="sales"?"bg-slate-200 font-medium":"bg-white hover:bg-slate-50"),onClick:()=>f("sales"),"data-testid":"filter-sales-only",children:[e.jsx(Fo,{className:"w-3 h-3 inline mr-1"}),"Sales"]}),e.jsxs("button",{className:Q("px-2 py-1 border-x",h==="rentals"?"bg-purple-100 font-medium text-purple-700":"bg-white hover:bg-slate-50"),onClick:()=>f("rentals"),"data-testid":"filter-rentals-only",children:[e.jsx(lp,{className:"w-3 h-3 inline mr-1"}),"Rentals",v.length>0&&e.jsx(kt,{className:"ml-1 h-4 px-1 text-[10px] bg-purple-500",children:v.length})]}),e.jsx("button",{className:Q("px-2 py-1",h==="all"?"bg-slate-200 font-medium":"bg-white hover:bg-slate-50"),onClick:()=>f("all"),"data-testid":"filter-all-types",children:"All"})]})}),S&&x&&e.jsxs("div",{className:"flex items-center gap-2 ml-4","data-testid":"comp-selection-mode-toggle",children:[e.jsx("span",{className:"text-[11px] text-slate-500",children:"Select as:"}),e.jsxs("div",{className:"flex items-center border rounded-md overflow-hidden text-xs",children:[e.jsxs("button",{className:Q("px-2 py-1",(N??"sale")==="sale"?"bg-slate-200 font-medium":"bg-white hover:bg-slate-50"),onClick:()=>x("sale"),"data-testid":"mode-sale-comps",children:[e.jsx(Fo,{className:"w-3 h-3 inline mr-1"}),"Sale comps"]}),e.jsxs("button",{className:Q("px-2 py-1 border-l",N==="rental"?"bg-emerald-100 font-medium text-emerald-700":"bg-white hover:bg-slate-50"),onClick:()=>x("rental"),"data-testid":"mode-rental-comps",children:[e.jsx(lp,{className:"w-3 h-3 inline mr-1"}),"Rental comps"]})]})]}),e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:"flex items-center h-[25px] bg-white border border-[#
44E2E8F0] rounded overflow-hidden",children:["MLS","PR","AI"].map(Fe=>{const Oe={MLS:"mls",PR:"public-record",AI:"ai"},$t={mls:"MLS","public-record":"PR",ai:"AI"}[E]===Fe;return e.jsxs("button",{onClick:()=>R(Oe[Fe]),"data-testid":`btn-toolbar-source-${Fe}`,className:Q("px-[11px] h-full text-[10px] font-semibold transition-all duration-150",$t?"flex items-center gap-1 px-[8px] h-[19px] mx-[3px] bg-[#072034] rounded text-white shadow-[0_1px_3px_rgba(0,0,0,0.1),0_1px_2px_-1px_rgba(0,0,0,0.1)]":"text-[#62748E] hover:text-[#45556C]"),children:[Fe==="AI"&&$t&&e.jsx(nL,{size:9,className:"inline mr-0.5"}),Fe]},Fe)})})]}),!G&&e.jsxs("div",{className:"shrink-0 px-3 py-2 border-b bg-slate-50 flex items-center justify-between",children:[e.jsxs(De,{size:"sm",variant:"outline",onClick:U,className:"gap-1.5 h-8","data-testid":"button-back-collapsed",children:[e.jsx(yN,{className:"w-3.5 h-3.5"}),"Back"]}),e.jsxs(De,{size:"sm",onClick:C,className:"gap-1.5 h-8 bg-green-600 hover:bg-green-700","data-testid":"button-continue-collapsed",children:["Next",e.jsx(Zp,{className:"w-3.5 h-3.5"})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:m&&h==="rentals"&&!F&&A.length===0&&(!M||M.length===0)?e.jsx(j9,{strAggregatorProviders:B}):oe==="cards"||oe==="cards-map"?e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[m&&h==="rentals"&&le.length>0&&B&&(B.succeeded?.length??0)>0&&Object.keys(B.errors??{}).length>0&&e.jsxs("div",{className:"mx-3 mt-3 flex items-start gap-2 rounded border border-purple-200 bg-purple-50 px-3 py-2 text-xs text-purple-800","data-testid":"banner-str-partial-results",children:[e.jsx(Ns,{className:"w-4 h-4 mt-0.5 flex-shrink-0 text-purple-400"}),e.jsxs("span",{children:["Showing partial STR results from: ",e.jsx("strong",{children:B.succeeded.join(", ")}),"."," ","One or more sources (",Object.keys(B.errors).join(", "),") could not be reached — coverage may be incomplete."]})]}),b&&e.jsx("div",{className:"mx-3 mt-3 rounded border border-slate-200 bg-slate-50 px-3 py-1.5 text-[11px] text-slate-500","data-testid":"notice-semantic-degraded",children:"Showing exact keyword matches only — similar-meaning matches are temporarily unavailable."}),ae?.partialFailure&&!ae?.fallbackAborted&&$&&e.jsxs("div",{role:"alert",className:"mx-3 mt-3 flex items-start justify-between gap-3 rounded border-2 border-rose-300 bg-rose-50 px-3 py-3 text-sm text-rose-900 shadow-sm","data-testid":"banner-geometry-partial-failure",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ns,{className:"w-5 h-5 mt-0.5 flex-shrink-0 text-rose-600"}),e.jsxs("span",{children:[e.jsx("strong",{className:"font-semibold",children:"Search incomplete — data provider error."}),e.jsx("span",{className:"block text-xs text-rose-800 mt-0.5",children:le.length>0?"The current results may be incomplete. Redraw to retry before relying on this search.":"No empty result was recorded. Redraw to retry."})]})]}),e.jsxs(De,{type:"button",size:"sm",variant:"ghost",className:"h-7 px-2 text-rose-800 hover:bg-rose-100","data-testid":"button-retry-partial-search",disabled:D||!z.current,onClick:()=>{const Fe=z.current;Fe&&typeof Fe.rerun=="function"&&Fe.rerun()},children:[e.jsx(Kl,{className:"w-3 h-3 mr-1"}),"Redraw / retry"]})]}),O?e.jsx(Qd,{className:"flex-1",children:e.jsx("div",{className:Q("grid gap-3 p-3",G?"grid-cols-1 xl:grid-cols-2":"grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"),"data-testid":"heavy-cache-skeleton-grid",children:Array.from({length:6}).map((Fe,Oe)=>e.jsxs("div",{className:"bg-white rounded-lg border border-slate-200 animate-pulse overflow-hidden","data-testid":`skeleton-card-heavy-cache-${Oe}`,children:[e.jsx("div",{className:"h-32 bg-slate-200"}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsx("div",{className:"h-3 bg-slate-200 rounded w-16"}),e.jsx("div",{className:"h-4 bg-slate-200 rounded w-3/4"}),e.jsx("div",{className:"h-5 bg-slate-200 rounded w-24"})]})]},Oe))})}):le.length>0?e.jsxs("div",{className:"relative flex-1 min-h-0 overflow-hidden flex flex-col",children:[(D||qa)&&e.jsx("div",{className:"absolute inset-0 z-10 bg-white/60 flex items-center justify-center","data-testid":qa?"comp-selection-
44pending-overlay":"geometry-search-overlay",role:"status",children:e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-white/95 px-3 py-2 text-xs font-medium text-slate-600 shadow-sm",children:[e.jsx(za,{className:"w-4 h-4 animate-spin text-[#C5A572]"}),qa?"Finishing property data…":"Refreshing results…"]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",style:D||qa?{pointerEvents:"none"}:void 0,children:e.jsx(E9,{properties:le,showMapPanel:G,hoveredPropertyId:W.hoveredPropertyId,isCompSelected:be,handleSelectProperty:H,handleDeselectProperty:ye,handleClickProperty:de,handleHoverProperty:ge,comparisonDataSource:E,assignmentId:Be,semanticOnlyIds:y,cachesPending:j,strProviders:m&&h==="rentals"?B:null})})]}):e.jsx(Qd,{className:"flex-1",children:e.jsx("div",{className:Q("grid gap-3 p-3",G?"grid-cols-1 xl:grid-cols-2":"grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"),children:T&&!W.isLoading?e.jsx(e.Fragment,{children:Array.from({length:6}).map((Fe,Oe)=>e.jsxs("div",{className:"bg-white rounded-lg border border-slate-200 animate-pulse overflow-hidden","data-testid":`skeleton-card-hydrating-${Oe}`,children:[e.jsx("div",{className:"h-32 bg-slate-200"}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsx("div",{className:"h-3 bg-slate-200 rounded w-16"}),e.jsx("div",{className:"h-4 bg-slate-200 rounded w-3/4"}),e.jsx("div",{className:"h-5 bg-slate-200 rounded w-24"})]})]},Oe))}):n.length===0&&V.circles.length===0&&V.polygons.length===0&&le.length===0&&!W.isLoading&&!me.current&&!(!Z&&!pe&&se)?e.jsx(e.Fragment,{children:e.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-16 text-center","data-testid":"no-boundary-prompt",children:[e.jsx(Wl,{className:"w-10 h-10 text-slate-300 mb-3"}),e.jsx("p",{className:"text-sm font-medium text-slate-500",children:"Draw or select a boundary to see results"}),e.jsx("p",{className:"text-xs text-slate-400 mt-1",children:"Use the map tools to define your search area"})]})}):(ya||W.isLoading||!Z&&!pe&&se&&!(typeof W.filters.remarksSearch=="string"&&W.filters.remarksSearch.trim().length>0)||m&&F&&h==="rentals")&&(le.length===0||ya)?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"col-span-full flex items-center justify-center gap-2 py-3","data-testid":"search-loading-message",children:[e.jsx(za,{className:"w-4 h-4 animate-spin text-blue-500"}),e.jsx("span",{className:"text-sm text-slate-500 font-medium","data-testid":"text-loading-phase-cards",children:ya&&!W.isLoading?"Loading all results…":fe||ue||"Loading nearby sales…"})]}),Array.from({length:6}).map((Fe,Oe)=>e.jsxs("div",{className:"bg-white rounded-lg border border-slate-200 animate-pulse overflow-hidden","data-testid":`skeleton-card-${Oe}`,children:[e.jsx("div",{className:"h-32 bg-slate-200"}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsx("div",{className:"h-3 bg-slate-200 rounded w-16"}),e.jsx("div",{className:"h-4 bg-slate-200 rounded w-3/4"}),e.jsx("div",{className:"h-5 bg-slate-200 rounded w-24"}),e.jsxs("div",{className:"flex gap-3 mt-2",children:[e.jsx("div",{className:"h-3 bg-slate-200 rounded w-10"}),e.jsx("div",{className:"h-3 bg-slate-200 rounded w-10"}),e.jsx("div",{className:"h-3 bg-slate-200 rounded w-14"})]})]})]},Oe))]}):le.length===0?e.jsx("div",{className:"col-span-full flex flex-col items-center justify-center py-12 text-center","data-testid":"comp-empty-state",children:D?e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"w-10 h-10 text-slate-400 mb-3 animate-spin","data-testid":"geometry-search-loading"}),e.jsx("p",{className:"text-sm font-medium text-slate-600 mb-1",children:"Expanding search…"}),e.jsx("p",{className:"text-xs text-slate-400 max-w-xs",children:"Looking up listings inside the drawn boundary. Areas outside the pre-loaded zone may take a few seconds."})]}):_&&$?e.jsxs(e.Fragment,{children:[e.jsx(Eu,{className:"w-10 h-10 text-slate-300 mb-3"}),ae?.partialFailure?e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"w-10 h-10 text-rose-500 mb-3"}),e.jsx("p",{className:"text-sm font-semibold text-rose-700 mb-1","data-testid":"geometry-search-incomplete",children:"Search incomplete — data provider error."}),e.jsx("p",{className:"text-xs text-rose-700 max-w-xs","data-testid":"text-geometry-empty-reason",children:"No empty result was recorded. Redraw to retry before relying on this search."})]}):ae?.fallbackError?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm font-medium text-rose-600 mb-1","data-testid":"geometry-search-empty",children:"Live MLS lookup failed"}),e.jsx("p",{className:"text-xs text-slate-400 max-w-xs","data-testid":"text-geometry-empty-reason",children:"We could not reach PropMix for the drawn boundary, so only cached comps were considered. Try again in a moment, or widen your boundary to use cached data."})]}):(ae?.propMixRawCount??0)>0?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm font-medium text-slate-600 mb-1","data-testid":"geometry-search-empty",children:[ae?.propMixRawCount," listings found, 0 matched your filters"]}),e.jsx("p",{className:"text-xs text-slate-400 max-w-xs","data-testid":"text-geometry-empty-reason",children:"Live MLS returned listings in this area, but your current Sold/Beds/Price/Year filters dropped them all. Relax a filter chip to see them."})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm font-medium text-slate-600 mb-1","data-testid":"geometry-search-empty",children:"No matching properties in this area"}),e.jsxs("p",{className:"text-xs text-slate-400 max-w-xs","data-testid":"text-geometry-empty-reason",children:["We checked cached data",ae?.fallbackAttempted?" and live MLS":""," for the drawn boundary. Try widening the area or relaxing your filters."]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[e.jsxs(De,{type:"button",size:"sm",variant:"outline","data-testid":"button-retry-geometry-search",disabled:D||!z.current,onClick:()=>{const Fe=z.current;Fe&&typeof Fe.rerun=="function"&&Fe.rerun()},children:[e.jsx(Kl,{className:"w-3.5 h-3.5 mr-1.5"}),"Retry live search"]}),e.jsxs(De,{type:"button",size:"sm",variant:"ghost","data-testid":"button-loosen-filters",onClick:()=>He(!0),children:[e.jsx(pf,{className:"w-3.5 h-3.5 mr-1.5"}),"Loosen filters"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Eu,{className:"w-10 h-10 text-slate-300 mb-3"}),e.jsx("p",{className:"text-sm font-medium text-slate-600 mb-1",children:W.error==="PROPERTY_DATA_SERVICE_UNAVAILABLE"?"Property data service unavailable":!$&&n.length===0?"Draw a boundary on the map to find comps":"No properties found"}),e.jsx("p",{className:"text-xs text-slate-400 max-w-xs",children:W.error==="PROPERTY_DATA_SERVICE_UNAVAILABLE"?"PropMix API credentials are not configured. Contact your administrator to set up property search.":!$&&n.length===0?"Use the map tools to draw a radius or polygon, or pick a saved boundary. Your default filters are already applied.":"Try adjusting your filters or expanding the search area."})]})}):null})}),e.jsxs("div",{className:"px-3 py-2 border-t border-slate-200 bg-slate-50 flex items-center justify-between shrink-0","data-testid":"cards-footer-bar",children:[e.jsxs("span",{className:"text-[10px] text-slate-500",children:[r===null?`${d} selected`:`${d} selected of ${r}`,u!==void 0&&e.jsxs("span",{className:`ml-2 ${u===0?"text-red-500":""}`,children:["· ",p??d," in grid · Available: ",u]})]}),At&&le.length>0&&e.jsxs("span",{className:"flex items-center gap-1.5 text-[10px] text-blue-500","data-testid":"cards-refresh-indicator",children:[e.jsx("span",{className:"w-2.5 h-2.5 border border-blue-400 border-t-transparent roun
44ded-full animate-spin"}),"Refreshing results…"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative flex-1 min-h-0",children:[qa&&e.jsx("div",{className:"absolute inset-0 z-20 bg-white/60 flex items-center justify-center","data-testid":"comp-selection-pending-overlay",role:"status",children:e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-white/95 px-3 py-2 text-xs font-medium text-slate-600 shadow-sm",children:[e.jsx(za,{className:"w-4 h-4 animate-spin text-[#C5A572]"}),"Finishing property data…"]})}),e.jsx("div",{className:"h-full",style:qa?{pointerEvents:"none"}:void 0,children:e.jsx(ZG,{properties:le,selectedCompIdSet:Ie,isCompSelected:be,isLoading:W.isLoading||m&&F&&h==="rentals",loadingPhase:fe||ue,hoveredPropertyId:W.hoveredPropertyId,onHoverProperty:ge,onClickProperty:de,onSelectProperty:H,onDeselectProperty:ye,selectedCount:d,sortBy:W.filters.sortBy,onSortChange:ce,columnSort:Pe??void 0,onColumnSortChange:Fe=>We(Fe??void 0),viewMode:"list",onFocusOnMap:Re,subjectElsFactors:ne,onElsOverride:Me,comparisonDataSource:E,visibleColumns:lt,onVisibleColumnsChange:Tt,onSaveColumnsAsDefault:je,strMode:m&&h!=="sales",showSelectedOnly:Le,onToggleShowSelectedOnly:()=>ut(Fe=>!Fe),subjectRow:st,emptyStateMessage:W.error==="PROPERTY_DATA_SERVICE_UNAVAILABLE"?"Property data service unavailable":void 0,emptyStateSubMessage:W.error==="PROPERTY_DATA_SERVICE_UNAVAILABLE"?"PropMix API credentials are not configured. Contact your administrator to set up property search.":void 0,noBoundaries:n.length===0&&V.circles.length===0&&V.polygons.length===0&&!W.isLoading&&!me.current,showMapPanel:G,aiAnalysisReady:Xt||ua||Oa,elsLoaded:Oa,isPreloading:a,initialLoading:!Z&&!pe&&!!se,stableCount:r,hasActiveClientFilter:typeof W.filters.remarksSearch=="string"&&W.filters.remarksSearch.trim().length>0})})]}),m&&h==="rentals"&&B&&le.length>0&&e.jsx("div",{className:"flex justify-center py-2 border-t border-slate-100 bg-white",children:e.jsx(sN,{providers:B})})]})})]})}function P9(t){const{searchFailure:a,setSearchFailure:s,setState:r,handleSearchRef:n,searchInFlightRef:i,subjectAddressForReport:l,enableStr:c,isPreloading:d,preloadFailed:p,preloadStatus:u,stageLabel:m,strAggregatorLoading:h,reviewingLock:f,exitReviewMode:v,handleUnlockMarket:S,handleUnlockSubMarket:N,lockedMarketCount:x=null,lockedSubMarketCount:y=null,lockedMarketPropertyCardsLength:b=0,lockedSubmarketPropertyCardsLength:j=0}=t,T=f==="market"?(x??null)||b:f==="submarket"?(y??null)||j:0;return e.jsxs(e.Fragment,{children:[a&&e.jsxs("div",{className:"shrink-0 bg-red-50 border-b border-red-200 px-4 py-3 flex items-start gap-3","data-testid":"property-lab-error-banner",role:"alert",children:[e.jsx(Di,{className:"w-5 h-5 text-red-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold text-red-800","data-testid":"text-property-lab-error-operation",children:a.title}),e.jsx("p",{className:"text-xs text-red-700 mt-0.5 break-words","data-testid":"text-property-lab-error-message",children:a.description})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(De,{size:"sm",variant:"outline",onClick:()=>{s(null),r(O=>({...O,error:null})),n.current&&!i.current&&n.current()},"data-testid":"button-property-lab-retry",children:[e.jsx(Kl,{className:"w-3.5 h-3.5 mr-1.5"}),"Retry"]}),e.jsx(De,{size:"sm",variant:"ghost",asChild:!0,"data-testid":"button-property-lab-report",children:e.jsxs("a",{href:(()=>{const O=`Property Lab search stalled — ${l||"unknown subject"}`,E=["Property Lab Step 4 search did not return in time.","",`Subject: ${l||"(no subject address available)"}`,`Title: ${a.title}`,`Description: ${a.description}`,`When: ${new Date().toISOString()}`,"","(Please leave the additional context here — screenshots / what you were trying to do.)"];return`mailto:[email protected]?subject=${encodeURIComponent(O)}&body=${encodeURIComponent(E.join(`
45`))}`})(),target:"_blank",rel:"noopener noreferrer",children:[e.jsx(a2,{className:"w-3.5 h-3.5 mr-1.5"}),"Report"]})}),e.jsx(De,{size:"sm",variant:"ghost",onClick:()=>s(null),"data-testid":"button-property-lab-error-dismiss",children:e.jsx(ur,{className:"w-4 h-4"})})]})]}),!c&&d&&!p&&(u.propertiesFound??0)>0&&e.jsxs("div",{className:"shrink-0 bg-blue-50 border-b border-blue-200 px-4 py-2 text-xs text-blue-700","data-testid":"preload-status-banner",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(za,{className:"w-3 h-3 animate-spin shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium transition-opacity duration-500",children:u.isStalled?"This is taking longer than usual...":(()=>{const O=u.propertiesFound||0,E=u.propertiesProcessed||0;if(m){const R=O>0&&E>0?Math.min(Math.round(E/O*100),99):null;return R!==null?`${m} ${R}%`:m}if(O>0&&E>0){const R=Math.min(Math.round(E/O*100),99);return R>=90?"Almost done loading nearby sales...":`Loading nearby sales data... ${R}%`}return"Loading nearby sales data..."})()},u.currentStage||"banner-init"),e.jsx("span",{className:"ml-2 text-blue-500 hidden sm:inline",children:"You can keep searching while we load results."})]})]}),u.propertiesFound&&u.propertiesFound>0&&(u.propertiesProcessed??0)>0&&e.jsx("div",{className:"mt-1.5 h-1.5 bg-blue-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-500 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.min(Math.round((u.propertiesProcessed||0)/u.propertiesFound*100),99)}%`},"data-testid":"preload-progress-bar"})})]}),!c&&p&&e.jsx("div",{className:"shrink-0 bg-amber-50 border-b border-amber-200 px-4 py-1.5 flex items-center gap-2 text-xs text-amber-700","data-testid":"preload-error-banner",children:e.jsx("span",{children:"Some property enhancements are unavailable right now. Search results are still fully usable."})}),c&&h&&e.jsxs("div",{className:"shrink-0 bg-purple-50 border-b border-purple-200 px-4 py-1.5 flex items-center gap-2 text-xs text-purple-700","data-testid":"str-aggregator-loading-banner",children:[e.jsx(za,{className:"w-3 h-3 animate-spin"}),e.jsx("span",{children:"Searching STR databases for rental comps..."})]}),f&&e.jsxs("div",{className:"shrink-0 bg-blue-50 border-b border-blue-200 px-4 py-2 flex items-center justify-between","data-testid":"review-mode-banner",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-blue-700",children:[e.jsx(of,{className:"w-3.5 h-3.5"}),e.jsxs("span",{className:"font-medium",children:["Viewing locked ",f==="market"?"Market":"Sub-Market",T>0&&e.jsxs("span",{className:"ml-1 font-semibold","data-testid":`text-review-locked-count-${f}`,children:["(",T," ",T===1?"property":"properties"," locked)"]})]}),e.jsx("span",{className:"text-blue-500",children:"— showing filters and boundaries from lock time"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:v,className:"text-xs font-medium text-blue-700 hover:text-blue-900 px-2.5 py-1 rounded-md hover:bg-blue-100 transition-colors border border-blue-200","data-testid":"btn-exit-review",children:"Back to current"}),e.jsxs("button",{onClick:()=>f==="market"?S():N(),className:"text-xs font-medium text-red-600 hover:text-red-800 px-2.5 py-1 rounded-md hover:bg-red-50 transition-colors border border-red-200 flex items-center gap-1","data-testid":"btn-unlock-from-review",children:[e.jsx(lf,{className:"w-3 h-3"}),"Unlock"]})]})]})]})}function US(t,a,s){return t.length>0?{cards:t,reason:"hydrated"}:!a||a.length===0?{cards:[],reason:"no-result-ids"}:{cards:[],reason:"hydration-empty"}}function P1(){return{records:[]}}function jM(t){const{filters:a={},monthsBack:s}=t;return[`s:${(Array.isArray(a.statusSelection)&&a.statusSelection.length>0?[...a.statusSelection]:Array.isArray(a.status)?[...a.status]:a.status?[String(a.status)]:[]).map(l
45=>String(l)).sort().join("|")}`,`mb:${s}`,`pt:${a.propertyType??""}`,`pts:${Array.isArray(a.propertyTypes)&&a.propertyTypes.length>0?[...a.propertyTypes].map(l=>String(l)).sort().join("|"):""}`,`pmin:${a.minPrice??""}`,`pmax:${a.maxPrice??""}`,`bdmin:${a.minBeds??""}`,`bdmax:${a.maxBeds??""}`,`bamin:${a.minBaths??""}`,`bamax:${a.maxBaths??""}`,`sfmin:${a.minSqft??""}`,`sfmax:${a.maxSqft??""}`,`yrmin:${a.minYearBuilt??""}`,`yrmax:${a.maxYearBuilt??""}`,`zg:${a.includeZeroGla===!1?"0":"1"}`].join(";")}function TM(t){let a=1/0,s=-1/0,r=1/0,n=-1/0,i=!1;for(const l of t)if(!(!l||typeof l!="object")){if(l.type==="polygon"&&Array.isArray(l.path))for(const c of l.path){const d=typeof c.lat=="number"?c.lat:parseFloat(c.lat),p=typeof c.lng=="number"?c.lng:parseFloat(c.lng);!Number.isFinite(d)||!Number.isFinite(p)||(d<a&&(a=d),d>s&&(s=d),p<r&&(r=p),p>n&&(n=p),i=!0)}else if(l.type==="circle"&&l.center){const c=typeof l.center.lat=="number"?l.center.lat:parseFloat(l.center.lat),d=typeof l.center.lng=="number"?l.center.lng:parseFloat(l.center.lng),p=typeof l.radiusMeters=="number"?l.radiusMeters:parseFloat(l.radiusMeters);if(!Number.isFinite(c)||!Number.isFinite(d)||!Number.isFinite(p))continue;const u=p/111320,m=p/(111320*Math.max(.1,Math.cos(c*Math.PI/180)));a=Math.min(a,c-u),s=Math.max(s,c+u),r=Math.min(r,d-m),n=Math.max(n,d+m),i=!0}}return i?{minLat:a,maxLat:s,minLng:r,maxLng:n}:null}function O9(t,a,s,r){const n=Date.now(),i=t.records.find(l=>l.filterHash===s&&l.monthsBack===r&&l.bbox.minLat===a.minLat&&l.bbox.maxLat===a.maxLat&&l.bbox.minLng===a.minLng&&l.bbox.maxLng===a.maxLng);if(i){i.recordedAt=n;return}t.records.length>=64&&(t.records.sort((l,c)=>l.recordedAt-c.recordedAt),t.records.shift()),t.records.push({bbox:a,filterHash:s,monthsBack:r,recordedAt:n})}function L9(t){const{geometries:a,subject:s,filtersForGeom:r,monthsBack:n,assignmentId:i,abortRef:l,propmixCoverageRef:c,setGeometrySearchInFlight:d,setGeometrySearchEmpty:p,setGeometrySearchMeta:u,commitAtomicResult:m,clearAtomicCommitPending:h,sessionShapes:f,lastGeometrySearchRef:v,rerun:S,toast:N,dismissMlsFailureToast:x,mlsFailureToastRef:y,propertyTypeFilter:b}=t,j=b==="rentals",T=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),O=jM({filters:r,monthsBack:n}),E=TM(a);l.current&&l.current.abort();const R=new AbortController;l.current=R,d(!0),p(!1),u(null),x(),v.current={geometries:a,subject:s??null,rerun:S},mT("Map","atomic-boundary-session: request",{shapeCount:a.length,types:a.map(G=>G.type)},{}),dn("/api/comps/search-by-geometry",{geometries:a,subject:s,filters:r,monthsBack:n,assignmentId:i,source:"user"},{throwOnSuccessFalse:!1,signal:R.signal,retryTransientErrors:!0}).then(G=>{if(l.current!==R||R.signal.aborted)return;const U=Array.isArray(G?.sales)?G.sales:[],C=G?.meta||{},F=Number.isFinite(C.propMixRawCount)?C.propMixRawCount:0,A=Number.isFinite(C.propMixPostFilterCount)?C.propMixPostFilterCount:0,M=Number.isFinite(C.cachedMatchedCount)?C.cachedMatchedCount:0,B=C.propMixDropReasons&&typeof C.propMixDropReasons=="object"?C.propMixDropReasons:{};if(U.length===0&&console.warn("[PropertyLab] geometry search zero-result",{reqId:C.reqId??null,zeroReason:C.zeroReason??"unknown",partialFailure:C.partialFailure??null,fallbackError:C.fallbackError??null,countShortCircuited:!!C.countShortCircuited}),console.log("[PropertyLab] atomic-boundary-session trace",{shapeCount:a.length,types:a.map(ae=>ae.type),propMixRaw:F,propMixPostFilter:A,finalReturned:U.length,dropReasons:B,elapsedMs:Math.round((typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now())-T),filterHash:O,fallbackAttempted:!!C.fallbackAttempted,fallbackError:C.fallbackError??null,cachedMatchedCount:M,countShortCircuited:!!C.countShortCircuited,zeroReason:C.zeroReason??null}),E&&C.fallbackAttempted&&!C.countShortCircuited&&!C.partialFailure&&!C.fallbackError&&E&&O9(c.current,E,O,n),mT("Map","atomic-boundary-session: response",{matched:U.length,fallback:C.fallbackAttempted,propMixRawCount:F,fallbackError:C.fallbackError},{}),u({fallbackAttempted:!!C.fallbackAttempted,fallbackError:C.fallbackError??null,fallbackAborted:!!C.fallbackAborted,partialFailure:!!C.partialFailure,propMixRawCount:F,propMixPostFilterCount:A,cachedMatchedCount:M,propMixDropReasons:B,zeroReason:C.zeroReason??null}),!C.fallbackAborted){if(U.length===0&&C.partialFailure){p(!0);return}if(C.fallbackError&&!j){x();const ae=N({title:"Live MLS lookup failed",description:"Could not fetch fresh listings for the drawn area. Showing cached results only — there may be more comps available.",variant:"destructive"});y.current={dismiss:ae.dismiss}}else x();if(U.length===0){p(!0),C.fallbackError||(F>0?N({title:`${F} listings found, none matched filters`,description:"Live MLS returned listings in this area but your current filters dropped them all. Try relaxing Sold/Beds/Price."}):N({title:"No comps in drawn area",description:C.fallbackAttempted?"No matching listings found for the drawn boundary, even after a live MLS lookup. Try widening the area or relaxing filters.":"No matching cached comps in this boundary. Try widening the area or relaxing filters."})),m([],f);return}console.log(`[PropertyLab] Atomic boundary commit: ${U.length} fetched comps — caller merges into live pool and derives drawnAreaPropertyIds`),m(U,f)}}).catch(G=>{G&&G.name==="AbortError"||R.signal.aborted||l.current!==R||(h(),console.warn("[PropertyLab] atomic-boundary-session failed:",G),N({title:"Boundary search failed",description:"Could not load comps for the drawn area. Try again or adju
45st the boundary.",variant:"destructive"}))}).finally(()=>{l.current===R&&(l.current=null,d(!1))})}function D9(t){const{shapes:a,subjectCoordinates:s,allCachedSales:r,state:n,assignmentId:i,propmixCoverageRef:l,setHasDrawnShapes:c,setGeometrySearchInFlight:d,setGeometrySearchEmpty:p,setGeometrySearchMeta:u,setAppliedBoundaries:m,commitAtomicResult:h,clearAtomicCommitPending:f,lastGeometrySearchRef:v,mlsFailureToastRef:S,geometrySearchAbortRef:N,toast:x,dismissMlsFailureToast:y,rerun:b,propertyTypeFilter:j}=t,T=a.polygons.length>0||a.circles.length>0,O=a.polygons.length>0;if(O&&a.polygons.find(R=>wV(R.path))){x({title:"Your shape crosses itself",description:"Please redraw the boundary so its edges don't overlap.",variant:"destructive"}),d(!1);return}if(c(T),T){const E=[...a.polygons.map(R=>({type:"polygon",path:R.path})),...a.circles.map(R=>({type:"circle",center:R.center,radiusMeters:R.radiusMeters}))];if(E.length>0){const R={status:n.filters.statusSelection?.length?n.filters.statusSelection:n.filters.status,propertyType:(()=>{const C=(n.filters.propertyTypes||[]).filter(F=>F!=="STR");return C.length===1?C[0]:void 0})(),propertyTypes:(()=>{const C=(n.filters.propertyTypes||[]).filter(F=>F!=="STR");return C.length>0?C:void 0})(),minPrice:n.filters.minPrice,maxPrice:n.filters.maxPrice,minBeds:n.filters.minBeds,maxBeds:n.filters.maxBeds,minBaths:n.filters.minBaths,maxBaths:n.filters.maxBaths,minSqft:n.filters.minSqft,maxSqft:n.filters.maxSqft,minYearBuilt:n.filters.minYearBuilt,maxYearBuilt:n.filters.maxYearBuilt,includeZeroGla:n.filters.includeZeroGla!==!1},G=n.filters.monthsBack??12;console.log("[PropertyLab] refresh-trigger polygon-draw (atomic)",{preRefreshPropertyCount:n.properties.length,shapeCount:E.length,allCachedSales:r.length,filterHash:jM({filters:R,monthsBack:G}),polyBbox:TM(E)}),mT("Map","runShapesChange: delegating to atomicBoundarySession",{shapeCount:E.length,types:E.map(C=>C.type)},{});const U=s?{lat:s.lat,lng:s.lng}:void 0;L9({geometries:E,subject:U,filtersForGeom:R,monthsBack:G,assignmentId:i,sessionShapes:a,abortRef:N,propmixCoverageRef:l,setGeometrySearchInFlight:d,setGeometrySearchEmpty:p,setGeometrySearchMeta:u,commitAtomicResult:h,clearAtomicCommitPending:f,lastGeometrySearchRef:v,rerun:b,toast:x,dismissMlsFailureToast:y,mlsFailureToastRef:S,propertyTypeFilter:j})}m(O?R=>{if(!R.find(U=>U.type==="custom"&&U.id.startsWith("drawn-area-"))){const U={id:`drawn-area-${Date.now()}`,type:"custom",name:"Drawn Area",color:"#6366f1"};return[...R,U]}return R}:R=>R.filter(G=>!G.id.startsWith("drawn-area-")))}else m(E=>E.filter(R=>!R.id.startsWith("drawn-area-")))}async function k9(t){const{shapes:a,signal:s,subjectCoordinates:r,state:n,assignmentId:i}=t,l=[...a.polygons.map(u=>({type:"polygon",path:u.path})),...a.circles.map(u=>({type:"circle",center:u.center,radiusMeters:u.radiusMeters}))];if(l.length===0)return null;const c=r?{lat:r.lat,lng:r.lng}:void 0,d={status:n.filters.statusSelection?.length?n.filters.statusSelection:n.filters.status,propertyType:(()=>{const u=(n.filters.propertyTypes||[]).filter(m=>m!=="STR");return u.length===1?u[0]:void 0})(),propertyTypes:(()=>{const u=(n.filters.propertyTypes||[]).filter(m=>m!=="STR");return u.length>0?u:void 0})(),minPrice:n.filters.minPrice,maxPrice:n.filters.maxPrice,minBeds:n.filters.minBeds,maxBeds:n.filters.maxBeds,minBaths:n.filters.minBaths,maxBaths:n.filters.maxBaths,minSqft:n.filters.minSqft,maxSqft:n.filters.maxSqft,minYearBuilt:n.filters.minYearBuilt,maxYearBuilt:n.filters.maxYearBuilt,includeZeroGla:n.filters.includeZeroGla!==!1},p=n.filters.monthsBack??12;try{const u=await Zn("/api/comps/search-by-geometry",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({geometries:l,subject:c,filters:d,monthsBack:p,assignmentId:i,countOnly:!0}),signal:s,throwOnSuccessFalse:!1});if(s.aborted)return null;const m=typeof u?.total=="number"?u.total:null;return m==null?null:{total:m,fallbackAttempted:!!u?.meta?.fallbackAttempted}}catch(u){return typeof DOMException<"u"&&u instanceof DOMException&&u.name==="AbortError"||u&&typeof u=="object"&&u.name==="AbortError"||console.warn("[PropertyLab] live-count request failed:",u instanceof Error?u.message:String(u)),null}}function O1(t,a){const s=new Set(t.map(n=>n.snapshotId||n.id)),r=a.filter(n=>!s.has(n.snapshotId||n.id));return r.length>0?[...t,...r]:t}function M9(t,a){return a.polygons.length>0||a.circles.length>0?LI(t,a):[]}function F9(t,a){return!(a.polygons.length>0||a.circles.length>0)||t.length===0?null:LI(t,a)}function _9({marketLocked:t,onToggleMarketLock:a,marketLockDisabled:s=!1,isLockingMarket:r=!1,subMarketLocked:n,onToggleSubMarketLock:i,subMarketLockDisabled:l=!1,isLockingSubMarket:c=!1,activeFilterCount:d=0,onToggleFilters:p,showFilterPanel:u=!1,labViewMode:m="cards-map",onViewModeChange:h,showMapPanel:f=!0,sortBy:v="match",onSortChange:S,extraActions:N,onOpenMatchSettings:x}){const y=m==="cards"||m==="cards-map",b=m==="list"||m==="list-map",j=m==="map";return e.jsxs("div",{className:"h-[58px] px-[14px] flex items-center gap-0 bg-white shrink-0 z-20 border-b border-[#
45E2E8F0]","data-testid":"lab-toolbar",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsxs("button",{onClick:a,disabled:r||s&&!t,"data-testid":"btn-toolbar-market-lock",className:Q("flex items-center gap-1.5 w-[72px] h-[36px] justify-center rounded text-[12px] font-semibold transition-all",t?"bg-[#D0FAE5] text-[#007A55] hover:bg-[#bbf7d0]":r?"bg-slate-100 text-slate-400 cursor-wait":s?"bg-slate-50 text-slate-300 cursor-not-allowed":"bg-slate-100 text-slate-500 hover:bg-slate-200"),children:[r?e.jsx(za,{className:"w-3 h-3 animate-spin"}):t?e.jsx(Hr,{size:10}):e.jsx(lf,{size:10})," Market"]}),e.jsxs("button",{onClick:i,disabled:c||l&&!n,"data-testid":"btn-toolbar-submarket-lock",className:Q("flex items-center gap-1.5 w-[104px] h-[36px] justify-center rounded text-[12px] font-semibold transition-all ml-2",n?"bg-[#D0FAE5] text-[#007A55] hover:bg-[#bbf7d0]":c?"bg-slate-100 text-slate-400 cursor-wait":l?"bg-slate-50 text-slate-300 cursor-not-allowed":"bg-slate-100 text-slate-500 hover:bg-slate-200"),children:[c?e.jsx(za,{className:"w-3 h-3 animate-spin"}):n?e.jsx(Hr,{size:10}):e.jsx(lf,{size:10})," Sub-Market"]}),N&&e.jsx("div",{className:"ml-2 flex items-center gap-2","data-testid":"lab-toolbar-extra-actions",children:N})]}),e.jsx("div",{className:"flex-1"}),h&&e.jsxs("div",{className:"flex items-center h-[36px] bg-white border border-[#E2E8F0] rounded overflow-hidden",children:[e.jsxs("button",{onClick:()=>h?.("cards"),"data-testid":"btn-toolbar-view-cards",className:Q("flex items-center gap-1 h-[28px] px-2 mx-1 rounded text-[10px] font-medium transition-all",y?"bg-[#072034] text-white shadow-[0_1px_3px_rgba(0,0,0,0.1),0_1px_2px_-1px_rgba(0,0,0,0.1)]":"text-[#62748E] hover:bg-slate-50"),children:[e.jsx(JO,{size:10})," Cards"]}),e.jsxs("button",{onClick:()=>h?.("list"),"data-testid":"btn-toolbar-view-list",className:Q("flex items-center gap-1 h-[28px] px-2 rounded text-[10px] font-medium transition-all",b?"bg-[#072034] text-white shadow-[0_1px_3px_rgba(0,0,0,0.1),0_1px_2px_-1px_rgba(0,0,0,0.1)]":"text-[#62748E] hover:bg-slate-50"),children:[e.jsx(SN,{size:10})," List"]}),e.jsxs("button",{onClick:()=>h?.("map"),"data-testid":"btn-toolbar-toggle-map",className:Q("flex items-center gap-1 h-[28px] px-2 mx-1 rounded text-[10px] font-medium transition-all",j?"bg-blue-600 text-white shadow-[0_1px_3px_rgba(0,0,0,0.1),0_1px_2px_-1px_rgba(0,0,0,0.1)]":f?"bg-[#072034] text-white shadow-[0_1px_3px_rgba(0,0,0,0.1),0_1px_2px_-1px_rgba(0,0,0,0.1)]":"text-[#62748E] hover:bg-slate-50"),children:[e.jsx(mN,{size:10})," Map"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-2",children:[S&&e.jsxs("select",{value:v,onChange:T=>S?.(T.target.value),className:"h-[36px] w-[130px] bg-white border border-[#E2E8F0] rounded px-[13px] text-[12px] text-[#45556C] outline-none cursor-pointer hover:border-[#C5A572]/50 transition-colors","data-testid":"select-sort-cards",children:[e.jsx("option",{value:"match",children:"Sort: Match"}),e.jsx("option",{value:"price-asc",children:"Price ↑"}),e.jsx("option",{value:"price-desc",children:"Price ↓"}),e.jsx("option",{value:"distance",children:"Distance"}),e.jsx("option",{value:"newest",children:"Newest"}),e.jsx("option",{value:"sqft-desc",children:"Sq Ft ↓"}),e.jsx("option",{value:"sqft-asc",children:"Sq Ft ↑"}),e.jsx("option",{value:"location",children:"Location"}),e.jsx("option",{value:"avm",children:"AVM"})]}),x&&e.jsxs("button",{onClick:x,"data-testid":"btn-toolbar-match-settings",className:"flex items-center gap-1.5 h-[36px] px-3 rounded border border-[#E2E8F0] bg-white text-[10px] font-medium text-[#45556C] hover:border-[#C5A572] hover:text-[#8b744f] transition-colors",children:[e.jsx(AI,{size:11})," Match settings"]}),e.jsxs("button",{onClick:p,"data-testid":"btn-toolbar-toggle-filters",className:Q("flex items-center gap-1.5 w-[80px] h-[36px] justify-center rounded text-[10px] font-medium transition-all",u?"bg-[#C5A572] text-white shadow-sm":"bg-[#072034] text-white hover:bg-[#0a2f4c]"),children:[e.jsx(pf,{size:11})," Filters",d>0&&e.jsx("span",{className:"flex items-center justify-center bg-[#C5A572] text-white text-[8px] font-bold w-[13px] h-[10px] rounded-full leading-none",children:d})]})]})]})}const U9=[5,10,15,20,25],V9=[5,10,15,20,25],$9=[5,10,15,20],B9=["Pool","Roofdeck","Water","Golf Course","Rehab","Addition"],L1=[{value:0,label:"Studio"},{value:1,label:"1"},{value:2,label:"2"},{value:3,label:"3"},{value:4,label:"4"},{value:5,label:"5+"}],D1=[{value:1,label:"1"},{value:1.5,label:"1.5"},{value:2,label:"2"},{value:2.5,label:"2.5"},{value:3,label:"3"},{value:3.5,label:"3.5"},{value:4,label:"4+"}],rN=[{value:"ACTV",label:"Active",group:"For Sale"},{value:"NEW",label:"New",group:"For Sale"},{value:"PCHG",label:"Price Change",group:"For Sale"},{value:"BOMK",label:"Back on Market",group:"For Sale"},{value:"RACT",label:"Re-activated",group:"For Sale"},{value:"CSOON",label:"Coming Soon",group:"For Sale"},{value:"PEND",label:"Pending",group:"Under Contract"},{value:"CTG",label:"Contingent",group:"Under Contract"},{value:"AUC",label:"Active Under Contract",group:"Under Contract"},{value:"HOLD",label:"Hold",group:"Under Contract"},{value:"CLSD",label:"Sold",group:"Sold"},{value:"WDRN",label:"Withdrawn",group:"Off Market"},{value:"EXPD",label:"Expired",group:"Off Market"},{value:"CAN",label:"Canceled",group:"Off Market"}];({...Object.fromEntries(rN.map(t=>[t.value,t.label]))});const z9=["Single Family","Condo","Townhouse","Multi-Family","Duplex","Land","Other","STR"],q9=[{value:0,label:"Any"},{value:1,label:"1+"},{value:2,label:"2+"},{value:3,label:"3+"}],Y9=[{value:1,label:"1"},{value:2,label:"2"},{value:3,label:"3+"}],G9=[{value:"Ranch",label:"Ranch"},{value:"Split Level",label:"Split Level"},{value:"Colonial",label:"Colonial"},{value:"Cape Cod",label:"Cape Cod"},{value:"Contemporary",label:"Contemporary"},{value:"Victorian",label:"Victorian"},{value:"Tudor",label:"Tudor"},{value:"Craftsman",label:"Craftsman"},{value:"Bungalow",label:"Bungalow"},{value:"Mediterranean",label:"Mediterranean"},{value:"Georgian",label:"Georgian"},{value:"Traditional",label:"Traditional"},{value:"Modern",label:"Modern"},{value:"Bi-Level",label:"Bi-Level"},{value:"Tri-Level",label:"Tri-Level"}];function a0({label:t,minValue:a,maxValue:s,onMinChange:r,onMaxChange:n,prefix:i="",testIdPrefix:l,formatDisplay:c}
45){const[d,p]=o.useState(a?.toString()??""),[u,m]=o.useState(s?.toString()??""),[h,f]=o.useState(!1),[v,S]=o.useState(!1);o.useEffect(()=>{h||p(a?.toString()??"")},[a,h]),o.useEffect(()=>{v||m(s?.toString()??"")},[s,v]);const N=R=>{const G=R.replace(/[^0-9]/g,"");if(!G)return;const U=parseInt(G,10);return!isNaN(U)&&U>0?U:void 0},x=(R,G)=>R===void 0?"":c?c(R):R.toLocaleString(),y=()=>{f(!1);const R=N(d);r(R),p(R?.toString()??"")},b=()=>{S(!1);const R=N(u);n(R),m(R?.toString()??"")},j=()=>{f(!0),p(a?.toString()??"")},T=()=>{S(!0),m(s?.toString()??"")},O=h?d:x(a),E=v?u:x(s);return e.jsx("div",{className:"space-y-3","data-testid":`filter-${l}-content`,children:e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs text-gray-500 mb-1",children:"Min"}),e.jsxs("div",{className:"relative",children:[i&&e.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-sm text-gray-400 pointer-events-none",children:i}),e.jsx(ze,{type:"text",inputMode:"numeric",placeholder:"No Min",value:O,onChange:R=>p(R.target.value),onFocus:j,onBlur:y,onKeyDown:R=>{R.key==="Enter"&&R.target.blur()},className:Q("h-9 text-sm",i&&"pl-6"),"data-testid":`input-${l}-min`})]})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs text-gray-500 mb-1",children:"Max"}),e.jsxs("div",{className:"relative",children:[i&&e.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-sm text-gray-400 pointer-events-none",children:i}),e.jsx(ze,{type:"text",inputMode:"numeric",placeholder:"No Max",value:E,onChange:R=>m(R.target.value),onFocus:T,onBlur:b,onKeyDown:R=>{R.key==="Enter"&&R.target.blur()},className:Q("h-9 text-sm",i&&"pl-6"),"data-testid":`input-${l}-max`})]})]})]})})}function VS({label:t,minValue:a,maxValue:s,presets:r,onMinChange:n,onMaxChange:i,prefix:l="",testIdPrefix:c,allowDecimals:d=!1}){const[p,u]=o.useState(""),[m,h]=o.useState(""),[f,v]=o.useState(!1),[S,N]=o.useState(!1),x=a!==void 0&&!r.some(O=>O.value===a),y=s!==void 0&&!r.some(O=>O.value===s),b=O=>{if(d){const E=O.replace(/[^0-9.]/g,""),R=parseFloat(E);return!isNaN(R)&&R>=0?R:null}else{const E=O.replace(/[^0-9]/g,""),R=parseInt(E,10);return!isNaN(R)&&R>0?R:null}},j=()=>{const O=b(p);O!==null&&(n(O),v(!1))},T=()=>{const O=b(m);O!==null&&(i(O),N(!1))};return e.jsx("div",{className:"space-y-3","data-testid":`filter-${c}-content`,children:e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs text-gray-500 mb-1",children:"Min"}),f?e.jsxs("div",{className:"flex gap-1",children:[e.jsx(ze,{type:"text",placeholder:l?`${l}Amount`:"Amount",value:p,onChange:O=>u(O.target.value),onKeyDown:O=>O.key==="Enter"&&j(),className:"h-9 text-sm flex-1",autoFocus:!0,"data-testid":`input-${c}-min-custom`}),e.jsx(De,{size:"sm",className:"h-9 px-2",onClick:j,children:e.jsx(Bs,{className:"w-4 h-4"})}),e.jsx(De,{size:"sm",variant:"ghost",className:"h-9 px-2",onClick:()=>v(!1),children:e.jsx(ur,{className:"w-4 h-4"})})]}):e.jsxs("select",{value:x?"custom":a??"",onChange:O=>{O.target.value==="custom"?(v(!0),u(a?.toString()||"")):n(O.target.value?Number(O.target.value):void 0)},className:"w-full h-9 px-2 text-sm border rounded-md bg-white","data-testid":`select-${c}-min`,children:[e.jsx("option",{value:"",children:"No Min"}),r.map(O=>e.jsxs("option",{value:O.value,children:[l,O.label]},O.value)),e.jsx("option",{value:"custom",children:"Custom..."}),x&&e.jsxs("option",{value:a,children:[l,a?.toLocaleString()]})]})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs text-gray-500 mb-1",children:"Max"}),S?e.jsxs("div",{className:"flex gap-1",children:[e.jsx(ze,{type:"text",placeholder:l?`${l}Amount`:"Amount",value:m,onChange:O=>h(O.target.value),onKeyDown:O=>O.key==="Enter"&&T(),className:"h-9 text-sm flex-1",autoFocus:!0,"data-testid":`input-${c}-max-custom`}),e.jsx(De,{size:"sm",className:"h-9 px-2",onClick:T,children:e.jsx(Bs,{className:"w-4 h-4"})}),e.jsx(De,{size:"sm",variant:"ghost",className:"h-9 px-2",onClick:()=>N(!1),children:e.jsx(ur,{className:"w-4 h-4"})})]}
45):e.jsxs("select",{value:y?"custom":s??"",onChange:O=>{O.target.value==="custom"?(N(!0),h(s?.toString()||"")):i(O.target.value?Number(O.target.value):void 0)},className:"w-full h-9 px-2 text-sm border rounded-md bg-white","data-testid":`select-${c}-max`,children:[e.jsx("option",{value:"",children:"No Max"}),r.map(O=>e.jsxs("option",{value:O.value,children:[l,O.label]},O.value)),e.jsx("option",{value:"custom",children:"Custom..."}),y&&e.jsxs("option",{value:s,children:[l,s?.toLocaleString()]})]})]})]})})}function H9({selected:t,onChange:a,activeStatusCounts:s}){const r=c=>{t.includes(c)?a(t.filter(d=>d!==c)):a([...t,c])},n=c=>s?c==="AUC"?s.underContract:c==="CTG"?s.contingent:c==="ACTV"?s.active:null:null,i=["Sold","For Sale","Under Contract","Off Market"],l=c=>{const d=rN.filter(u=>u.group===c).map(u=>u.value);if(d.every(u=>t.includes(u)))a(t.filter(u=>!d.includes(u)));else{const u=[...t];d.forEach(m=>{u.includes(m)||u.push(m)}),a(u)}};return e.jsx("div",{className:"space-y-3 max-h-[300px] overflow-y-auto","data-testid":"filter-status-content",children:i.map(c=>{const d=rN.filter(u=>u.group===c),p=d.every(u=>t.includes(u.value));return d.some(u=>t.includes(u.value)),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-gray-500",children:c}),e.jsx("button",{onClick:()=>l(c),className:"text-[10px] font-medium text-blue-600 hover:text-blue-800 hover:underline","data-testid":`btn-select-all-${c.toLowerCase().replace(/\s+/g,"-")}`,children:p?"Deselect All":"Select All"})]}),e.jsx("div",{className:"space-y-1",children:d.map(u=>{const m=n(u.value);return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer hover:bg-gray-50 p-1 rounded",children:[e.jsx(Pa,{checked:t.includes(u.value),onCheckedChange:()=>r(u.value),"data-testid":`checkbox-status-${u.value}`}),e.jsx("span",{className:"text-sm flex-1",children:u.label}),m!==null&&e.jsx("span",{className:"text-xs font-medium text-gray-500 tabular-nums","data-testid":`count-status-${u.value}`,children:m})]},u.value)})})]},c)})})}function W9({mode:t,preset:a,startDate:s,endDate:r,presets:n,onModeChange:i,onPresetChange:l,onStartDateChange:c,onEndDateChange:d}){const[p,u]=o.useState(!1),[m,h]=o.useState(!1);return e.jsxs("div",{className:"space-y-3","data-testid":"filter-date-content",children:[e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsx("button",{onClick:()=>i("preset"),className:Q("px-3 py-1 text-sm rounded-md transition-colors",t!=="custom"?"bg-blue-600 text-white":"bg-gray-100 text-gray-700 hover:bg-gray-200"),"data-testid":"btn-date-preset-mode",children:"Preset"}),e.jsx("button",{onClick:()=>i("custom"),className:Q("px-3 py-1 text-sm rounded-md transition-colors",t==="custom"?"bg-blue-600 text-white":"bg-gray-100 text-gray-700 hover:bg-gray-200"),"data-testid":"btn-date-custom-mode",children:"Custom"})]}),t!=="custom"?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(f=>e.jsx("button",{onClick:()=>l(f.value),className:Q("px-3 py-1.5 text-sm rounded-md transition-colors border",a===f.value?"bg-blue-600 text-white border-blue-600":"bg-white text-gray-700 border-gray-200 hover:border-blue-300"),"data-testid":`btn-date-${f.value}mo`,children:f.label},f.value))}):e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs text-gray-500 mb-1",children:"Start"}),e.jsxs(xn,{open:p,onOpenChange:u,children:[e.jsx(bn,{asChild:!0,children:e.jsxs(De,{variant:"outline",className:"w-full justify-start text-left font-normal h-9 text-sm","data-testid":"btn-start-date",children:[e.jsx(mc,{className:"mr-2 h-3 w-3"}),s?Vi(new Date(s),"M/d/yy"):"Pick"]})}),e.jsx(yn,{className:"w-auto p-0",align:"start",children:e.jsx(Uv,{mode:"single",selected:s?new Date(s):void 0,onSelect:f=>{c(f?.toISOString()),u(!1)},initialFocus:!0})})]})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs text-gray-500 mb-1",children:"End"}),e.jsxs(xn,{open:m,onOpenChange:h,children:[e.jsx(bn,{asChild:!0,children:e.jsxs(De,{variant:"outline",className:"w-full justify-start text-left font-normal h-9 text-sm","data-testid":"btn-end-date",children:[e.jsx(mc,{className:"mr-2 h-3 w-3"}
45),r?Vi(new Date(r),"M/d/yy"):"Pick"]})}),e.jsx(yn,{className:"w-auto p-0",align:"start",children:e.jsx(Uv,{mode:"single",selected:r?new Date(r):void 0,onSelect:f=>{d(f?.toISOString()),h(!1)},initialFocus:!0})})]})]})]})]})}function K9({filters:t,onFiltersChange:a,enableStr:s}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-0.5 max-h-60 overflow-y-auto",children:z9.filter(r=>r!=="STR"||s).map(r=>{const n=r==="STR"&&s,i=t.propertyTypes?.includes(r)??!1;return e.jsxs("label",{className:Q("flex items-center gap-2 cursor-pointer hover:bg-gray-50 px-1.5 py-1 rounded text-xs",r==="STR"&&"text-amber-700",n&&"opacity-75 cursor-not-allowed"),children:[e.jsx(Pa,{checked:i,disabled:n,onCheckedChange:l=>{if(n)return;const c=(t.propertyTypes||[]).filter(d=>s||d!=="STR");if(l){const d={propertyTypes:[...c,r]};r==="STR"&&(d.strOnly=!0),a(d)}else{const d={propertyTypes:c.filter(p=>p!==r)};r==="STR"&&(d.strOnly=!1),a(d)}},"data-testid":`checkbox-proptype-${r.replace(/\s+/g,"-")}`}),e.jsx("span",{className:Q(r==="STR"&&"font-medium"),children:r==="STR"?n?"STR (locked)":"STR":r})]},r)})}),(t.propertyTypes||[]).filter(r=>s||r!=="STR").length>0&&e.jsx("button",{type:"button",onClick:()=>a({propertyTypes:[],strOnly:!1}),className:"w-full text-[11px] text-blue-600 hover:underline mt-1 pt-1 border-t","data-testid":"button-proptype-clear",children:"Clear selection"})]})}function _d({icon:t,label:a,hasValue:s,children:r,testId:n,onClear:i,popoverClassName:l,isBlueActive:c,isExpanding:d}){const[p,u]=o.useState(!1);return e.jsxs(xn,{open:p,onOpenChange:u,children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{className:Q("flex items-center gap-1.5 h-[28px] px-3 rounded-md text-[12px] font-medium transition-all duration-150 shadow-[0_1px_2px_rgba(0,0,0,0.05)] shrink-0",c||s?"bg-[#C5A572]/10 border border-[#C5A572]/40 text-[#8B6F47]":"bg-white border border-[#E5E7EB] text-[#364153] hover:bg-slate-50 hover:border-[#C5A572]/30"),"data-testid":n,children:[c&&e.jsx(Bs,{size:14,className:"text-[#C5A572]"}),a,d?e.jsx(za,{size:14,className:"ml-0.5 animate-spin text-[#C5A572]","data-testid":`${n}-expanding`}):s&&i?e.jsx("span",{role:"button",className:"ml-0.5 p-0.5 rounded hover:bg-[#C5A572]/20 transition-colors",onClick:m=>{m.stopPropagation(),i()},"data-testid":`${n}-clear`,children:e.jsx(ur,{size:14,className:"text-[#C5A572]"})}):e.jsx(Rr,{size:14,className:"opacity-50"})]})}),e.jsx(yn,{className:l||"w-auto min-w-[260px] p-4",align:"start",children:r})]})}function k1({pool:t,formatValue:a,onSetMin:s,onSetMax:r,emptyText:n,testIdPrefix:i}){if(t.length===0)return e.jsx("div",{className:"pt-2 mt-1 border-t border-slate-100 text-[11px] text-slate-500","data-testid":`${i}-empty`,children:n});const l=[...t].sort((b,j)=>b-j),c=b=>{if(l.length===1)return l[0];const j=Math.max(0,Math.min(l.length-1,Math.floor(b*(l.length-1))));return l[j]},d=c(.25),p=c(.5),u=c(.75),m=l[0],h=l[l.length-1],f=h-m,v=Math.min(6,Math.max(2,l.length)),S=f>0?f/v:1,N=Array.from({length:v},(b,j)=>{const T=m+j*S,O=j===v-1?h+1:T+S;return l.filter(E=>E>=T&&E<O).length}),x=Math.max(...N,1),y=[{label:"p25",key:"p25",val:d},{label:"Median",key:"median",val:p},{label:"p75",key:"p75",val:u}];return e.jsxs("div",{className:"pt-2 mt-1 border-t border-slate-100 space-y-1.5","data-testid":`${i}-distribution`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] font-medium text-slate-500 uppercase tracking-wide",children:"Distribution"}),e.jsxs("span",{className:"text-[10px] text-slate-400 tabular-nums","data-testid":`${i}-distribution-count`,children:[t.length," rental",t.length===1?"":"s"]})]}),e.jsx("div",{className:"flex items-end gap-0.5 h-8","aria-hidden":"true",children:N.map((b,j)=>e.jsx("div",{className:"flex-1 bg-[#C5A572]/40 rounded-sm",style:{height:`${Math.max(b/x*100,6)}%`},title:`${b} rental${b===1?"":"s"}`},j))}),e.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:y.map(b=>e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsx("span",{className:"text-[10px] text-slate-500",children:b.label}),e.jsx("span",{className:"text-[11px] font-semibold text-slate-700 tabular-nums leading-tight","data-testid":`${i}-marker-${b.key}-value`,children:a(b.val)}),e.jsxs("div",{className:"flex gap-0.5 mt-0.5",children:[e.jsx("button",{type:"button",className:"text-[10px] px-1.5 py-0.5 rounded border border-slate-200 hover:bg-blue-50 hover:border-blue-300 hover:text-blue-700 transition-colors",onClick:()=>s(b.val),"data-testid":`${i}-marker-${b.key}-min`,children:"Min"}),e.jsx("button",{type:"button",className:"text-[10px] px-1.5 py-0.5 rounded border border-slate-200 hover:bg-blue-50 hover:border-blue-300 hover:text-blue-700 transition-colors",onClick:()=>r(b.val),"data-testid":`${i}-marker-${b.key}-max`,children:"Max"})]})]},b.key))})]})}function Q9({filters:t,onFiltersChange:a,resultCount:s,onClearFilters:r,comparisonDataSource:n="mls",onDataSourceChange:i,currentRadius:l,onRadiusChange:c,isReviewM
45ode:d=!1,enableStr:p=!1,subjectGla:u,subjectPrice:m,subjectLotSizeSqft:h,subjectYearBuilt:f,expandingFilters:v,quickPicks:S,activeStatusCounts:N,strRentalPool:x}){const y=Z=>Z%12===0?`${Z/12} Yr`:`${Z} Mo`,b=(S?.dateMonths??GE.dateMonths).slice().sort((Z,pe)=>Z-pe).map(Z=>({value:Z,label:y(Z)})),j=(S?.glaPercents??GE.glaPercents).slice().sort((Z,pe)=>Z-pe),T=t.statusSelection!==void 0?t.statusSelection:t.status||[],O=T.length>0,E=(()=>{if(T.length){const Z=T.map(pe=>rN.find(se=>se.value===pe)?.label||pe);return Z.length===1?Z[0]:`${Z.length} Status`}return"Status"})(),R=!!N&&N.active+N.underContract+N.contingent>0,G=N?`Active ${N.active} · Under Contract ${N.underContract} · Contingent ${N.contingent}`:"",U=(()=>{if(t.minBeds!==void 0||t.maxBeds!==void 0){const Z=t.minBeds,pe=t.maxBeds;if(Z!==void 0&&pe!==void 0)return Z===pe?Z===0?"Studio":`${Z} Bed`:`${Z===0?"Studio":Z}-${pe}`;if(Z!==void 0)return Z===0?"Studio+":`${Z}+`;if(pe!==void 0)return`≤${pe}`}return null})(),C=(()=>{if(t.minBaths!==void 0||t.maxBaths!==void 0){const Z=t.minBaths,pe=t.maxBaths;if(Z!==void 0&&pe!==void 0)return Z===pe?`${Z}`:`${Z}-${pe}`;if(Z!==void 0)return`${Z}+`;if(pe!==void 0)return`≤${pe}`}return null})(),F=(()=>{const Z=t.minBeds!==void 0||t.maxBeds!==void 0,pe=t.minBaths!==void 0||t.maxBaths!==void 0;return Z&&pe?`${U} bd / ${C} ba`:Z?`${U} bd`:pe?`${C} ba`:"Beds/Baths"})(),A=t.minBeds!==void 0||t.maxBeds!==void 0||t.minBaths!==void 0||t.maxBaths!==void 0,M=t.minPrice!==void 0||t.maxPrice!==void 0?`$${t.minPrice?Math.round(t.minPrice/1e3)+"K":"0"}-${t.maxPrice?Math.round(t.maxPrice/1e3)+"K":"Any"}`:"Price",B=t.minSqft!==void 0||t.maxSqft!==void 0?`${t.minSqft?.toLocaleString()??"0"}-${t.maxSqft?.toLocaleString()??"Any"}`:"Sqft",oe=t.minPrice!==void 0||t.maxPrice!==void 0?`$${t.minPrice??0}-$${t.maxPrice??"Any"}/nt`:"Nightly Rate",ae=t.minPrice!==void 0||t.maxPrice!==void 0,D=t.minOccupancyPct!==void 0||t.maxOccupancyPct!==void 0?`${t.minOccupancyPct??0}%-${t.maxOccupancyPct??100}%`:"Occupancy",_=t.minOccupancyPct!==void 0||t.maxOccupancyPct!==void 0,$=t.dateFilterField==="contract"?"Contract":"Closed",z=t.dateRangeMode==="custom"?`${$}: Custom`:t.dateRangePreset?`${$}: ${t.dateRangePreset}mo`:t.monthsBack&&t.monthsBack!==12?`${$}: ${t.monthsBack}mo`:"Date",V=t.minYearBuilt!==void 0||t.maxYearBuilt!==void 0,le=(t.propertyTypes||[]).filter(Z=>p||Z!=="STR"),W=le.length>0,me=[t.minGarage!==void 0?1:0,t.stories?.length?1:0,t.styleSelection?.length?1:0,t.minLotSqft!==void 0||t.maxLotSqft!==void 0?1:0,t.hasPool!==void 0?1:0,t.basementCategories?.length?1:0,t.conditionRatings?.length?1:0,t.qualityRatings?.length?1:0,t.minLocationScore!==void 0||t.maxLocationScore!==void 0?1:0,V?1:0,t.cityFilter?1:0,t.streetNameFilter?1:0,t.minStreetNumber!==void 0||t.maxStreetNumber!==void 0?1:0].reduce((Z,pe)=>Z+pe,0);return e.jsxs("div",{className:Q("h-[46px] flex items-center px-[14px] gap-0 bg-[#F5F7FA] border-b border-[#E2E8F0] z-10",d&&"opacity-75 pointer-events-none"),"data-testid":"filter-bar",children:[e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto flex-1",children:[!p&&e.jsx(gr,{delayDuration:200,children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("span",{className:"shrink-0",children:e.jsx(_d,{icon:Bs,label:E,hasValue:O,isBlueActive:O,isExpanding:v?.status,testId:"filter-chip-status",onClear:()=>a({statusSelection:[],status:[]}),children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{className:"text-sm font-medium",children:"Status"}),R&&e.jsxs("div",{className:"text-[11px] text-gray-600 bg-slate-50 rounded px-2 py-1.5 leading-snug","data-testid":"text-status-breakdown-popover",children:[e.jsx("div",{className:"font-medium text-gray-700 mb-0.5",children:"Active competition pool"}),e.jsx("div",{className:"tabular-nums",children:G})]}),e.jsx(H9,{selected:T,onChange:Z=>a({statusSelection:Z}),activeStatusCounts:N})]})})})}),R&&e.jsx(Wa,{side:"bottom",align:"start",className:"bg-slate-900 text-white text-[11px] tabular-nums","data-testid":"tooltip-status-breakdown",children:G})]})}),!p&&e.jsx(_d,{icon:Jj,label:A?F:"Bed/Bath",hasValue:A,onClear:()=>a({minBeds:void 0,maxBeds:void 0,minBaths:void 0,maxBaths:void 0,bedsSelection:void 0,bathsSelection:void 0}),testId:"filter-chip-beds-baths",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"filter-chip-beds",children:[e.jsx(Ja,{className:"text-sm font-medium mb-2 block",children:"Bedrooms"}),e.jsx(VS,{label:"Bedrooms",minValue:t.minBeds,maxValue:t.maxBeds,presets:L1,onMinChange:Z=>a({minBeds:Z,bedsSelection:void 0}),onMaxChange:Z=>a({maxBeds:Z,bedsSelection:void 0}),testIdPrefix:"beds"})]}),e.jsxs("div",{className:"border-t border-gray-100 pt-3","data-testid":"filter-chip-baths",children:[e.jsx(Ja,{className:"text-sm font-medium mb-2 block",children:"Bathrooms"}),e.jsx(VS,{label:"Bathrooms",minValue:t.minBaths,maxValue:t.maxBaths,presets:D1,onMinChange:Z=>a({minBaths:Z,bathsSelection:void 0}),onMaxChange:Z=>a({maxBaths:Z,bathsSelection:void 0}),testIdPrefix:"baths",allowDecimals:!0})]})]})}),!p&&e.jsx(_d,{icon:xv,label:t.minPrice!==void 0||t.maxPrice!==void 0?M:"Price",hasValue:t.minPrice!==void 0||t.maxPrice!==void 0,onClear:()=>a({minPrice:void 0,maxPrice:void 0}),testId:"filter-chip-price",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(a0,{label:"Price",minValue:t.minPrice,maxValue:t.maxPrice,onMinChange:Z=>a({minPrice:Z}),onMaxChange:Z=>a({maxPrice:Z}),prefix:"$",testIdPrefix:"price",formatDisplay:Z=>Z>=1e6?`${(Z/1e6).toFixed(Z%1e6===0?0:1)}M`:Z>
45=1e3?`${Math.round(Z/1e3).toLocaleString()}K`:Z.toLocaleString()}),m!==void 0&&m>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"text-[10px] text-slate-500","data-testid":"text-price-percent-basis",children:["Based on subject price: $",m.toLocaleString()]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:U9.map(Z=>{const pe=Math.round(m*(1-Z/100)),se=Math.round(m*(1+Z/100)),fe=t.minPrice===pe&&t.maxPrice===se;return e.jsxs("button",{type:"button",onClick:()=>a({minPrice:pe,maxPrice:se}),className:Q("px-2 py-1 text-[11px] font-medium rounded-full border transition-colors",fe?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"),"data-testid":`button-price-percent-${Z}`,children:["± ",Z,"%"]},Z)})})]})]})}),!p&&e.jsx(_d,{icon:Um,label:t.minSqft!==void 0||t.maxSqft!==void 0?B:"Sqft",hasValue:t.minSqft!==void 0||t.maxSqft!==void 0,onClear:()=>a({minSqft:void 0,maxSqft:void 0}),testId:"filter-chip-sqft",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(a0,{label:"GLA (Sqft)",minValue:t.minSqft,maxValue:t.maxSqft,onMinChange:Z=>a({minSqft:Z}),onMaxChange:Z=>a({maxSqft:Z}),testIdPrefix:"sqft",formatDisplay:Z=>Z.toLocaleString()}),u!==void 0&&u>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"text-[10px] text-slate-500","data-testid":"text-gla-percent-basis",children:["Based on subject GLA: ",u.toLocaleString()," sf"]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:j.map(Z=>{const pe=Math.round(u*(1-Z/100)),se=Math.round(u*(1+Z/100)),fe=t.minSqft===pe&&t.maxSqft===se;return e.jsxs("button",{type:"button",onClick:()=>a({minSqft:pe,maxSqft:se}),className:Q("px-2 py-1 text-[11px] font-medium rounded-full border transition-colors",fe?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"),"data-testid":`button-gla-percent-${Z}`,children:["± ",Z,"%"]},Z)})})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer","data-testid":"include-zero-gla-checkbox",children:[e.jsx("input",{type:"checkbox",checked:t.includeZeroGla!==!1,onChange:Z=>a({includeZeroGla:Z.target.checked}),className:"rounded border-slate-300 text-blue-600 focus:ring-blue-500 h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs text-slate-600",children:"Include 0 GLA"})]}),i&&e.jsx("div",{className:"pt-2 border-t border-gray-100",children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs font-medium text-slate-600",children:"GLA Data Source"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Select sqft source for display, scoring & filters"}),e.jsx("div",{className:"flex rounded-md border border-slate-200 overflow-hidden","data-testid":"gla-source-selector-filter",children:[{value:"mls",label:"MLS"},{value:"public-record",label:"PR"},{value:"ai",label:"AI"}].map(Z=>e.jsx("button",{onClick:()=>i(Z.value),className:Q("flex-1 text-[11px] font-medium py-1 px-2 transition-colors",n===Z.value?Z.value==="ai"?"bg-indigo-600 text-white":"bg-slate-700 text-white":"bg-white text-slate-500 hover:bg-slate-50"),"data-testid":`gla-source-${Z.value}`,children:Z.label},Z.value))})]})})]})}),!p&&e.jsx(_d,{icon:mc,label:t.dateRangePreset!==void 0||t.dateRangeStart!==void 0||t.dateRangeEnd!==void 0||t.dateRangeMode!==void 0||t.monthsBack!==void 0&&t.monthsBack!==12?z:"Date",hasValue:t.dateRangePreset!==void 0||t.dateRangeStart!==void 0||t.dateRangeEnd!==void 0||t.dateRangeMode!==void 0||t.monthsBack!==void 0&&t.monthsBack!==12,onClear:()=>a({dateRangePreset:void 0,dateRangeStart:void 0,dateRangeEnd:void 0,dateRangeMode:void 0,monthsBack:12}),isExpanding:v?.date,testId:"filter-chip-date",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex rounded-md overflow-hidden border border-gray-200","data-testid":"toggle-date-field",children:[e.jsx("button",{onClick:()=>a({dateFilterField:"closed",dateRangeMode:void 0,dateRangePreset:void 0,dateRangeStart:void 0,dateRangeEnd:void 0,monthsBack:void 0}),className:Q("flex-1 px-3 py-1.5 text-sm font-medium transition-colors",(t.dateFilterField??"closed")==="closed"?"bg-blue-600 text-white":"bg-white text-gray-600 hover:bg-gray-50"),"data-testid":"btn-date-field-closed",children:"Closed Date"}),e.jsx("button",{onClick:()=>a({dateFilterField:"contract",dateRangeMode:void 0,dateRangePreset:void 0,dateRangeStart:void 0,dateRangeEnd:void 0,monthsBack:void 0}),className:Q("flex-1 px-3 py-1.5 text-sm font-medium transition-colors",t.dateFilterField==="contract"?"bg-blue-600 text-white":"bg-white text-gray-600 hover:bg-gray-50"),"data-testid":"btn-date-field-contract",children:"Contract Date"})]}),e.jsx(W9,{mode:t.dateRangeMode,preset:t.dateRangePreset??t.monthsBack,startDate:t.dateRangeStart,endDate:t.dateRangeEnd,presets:b,onModeChange:Z=>a({dateRangeMode:Z}),onPresetChange:Z=>a({dateRangePreset:Z,dateRangeMode:"preset"}),onStartDateChange:Z=>a({dateRangeStart:Z,dateRangeMode:"custom"}),onEndDateChange:Z=>a({dateRangeEnd:Z,dateRangeMode:"custom"})})]})}),!p&&e.jsx(_d,{icon:gn,label:"Remarks",hasValue:!!t.remarksSearch,onClear:()=>a({remarksSearch:void 0}),testId:"filter-chip-remarks",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{className:"text-sm font-medium",children:"Search in Remarks"}),e.jsx("p",{className:"text-xs text-gray-500",children:"Find properties with specific keywords in their listing description. Separate multiple terms with commas."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ze,{type:"text",placeholder:"e.g. renovated, pool, updated",value:t.remarksSearch||"",onChange:Z=>a({remarksSearch:Z.target.value||void 0}),className:"flex-1","data-testid":"input-remarks-search"}),t.remarksSearch&&e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>a({remarksSearch:void 0}),"data-testid":"btn-clear-remarks",children:e.jsx(ur,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-[10px] text-slate-500",children:"Qu
45ick add"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:B9.map(Z=>{const se=(t.remarksSearch||"").split(",").map(be=>be.trim()).filter(Boolean),fe=se.some(be=>be.toLowerCase()===Z.toLowerCase()),ue=()=>{let be;fe?be=se.filter(ye=>ye.toLowerCase()!==Z.toLowerCase()):be=[...se,Z];const H=be.join(", ");a({remarksSearch:H||void 0})};return e.jsxs("button",{type:"button",onClick:ue,className:Q("px-2 py-1 text-[11px] font-medium rounded-full border transition-colors",fe?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"),"data-testid":`button-remarks-quick-${Z.toLowerCase().replace(/\s+/g,"-")}`,children:[fe?"− ":"+ ",Z]},Z)})})]})]})}),!p&&e.jsx(_d,{icon:Fo,label:W?le.length===1?le[0]:`${le.length} types`:"Property Type",hasValue:W,isBlueActive:W,testId:"filter-chip-proptype",onClear:()=>a({propertyTypes:[],strOnly:!1}),popoverClassName:"w-56 p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ja,{className:"text-sm font-medium",children:"Property Type"}),e.jsx(K9,{filters:t,onFiltersChange:a,enableStr:p})]})}),!p&&e.jsx(_d,{icon:AI,label:me>0?`More (${me})`:"More",hasValue:me>0,testId:"filter-chip-more",popoverClassName:"w-[min(720px,calc(100vw-2rem))] p-4 max-h-[85vh] overflow-y-auto",isBlueActive:!1,children:e.jsxs("div",{className:"columns-1 sm:columns-2 lg:columns-3 gap-6 [&>div]:break-inside-avoid [&>div]:mb-4",children:[e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Year Built"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ze,{type:"number",placeholder:"Min Year",value:t.minYearBuilt??"",onChange:Z=>a({minYearBuilt:Z.target.value?parseInt(Z.target.value):void 0}),className:"h-8 text-xs","data-testid":"input-year-min"}),e.jsx(ze,{type:"number",placeholder:"Max Year",value:t.maxYearBuilt??"",onChange:Z=>a({maxYearBuilt:Z.target.value?parseInt(Z.target.value):void 0}),className:"h-8 text-xs","data-testid":"input-year-max"})]}),f!==void 0&&f>0&&e.jsxs("div",{className:"space-y-1 mt-2",children:[e.jsxs("div",{className:"text-[10px] text-slate-500","data-testid":"text-year-range-basis",children:["Based on subject year built: ",f]}),e.jsx("div",{className:"flex gap-1",children:$9.map(Z=>{const pe=f-Z,se=f+Z,fe=t.minYearBuilt===pe&&t.maxYearBuilt===se;return e.jsxs("button",{type:"button",onClick:()=>a({minYearBuilt:pe,maxYearBuilt:se}),className:Q("flex-1 px-1 py-0.5 text-[10px] font-medium rounded-full border transition-colors whitespace-nowrap",fe?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"),"data-testid":`button-year-range-${Z}`,children:["±",Z,"y"]},Z)})})]})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Lot Size (sqft)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ze,{type:"number",placeholder:"Min",value:t.minLotSqft??"",onChange:Z=>a({minLotSqft:Z.target.value?parseInt(Z.target.value):void 0}),className:"h-8 text-xs","data-testid":"input-lot-min"}),e.jsx(ze,{type:"number",placeholder:"Max",value:t.maxLotSqft??"",onChange:Z=>a({maxLotSqft:Z.target.value?parseInt(Z.target.value):void 0}),className:"h-8 text-xs","data-testid":"input-lot-max"})]}),h!==void 0&&h>0&&e.jsxs("div",{className:"space-y-1 mt-2",children:[e.jsxs("div",{className:"text-[10px] text-slate-500","data-testid":"text-lot-percent-basis",children:["Based on subject lot size: ",h.toLocaleString()," sf"]}),e.jsx("div",{className:"flex gap-1",children:V9.map(Z=>{const pe=Math.round(h*(1-Z/100)),se=Math.round(h*(1+Z/100)),fe=t.minLotSqft===pe&&t.maxLotSqft===se;return e.jsxs("button",{type:"button",onClick:()=>a({minLotSqft:pe,maxLotSqft:se}),className:Q("flex-1 px-1 py-0.5 text-[10px] font-medium rounded-full border transition-colors whitespace-nowrap",fe?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"),"data-testid":`button-lot-percent-${Z}`,children:["±",Z,"%"]},Z)})})]})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Garage"}),e.jsx("div",{className:"flex gap-1.5",children:q9.map(Z=>{const pe=Z.value!==0&&(t.minGarage??0)===Z.value;return e.jsx("button",{onClick:()=>a({minGarage:Z.value===0?void 0:Z.value}),className:Q("px-2.5 py-1 text-xs rounded-md border",pe?"bg-blue-600 text-white border-blue-600":"bg-white text-gray-700 border-gray-200 hover:border-blue-300"),"data-testid":`btn-garage-${Z.value}`,children:Z.label},Z.value)})})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Stories"}),e.jsx("div",{className:"flex gap-1.5",children:Y9.map(Z=>e.jsx("button",{onClick:()=>{const pe=t.stories||[];pe.includes(Z.value)?a({stories:pe.filter(se=>se!==Z.value)}):a({stories:[...pe,Z.value]})},className:Q("px-2.5 py-1 text-xs rounded-md border",t.stories?.includes(Z.value)?"bg-blue-600 text-white border-blue-600":"bg-white text-gray-700 border-gray-200 hover:border-blue-300"),"data-testid":`btn-stories-${Z.value}`,children:Z.label},Z.value))})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Style"}),e.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:G9.map(Z=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer hover:bg-gray-50 p-1 rounded text-xs",children:[e.jsx(Pa,{checked:t.styleSelection?.includes(Z.value)??!1,onCheckedChange:pe=>{const se=t.styleSelection||[];a(pe?{styleSelection:[...se,Z.value]}:{styleSelection:se.filter(fe=>fe!==Z.value)})},"data-testid":`checkbox-style-${Z.value.replace(/\s+/g,"-")}`}),Z.label]},Z.value))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ja,{className:"text-xs font-medium",children:"Pool"}),e.jsx(N$,{checked:t.hasPool===!0,onCheckedChange:Z=>a({hasPool:Z?!0:void 0}),"data-testid":"switch-pool"})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Basement"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["Full","Partial","None"].map(Z=>e.jsx("button",{onClick:()=>{const pe=t.basementCategories||[];if(pe.includes(Z)){const se=pe.filter(fe=>fe!==Z);a({basementCategories:se.length?se:void 0,hasBasement:void 0})}else a({basementCategories:[...pe,Z],hasBasement:void 0})},className:Q("px-2 py-0.5 text-xs rounded border",t.basementCategories?.includes(Z)?"bg-purple-600 text-white border-purple-600":"bg-white text-gray-700 border-gray-200 hover:border-purple-300"),"data-testid":`btn-basement-${Z}`,children:Z},Z))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Condition (C1-C6)"}),e.jsx("div",{className:"flex gap-0.5",children:["C1","C2","C3","C4","C5","C6"].map(Z=>e.jsx("button",{onClick:()=>{const pe=t.conditionRatings||[];pe.includes(Z)?a({conditionRatings:pe.filter(se=>se!==Z)||void 0}):a({conditionRatings:[...pe,Z]})},className:Q("flex-1 px-1 py-0.5 text-[11px] rounded border",t.conditionRatings?.includes(Z)?"bg-purple-600 text-white border-purple-600":"bg-white text-gray-700 border-gray-200 hover:border-purple-300"),"data-testid":`btn-condition-${Z}`,children:Z},Z))})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Quality (Q1-Q6)"}),e.jsx("div",{className:"flex gap-0.5",children:["Q1","Q2","Q3","Q4","Q5","Q6"].map(Z=>e.jsx("button",{onClick:()=>{const pe=t.qualityRatings||[];pe.includes(Z)?a({qualityRatings:pe.filter(se=>se!==Z)||void 0}):a({qualityRatings:[...pe,Z]})},className:Q("flex-1 px-1 py-0.5 text-[11px] rounded border",t.qualityRatings?.includes(Z)?"bg-purple-600 text-white border-purple-600":"bg-white text-gray-700 border-gray-200 hover:border-purple-300"),"data-testid":`btn-quality-${Z}`,children:Z},Z))})]})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Location Score (0-100)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ze,{type:"number",placeholder:"Min",min:0,max:100,value:t.minLocationScore??"",onChange:Z=>a({minLocationScore:Z.target.value?parseInt(Z.target.value):void 0}),className:"h-8 text-xs","data-testid":"input-location-min"}),e.jsx(ze,{type:"number",placeholder:"Max",min:0,max:100,value:t.maxLocationScore??"",onChange:Z=>a({maxLocationScore:Z.target.value?parseInt(Z.target.value):void 0}),className:"h-8 text-xs","data-testid":"input-location-max"})]})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"City"}),e.jsx(ze,{type:"text",placeholder:"e.g. Chicago",value:t.cityFilter??"",onChange:Z=>a({cityFilter:Z.target.value||void 0}),className:"h-8 text-xs","data-testid":"input-city-filter"})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Street Name"}),e.jsx(ze,{type:"text",placeholder:"e.g. Elm",value:t.streetNameFilter??"",onChange:Z=>a({streetNameFilter:Z.target.value||void 0}),className:"h-8 text-xs","data-testid":"input-street-name-filter"})]}),e.jsxs("div",{children:[e.jsx(Ja,{className:"text-xs font-medium mb-1.5 block",children:"Street Number Range"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ze,{type:"number",placeholder:"Min",value:t.minStreet
45Number??"",onChange:Z=>a({minStreetNumber:Z.target.value?parseInt(Z.target.value):void 0}),className:"h-8 text-xs","data-testid":"input-street-number-min"}),e.jsx(ze,{type:"number",placeholder:"Max",value:t.maxStreetNumber??"",onChange:Z=>a({maxStreetNumber:Z.target.value?parseInt(Z.target.value):void 0}),className:"h-8 text-xs","data-testid":"input-street-number-max"})]})]})]})}),p&&(()=>{const Z=["Single Family","Condo","Townhouse","Multi-Family"],pe=(t.propertyTypes||[]).filter(ue=>ue!=="STR"),se=pe.length>0,fe=se?pe.length===1?pe[0]:`${pe.length} types`:"Property Type";return e.jsxs(e.Fragment,{children:[e.jsx(_d,{icon:Jj,label:A?F:"Bed/Bath",hasValue:A,testId:"filter-chip-str-beds-baths",onClear:()=>a({minBeds:void 0,maxBeds:void 0,minBaths:void 0,maxBaths:void 0,bedsSelection:void 0,bathsSelection:void 0}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{"data-testid":"filter-chip-str-beds",children:[e.jsx(Ja,{className:"text-sm font-medium mb-2 block",children:"Bedrooms"}),e.jsx(VS,{label:"Bedrooms",minValue:t.minBeds,maxValue:t.maxBeds,presets:L1,onMinChange:ue=>a({minBeds:ue,bedsSelection:void 0}),onMaxChange:ue=>a({maxBeds:ue,bedsSelection:void 0}),testIdPrefix:"str-beds"})]}),e.jsxs("div",{className:"border-t border-gray-100 pt-3","data-testid":"filter-chip-str-baths",children:[e.jsx(Ja,{className:"text-sm font-medium mb-2 block",children:"Bathrooms"}),e.jsx(VS,{label:"Bathrooms",minValue:t.minBaths,maxValue:t.maxBaths,presets:D1,onMinChange:ue=>a({minBaths:ue,bathsSelection:void 0}),onMaxChange:ue=>a({maxBaths:ue,bathsSelection:void 0}),testIdPrefix:"str-baths",allowDecimals:!0})]})]})}),e.jsx(_d,{icon:Um,label:t.minSqft!==void 0||t.maxSqft!==void 0?B:"Sqft",hasValue:t.minSqft!==void 0||t.maxSqft!==void 0,testId:"filter-chip-str-sqft",onClear:()=>a({minSqft:void 0,maxSqft:void 0}),children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(a0,{label:"GLA (Sqft)",minValue:t.minSqft,maxValue:t.maxSqft,onMinChange:ue=>a({minSqft:ue}),onMaxChange:ue=>a({maxSqft:ue}),testIdPrefix:"str-sqft",formatDisplay:ue=>ue.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-slate-500",children:"Rentals with unknown sqft remain visible."})]})}),e.jsx(_d,{icon:Fo,label:fe,hasValue:se,testId:"filter-chip-str-property-type",onClear:()=>a({propertyTypes:["STR"],strOnly:!0}),children:e.jsxs("div",{className:"space-y-2 min-w-[200px]",children:[e.jsx(Ja,{className:"text-sm font-medium",children:"Property Type"}),e.jsx("div",{className:"space-y-1",children:Z.map(ue=>{const be=pe.includes(ue);return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer hover:bg-gray-50 px-1.5 py-1 rounded text-sm",children:[e.jsx(Pa,{checked:be,onCheckedChange:H=>{const ye=H?["STR",...pe,ue]:["STR",...pe.filter(de=>de!==ue)];a({propertyTypes:ye,strOnly:!0})},"data-testid":`checkbox-str-proptype-${ue.replace(/\s+/g,"-")}`}),e.jsx("span",{children:ue})]},ue)})}),se&&e.jsx("button",{type:"button",onClick:()=>a({propertyTypes:["STR"],strOnly:!0}),className:"w-full text-[11px] text-blue-600 hover:underline mt-1 pt-1 border-t","data-testid":"button-str-proptype-clear",children:"Clear selection"}),e.jsx("p",{className:"text-[10px] text-slate-500 pt-1 border-t",children:"Rentals with unknown property type remain visible."})]})}),e.jsx(_d,{icon:xv,label:oe,hasValue:ae,testId:"filter-chip-str-nightly-rate",onClear:()=>a({minPrice:void 0,maxPrice:void 0}),children:e.jsxs("div",{className:"space-y-3 min-w-[260px]",children:[e.jsx(Ja,{className:"text-sm font-medium",children:"Nightly Rate"}),e.jsx(a0,{label:"Nightly Rate",minValue:t.minPrice,maxValue:t.maxPrice,onMinChange:ue=>a({minPrice:ue}),onMaxChange:ue=>a({maxPrice:ue}),prefix:"$",testIdPrefix:"str-nightly-rate",formatDisplay:ue=>ue.toLocaleString()}),e.jsx(k1,{pool:(x??[]).map(ue=>ue.strAverageDailyRate??ue.strNightlyRate).filter(ue=>typeof ue=="number"&&ue>0),formatValue:ue=>`$${Math.round(ue).toLocaleString()}`,onSetMin:ue=>a({minPrice:Math.round(ue)}),onSetMax:ue=>a({maxPrice:Math.round(ue)}),emptyText:"Load rentals to see distribution.",testIdPrefix:"str-nightly-rate"}),e.jsx("p",{className:"text-[10px] text-slate-500",children:"Rentals with unknown rate remain visible."})]})}),e.jsx(_d,{icon:Lo,label:D,hasValue:_,testId:"filter-chip-str-occupancy",onClear:()=>a({minOccupancyPct:void 0,maxOccupancyPct:void 0}),children:e.jsxs("div",{className:"space-y-3 min-w-[260px]",children:[e.jsx(Ja,{className:"text-sm font-medium",children:"Occupancy (%)"}),e.jsx(a0,{label:"Occupancy",minValue:t.minOccupancyPct,maxValue:t.maxOccupancyPct,onMinChange:ue=>a({minOccupancyPct:ue}),onMaxChange:ue=>a({maxOccupancyPct:ue}),testIdPrefix:"str-occupancy",formatDisplay:ue=>`${ue}%`}),e.jsx(k1,{pool:(x??[]).map(ue=>ue.strOccupancyRate).filter(ue=>typeof ue=="number"&&ue>0).map(ue=>ue<=1?ue*100:ue),formatValue:ue=>`${Math.round(ue)}%`,onSetMin:ue=>a({minOccupancyPct:Math.round(ue)}),onSetMax:ue=>a({maxOccupancyPct:Math.round(ue)}
45),emptyText:"Load rentals to see distribution.",testIdPrefix:"str-occupancy"}),e.jsx("p",{className:"text-[10px] text-slate-500",children:"Rentals with unknown occupancy remain visible."})]})}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-purple-600 bg-purple-50 px-2.5 py-1.5 rounded-md border border-purple-200 shrink-0","data-testid":"str-mode-indicator",children:[e.jsx(s2,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"font-medium",children:"STR Mode"})]})]})})()]}),r&&e.jsx("button",{onClick:r,className:"text-[14px] font-medium text-[#6A7282] underline hover:text-[#4B5563] transition-colors shrink-0 pl-3","data-testid":"btn-clear-all-filters",children:"Reset"})]})}function Z9(t,a,s,r){let n=a;return a==="cards"||a==="cards-map"?t==="cards-map"?(r.current="cards",n="map"):t==="cards"||t==="cards-map"?n=t:n=s?"cards-map":"cards":a==="list"||a==="list-map"?t==="list-map"?(r.current="list",n="map"):t==="list"||t==="list-map"?n=t:n=s?"list-map":"list":a==="map"&&(t==="map"?n=r.current:s?n=t==="list-map"?"list":"cards":n=t==="list"?"list-map":"cards-map"),n}function J9(t,a){let s=0;return(t.minBeds||t.maxBeds)&&s++,(t.minBaths||t.maxBaths)&&s++,(t.minPrice||t.maxPrice)&&s++,(t.minSqft||t.maxSqft)&&s++,!a&&t.monthsBack&&t.monthsBack!==12&&s++,a&&(t.minOccupancyPct!==void 0||t.maxOccupancyPct!==void 0)&&s++,(t.propertyTypes||[]).filter(n=>n!=="STR").length>0&&s++,typeof t.remarksSearch=="string"&&t.remarksSearch.trim()&&s++,(Array.isArray(t.statusSelection)&&t.statusSelection.length>0||Array.isArray(t.status)&&t.status.length>0)&&s++,Array.isArray(t.styleSelection)&&t.styleSelection.length>0&&s++,Array.isArray(t.basementCategories)&&t.basementCategories.length>0&&s++,s}function X9(t){const{marketLocked:a,handleMarketButtonClick:s,propertiesInArea:r,subMarketLocked:n,handleSubmarketButtonClick:i,subMarketPropertiesCount:l,isLockingMarket:c,isLockingSubMarket:d,state:p,enableStr:u,showToolbarFilterPanel:m,setShowToolbarFilterPanel:h,labViewMode:f,setLabViewMode:v,showMapPanel:S,preFullscreenMapModeRef:N,handleSortChange:x,handleFilterBarChange:y,sortedProperties:b,handleClearAllFilters:j,comparisonDataSource:T,setComparisonDataSource:O,reviewingLock:E,radiusCircle:R,handleRadiusChange:G,userQuickPicks:U,verifiedSubject:C,expandingFilters:F,activeStatusCounts:A,toolbarExtraActions:M,strRentalPool:B,onOpenMatchSettings:oe}=t;return e.jsxs(e.Fragment,{children:[e.jsx(_9,{marketLocked:a,onToggleMarketLock:()=>s(),marketLockDisabled:!a&&r===0,isLockingMarket:c,subMarketLocked:n,onToggleSubMarketLock:()=>i(),subMarketLockDisabled:!n&&l===0,isLockingSubMarket:d,activeFilterCount:J9(p.filters,u),showFilterPanel:m,onToggleFilters:()=>h(ae=>!ae),labViewMode:f,onViewModeChange:ae=>{const D=f,_=Z9(D,ae,S,N);console.log("[ViewMode] StepPropertyLab toolbar toggle:",D,"->",_),_!==D&&v(_)},showMapPanel:S,sortBy:p.filters.sortBy,onSortChange:x,extraActions:M,onOpenMatchSettings:oe}),m&&e.jsx("div",{className:"shrink-0",children:e.jsx(Q9,{filters:p.filters,onFiltersChange:y,resultCount:b.length,onClearFilters:j,comparisonDataSource:T,onDataSourceChange:O,isReviewMode:!!E,currentRadius:R?.radiusMiles??1,onRadiusChange:G,enableStr:u,quickPicks:U??void 0,subjectGla:C?.gla,subjectPrice:C?.lastSalePrice&&C.lastSalePrice>0?C.lastSalePrice:C?.listPrice,subjectLotSizeSqft:C?.lotSizeAcres?Math.round(C.lotSizeAcres*43560):void 0,subjectYearBuilt:C?.yearBuilt,expandingFilters:F,activeStatusCounts:A,strRentalPool:B})})]})}const uC=[{key:"address",label:"Street Address",type:"text",group:"Address",requiredForComp:!0,synonyms:["address","streetaddress","propertyaddress","fulladdress","addr","situsaddress","location","addressline1"],composeParts:[{role:"streetNumber",required:!0,synonyms:["street#","streetnumber","streetno","stnum","housenumber","streetnum"]},{role:"direction",synonyms:["cp","compass","compasspoint","streetdir","dir","streetdirection","streetdirprefix"]},{role:"streetName",required:!0,synonyms:["strname","streetname","stname"]},{role:"suffix",synonyms:["sfx","suffix","streetsuffix","sttype","streettype","streetsfx"]}]},{key:"city",label:"City",type:"text",group:"Address",synonyms:["city","municipality","town","situscity"]},{key:"state",label:"State",type:"text",group:"Address",synonyms:["state","st","province","stateorprovince","situsstate"]},{key:"zip",label:"ZIP Code",type:"text",group:"Address",synonyms:["zip","zipcode","postalcode","postal","zip5","situszip"]},{key:"mlsNumber",label:"MLS Number",type:"text",group:"Address",synonyms:["mls","mlsnumber","mlsid","listingid","listingnumber","mlsnum","mln"]},{key:"latitude",label:"Latitude",type:"coord",group:"Address",synonyms:["lat","latitude","geolat","ycoordinate"]},{key:"longitude",label:"Longitude",type:"coord",group:"Address",synonyms:["lng","lon","long","longitude","geolng","geolon","xcoordinate"]},{key:"price",label:"Sale Price",type:"money",group:"Sale",requiredFor
45Comp:!0,synonyms:["price","saleprice","soldprice","closeprice","closingprice","sp","salesprice","soldpr","closedprice","lastsaleprice","contractprice"]},{key:"listPrice",label:"List Price",type:"money",group:"Sale",synonyms:["listprice","lp","originallistprice","askingprice","currentprice","listpr","origlistpr","origlistprice","olp","lpsp"]},{key:"status",label:"Status",type:"status",group:"Sale",synonyms:["status","mlsstatus","standardstatus","saletype","listingstatus","stat"]},{key:"saleDate",label:"Sale Date",type:"date",group:"Sale",synonyms:["saledate","solddate","closedate","closingdate","settlementdate","datesold","closeddate","coedate","saledt","clsddate","dateclosed"]},{key:"contractDate",label:"Contract Date",type:"date",group:"Sale",synonyms:["contractdate","undercontractdate","pendingdate","contractdt","datecontract"]},{key:"listDate",label:"List Date",type:"date",group:"Sale",synonyms:["listdate","listingdate","onmarketdate","datelisted","listdt"]},{key:"dom",label:"Days on Market",type:"int",group:"Sale",synonyms:["dom","daysonmarket","cdom","marketdays","daysmarket","adom"]},{key:"gla",label:"GLA (Living Area)",type:"sqft",group:"Physical",subjectFieldId:"gla",synonyms:["gla","grosslivingarea","livingarea","sqft","squarefeet","sqfeet","sf","abovegradesqft","finishedsqft","totalsqft","heatedsqft","livingsqft","buildingsqft","squarefootage","asf","agsf","abovegradefinishedarea","aprxsqft","approxsqft"]},{key:"beds",label:"Bedrooms",type:"beds",group:"Physical",subjectFieldId:"beds",synonyms:["beds","bedrooms","br","bed","beds total","bedstotal","totalbedrooms","numbeds","allbeds"]},{key:"baths",label:"Bathrooms",type:"baths",group:"Physical",subjectFieldId:"baths",synonyms:["baths","bathrooms","ba","bath","totalbaths","bathstotal","numbaths"]},{key:"fullBaths",label:"Full Bathrooms",type:"int",group:"Physical",synonyms:["fullbaths","fullbathrooms","fullbath","bathsfull","numfullbaths","fb"]},{key:"halfBaths",label:"Half Bathrooms",type:"int",group:"Physical",synonyms:["halfbaths","halfbathrooms","halfbath","bathshalf","numhalfbaths","hb"]},{key:"yearBuilt",label:"Year Built",type:"year",group:"Physical",subjectFieldId:"yearBuilt",synonyms:["yearbuilt","yrblt","yrbuilt","built","yearconstructed","constructionyear","yb"]},{key:"lotSize",label:"Lot Size (sqft)",type:"sqft",group:"Physical",subjectFieldId:"lotSize",synonyms:["lotsize","lotsqft","lotsizesqft","lotsizesquarefeet","lot","lotarea","landsqft","lotsizearea"]},{key:"lotSizeAcres",label:"Lot Size (acres)",type:"float",group:"Physical",synonyms:["acreage","acres","lotacres","lotsizeacres"]},{key:"lotDim",label:"Lot Dimensions",type:"text",group:"Physical",synonyms:["lotdim","lotdimensions","lotdimension","lotdims"]},{key:"garageSpaces",label:"Garage Spaces",type:"int",group:"Physical",subjectFieldId:"garage",synonyms:["garagespaces","garage","garagecars","garagecount","parkingspaces","garagecapacity"]},{key:"propertyType",label:"Property Type",type:"text",group:"Physical",synonyms:["propertytype","proptype","type","propertysubtype","style","structuretype"]},{key:"style",label:"Architectural Style",type:"text",group:"Physical",synonyms:["architecturalstyle","archstyle","homestyle","designstyle","stories"]},{key:"basement",label:"Basement",type:"enum",group:"Physical",subjectFieldId:"basementType",synonyms:["basement","basementtype","foundation","foundationtype","bsmt","basementdescription"],canonicalValues:["Full","Partial","Walkout","English","Crawl Space","Slab","None"],valueSynonyms:{Full:["full","fullbasement","fullfinished","fullunfinished","finishedfull","yesfull"],Partial:["partial","partialbasement","part","halfbasement"],Walkout:["walkout","walkoutbasement","walkout basement","walkoutfull","fullwalkout","exposedwalkout"],English:["english","englishbasement","lookout","daylight"],"Crawl Space":["crawl","crawlspace","crawlspaceonly"],Slab:["slab","slabongrade","noneslab"],None:["none","no","nobasement","n","na"]}},{key:"garageType",label:"Garage Type",type:"enum",group:"Physical",synonyms:["garagetype","garagedescription","garageownership","parkingtype","garageattached"],canonicalValues:["Attached","Detached","Carport","None"],valueSynonyms:{Attached:["attached","attachedgarage","garageattached","att","builtin"],Detached:["detached","detachedgarage","garagedetached","det"],Carport:["carport"],None:["none","no","nogarage","n","na"]}},{key:"taxes",label:"Annual Taxes",type:"money",group:"Other",synonyms:["taxes","taxamount","annualtaxes","taxannualamount","propertytaxes"]}],nN=uC.reduce((t,a)=>(t[a.key]=a,t),{});function pv(t){return String(t??"").toLowerCase().replace(/[^a-z0-9]/g,"")}const M1=new Date().getFullYear();function IM(t){return t==null||String(t).trim()===""}function Ix(t){const a=String(t).replace(/[$,\s]/g,"").replace(/[^0-9.\-]/g,"");if(a===""||a==="-"||a===".")return null;const s=Number(a);return Number.isFinite(s)?s:null}const F1=[{value:"CLSD",codes:["closed","sold","clsd","settled","complete","c","s"]},{value:"PEND",codes:["pending","pend","undercontract","contingent","ctg","p","uc"]},{value:"ACTV",codes:["active","actv","a","forsale","available","comingsoon","new"]}];function eQ(t){const a=pv(t);if(!a)return null;for(const s of F1)if(s.codes.some(r=>a===r))return s.value;for(const s of F1)if(s.codes.some(r=>r.length>=3&&a.includes(r)))return s.value;return null}function tQ(t){const a=String(t).trim();if(!a)return null;const s=a.match(/^(\d{1,2})[\/\-.](\d{1,2})[\/\-.](\d{2,4})$/);if(s){let[,i,l,c]=s,d=parseInt(c,10);c.length===2&&(d+=d<50?2e3:1900);const p=parseInt(i,10),u=parseInt(l,10);return p>=1&&p<=12&&u>=1&&u<=31?`${d.toString().padStart(4,"0")}-${String(p).padStart(2,"0")}-${String(u).padStart(2,"0")}`:null}const r=a.match(/^(\d{4})[\/\-.](\d{1,2})[\/\-.](\d{1,2})/);if(r){const[,i,l,c]=r,d=parseInt(l,10),p=parseInt(c,10);return d>=1&&d<=12&&p>=1&&p<=31?`${i}
45-${String(d).padStart(2,"0")}-${String(p).padStart(2,"0")}`:null}const n=new Date(a);return!isNaN(n.getTime())&&n.getFullYear()>1900&&n.getFullYear()<2100?`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`:null}function aQ(t,a,s){const r=pv(a);if(!r)return{value:null,viaAi:!1};const n=t.canonicalValues??[];for(const c of n)if(pv(c)===r)return{value:c,viaAi:!1};for(const[c,d]of Object.entries(t.valueSynonyms??{}))if(d.some(p=>pv(p)===r))return{value:c,viaAi:!1};let i=null;for(const[c,d]of Object.entries(t.valueSynonyms??{}))for(const p of d)p.length>=4&&r.includes(p)&&(!i||p.length>i.len)&&(i={c,len:p.length});if(i)return{value:i.c,viaAi:!1};const l=s?.[t.key]?.[r];return l&&n.includes(l)?{value:l,viaAi:!0}:{value:null,viaAi:!1}}function pC(t,a,s){if(t.type!=="enum")return sQ(t.type,a);if(IM(a))return{value:null,valid:!0};const r=String(a).trim(),{value:n,viaAi:i}=aQ(t,r,s);return n===null?{value:null,valid:!1,warning:`Unrecognized ${t.label.toLowerCase()} "${r}" — imported blank`}:i?{value:n,valid:!0,warning:`AI-standardized "${r}" → ${n}`}:{value:n,valid:!0}}function sQ(t,a){if(IM(a))return{value:null,valid:!0};const s=String(a).trim();switch(t){case"money":{const r=Ix(s);return r===null?{value:null,valid:!1,warning:`"${s}" is not a valid amount`}:r<=0?{value:r,valid:!1,warning:"Amount must be greater than 0"}:{value:r,valid:!0}}case"sqft":case"int":{const r=Ix(s);return r===null?{value:null,valid:!1,warning:`"${s}" is not a number`}:r<0?{value:r,valid:!1,warning:"Value cannot be negative"}:{value:Math.round(r),valid:!0}}case"float":case"beds":{const r=Ix(s);return r===null?{value:null,valid:!1,warning:`"${s}" is not a number`}:r<0?{value:r,valid:!1,warning:"Value cannot be negative"}:{value:r,valid:!0}}case"baths":{const r=s.match(/^(\d+)\s*[\/|]\s*(\d+)$/);if(r){const i=parseInt(r[1],10),l=parseInt(r[2],10);return{value:i+l*.5,valid:!0}}const n=Ix(s);return n===null?{value:null,valid:!1,warning:`"${s}" is not a valid bath count`}:n<0?{value:n,valid:!1,warning:"Value cannot be negative"}:{value:n,valid:!0}}case"year":{const r=Ix(s);return r===null?{value:null,valid:!1,warning:`"${s}" is not a year`}:r<1800||r>M1+1?{value:Math.round(r),valid:!1,warning:`Year ${Math.round(r)} is outside 1800–${M1+1}`}:{value:Math.round(r),valid:!0}}case"coord":{const r=Ix(s);return r===null?{value:null,valid:!1,warning:`"${s}" is not a coordinate`}:r<-180||r>180?{value:r,valid:!1,warning:"Coordinate out of range"}:{value:r,valid:!0}}case"status":{const r=eQ(s);return r?{value:r,valid:!0}:{value:null,valid:!1,warning:`Unrecognized status "${s}"`}}case"date":{const r=tQ(s);return r?{value:r,valid:!0}:{value:null,valid:!1,warning:`"${s}" is not a valid date`}}default:return{value:s,valid:!0}}}function rQ(t,a,s){const r={},n=[],i=[];for(const l of a){if(!l.header)continue;const c=nN[l.targetKey];if(!c)continue;const d=l.parts?l.parts.map(u=>String(t[u]??"").trim()).filter(Boolean).join(" "):t[l.header],p=pC(c,d,s);r[l.targetKey]=p.value,p.warning&&(!p.valid||p.warning.startsWith("AI-standardized"))&&n.push({targetKey:l.targetKey,warning:p.warning})}for(const l of uC)if(l.requiredForComp){const c=r[l.key];(c==null||c==="")&&i.push(l.key)}return{values:r,issues:n,missingRequired:i}}const nQ="CSV Import";function _1(t,a,s){return t.map((r,n)=>{const{values:i,issues:l,missingRequired:c}=rQ(r,a,s);return{index:n,values:i,issues:l,missingRequired:c,usable:c.length===0}})}function iQ(t,a){if(!(t===void 0&&a===void 0))return(t??0)+(a??0)*.5}function zl(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function od(t){if(t==null)return;const a=String(t).trim();return a===""?void 0:a}function oQ(t){const a=od(t);return a==="CLSD"||a==="ACTV"||a==="PEND"?a:"CLSD"}function lQ(t,a){const s=t.values,r=od(s.address)||"",n=od(s.city)||"",i=od(s.state)||"",l=od(s.zip)||"",c=[r,[n,i].filter(Boolean).join(", "),l].filter(Boolean).join(", "),d=zl(s.latitude),p=zl(s.longitude);return{id:`${a}-${t.index}`,address:r,city:n,state:i,zip:l,fullAddress:c,coordinates:{lat:d??0,lng:p??0},distance:0,status:oQ(s.status),saleDate:od(s.saleDate),contractDate:od(s.contractDate),listDate:od(s.listDate),price:zl(s.price)??0,listPrice:zl(s.listPrice),gla:zl(s.gla)??0,beds:zl(s.beds)??0,baths:zl(s.baths)??iQ(zl(s.fullBaths),zl(s.halfBaths))??0,fullBathrooms:zl(s.fullBaths)??null,halfBathrooms:zl(s.halfBaths)??null,yearBuilt:zl(s.yearBuilt)??0,lotSize:zl(s.lotSize)??(zl(s.lotSizeAcres)!==void 0?Math.round(zl(s.lotSizeAcres)*43560):void 0),dom:zl(s.dom),propertyType:od(s.propertyType),style:od(s.style),basement:od(s.basement),garageType:od(s.garageType)??null,garageSpaces:zl(s.garageSpaces),mlsNumber:od(s.mlsNumber),selectionState:"none",reportSection:nQ}}function cQ(t,a){const s={};for(const[r,n]of Object.entries(a)){const i=od(t.values[r]);i!==void 0&&(s[n]=i)}return s}const lI=[{label:"General Information",rows:[{key:"mlsNumber",label:"Data Source · MLS #"},{key:"status",label:"Status"},{key:"price",label:"Sale Price"},{key:"listPrice",label:"List Price"},{key:"saleDate",label:"Date of Sale / Contract"},{key:"contractDate",label:"Contract Date"},{key:"listDate",label:"List Date"},{key:"dom",label:"Days on Market"}]},{label:"Site",rows:[{key:"lotSize",label:"Site (sqft)"},{key:"lotSizeAcres",label:"Site (acres)"},{key:"lotDim",label:"Lot Dimensions"}]},{label:"Dwelling(s)",rows:[{key:"yearBuilt",label:"Year Built"},{key:"propertyType",label:"Property Type"},{key:"style",label:"Design (Style)"}]},{label:"Unit(s)",rows:[{key:"beds",label:"Bedrooms"},{key:"baths",label:"Bathrooms"},{key:"gla",label:"Finished Area Above Grade (GLA)"},{key:"basement",label:"Basement"}]},{label:"Vehicle Storage",rows:[{key:"garageType",label:"Garage Type"},{key:"garageSpaces",label:"Garage Spaces"}]}],U1=lI.flatMap(t=>t.rows.map(a=>a.key));function Oh(t){return t==null?"":String(t).trim()}function Cx(t){return Oh(t)===""}async function dQ(t,a,s){const r=new Image;await new Promise((c,d)=>{r.onload=()=>c(),r.onerror=()=>d(new Error("Image decode failed")),r.src=t});const n=Math.min(1,a/Math.max(r.width,r.height));if(n>=1&&t.length<12e4)return t;const i=document.createElement("canvas");i.width=Math.max(1,Math.round(r.width*n)),i.height=Math.max(1,Math.round(r.height*n));const l=i.getContext("2d");return l?(l.drawImage(r,0,0,i.width,i.height),i.toDataURL("image/jpeg",s)):t}const s0=25,uQ={CLSD:"bg-green-100 text-green-800 border-green-300",PEND:"bg-amber-100 text-amber-800 border-amber-300",ACTV:"bg-sky-100 text-sky-800 border-sky-300"};function V1({value:t}){const a=uQ[t];return a?e.jsx("span",{className:`inline-block rounded border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${a}`,children:t}):e.jsx("span",{className:"text-muted-foreground",children:t||"—"})}function pQ({conversions:t,valueMappings:a,mappedKeys:s,subject:r,onBack:n,onConfirm:i,confirming:l}
45){const[c,d]=o.useState({}),[p,u]=o.useState(new Set),[m,h]=o.useState({}),[f,v]=o.useState(null),[S,N]=o.useState(!1),[x,y]=o.useState(0),[b,j]=o.useState(null),T=o.useRef(null),O=o.useRef(null),E=o.useMemo(()=>t.map(z=>{const V={...z.values},le={};for(const W of z.issues)le[W.targetKey]=W.warning;for(const W of U1){const me=`${z.index}:${W}`;if(c[me]===void 0)continue;const Z=c[me];if(Z.trim()===""){V[W]=null,delete le[W];continue}const pe=nN[W],se=pe?pC(pe,Z,a):{value:Z,valid:!0};se.value!==null&&se.valid?(V[W]=se.value,delete le[W]):(V[W]=null,le[W]="warning"in se&&se.warning||"Value not recognized — imports blank")}return{conv:z,values:V,flags:le}}),[t,c,a]),R=E.filter(z=>!p.has(z.conv.index)),G=Math.max(1,Math.ceil(E.length/s0)),U=Math.min(x,G-1),C=E.slice(U*s0,(U+1)*s0),F=R.reduce((z,V)=>z+Object.keys(V.flags).length,0),A=R.reduce((z,V)=>z+U1.filter(le=>s.has(le)&&Cx(V.values[le])&&!V.flags[le]).length,0),M=z=>R.some(V=>V.flags[z]||s.has(z)&&Cx(V.values[z])),B=o.useMemo(()=>S?lI.map(z=>({...z,rows:z.rows.filter(V=>M(V.key))})).filter(z=>z.rows.length>0):lI,[S,E,p]),oe=(z,V,le)=>{d(W=>({...W,[`${z}:${V}`]:le})),v(null)},ae=async z=>{const V=O.current;if(V!==null){j(V);try{const{preprocessImage:le}=await ri(async()=>{const{preprocessImage:Z}=await import("./uad36ImagePreprocess-5jaGBucA.js");return{preprocessImage:Z}},[]),W=await le(z),me=await dQ(W.dataUrl,640,.72);h(Z=>({...Z,[V]:me}))}catch(le){console.error("[CsvGridReview] photo preprocess failed:",le)}finally{j(null),O.current=null}}},D=()=>{const z=E.map(({conv:le,values:W,flags:me})=>({...le,values:W,issues:Object.entries(me).map(([Z,pe])=>({targetKey:Z,warning:pe})),usable:!Cx(W.address)&&!Cx(W.price)})),V=new Set(t.map(le=>le.index).filter(le=>!p.has(le)));i({conversions:z,includedIndexes:V,photosByIndex:m})},_=R.length,$=R.filter(z=>!Cx(z.values.address)&&!Cx(z.values.price)).length;return e.jsxs("div",{className:"flex flex-col gap-2 flex-1 min-h-0","data-testid":"csv-grid-review",children:[e.jsx("input",{ref:T,type:"file",accept:"image/*",className:"hidden","data-testid":"input-comp-photo",onChange:z=>{const V=z.target.files?.[0];V&&ae(V),z.target.value=""}}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Same rows and bands as your Sales Comparison Grid — click any cell to edit before importing."}),G>1&&e.jsxs("div",{className:"flex items-center gap-2 text-xs","data-testid":"grid-review-pager",children:[e.jsx(De,{variant:"outline",size:"sm",className:"h-7 px-2",disabled:U===0,onClick:()=>y(U-1),"data-testid":"button-page-prev",children:"‹ Prev"}),e.jsxs("span",{className:"text-muted-foreground",children:["Comps ",U*s0+1,"–",Math.min((U+1)*s0,E.length)," of ",E.length]}),e.jsx(De,{variant:"outline",size:"sm",className:"h-7 px-2",disabled:U>=G-1,onClick:()=>y(U+1),"data-testid":"button-page-next",children:"Next ›"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-lg border bg-muted/40 p-0.5 text-xs",children:[e.jsx("button",{type:"button",onClick:()=>N(!1),className:`rounded-md px-3 py-1 font-medium ${S?"text-muted-foreground hover:text-foreground":"bg-white dark:bg-background shadow-sm"}`,"data-testid":"button-filter-all",children:"All fields"}),e.jsxs("button",{type:"button",onClick:()=>N(!0),className:`flex items-center gap-1.5 rounded-md px-3 py-1 font-medium ${S?"bg-white dark:bg-background text-amber-700 shadow-sm":"text-muted-foreground hover:text-foreground"}`,"data-testid":"button-filter-missing",children:[e.jsx(pf,{className:"h-3 w-3"}),"Missing & flagged only",e.jsx("span",{className:"rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold text-amber-800",children:F+A})]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto rounded-md border",children:e.jsxs("table",{className:"border-collapse text-[12.5px] w-max min-w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-800 text-white",children:[e.jsx("th",{className:"sticky left-0 top-0 z-30 w-52 min-w-52 border-r border-slate-600 bg-slate-800 px-3 py-2 text-left align-bottom text-[11px] font-semibold uppercase tracking-wide",children:"Feature"}),r&&e.jsxs("th",{className:"sticky top-0 z-20 w-44 min-w-44 border-r border-slate-600 bg-slate-700 px-3 py-2 text-left align-bottom",children:[e.jsx("div",{className:"mb-1.5 flex h-14 w-full items-center justify-center rounded bg-slate-600/60",children:e.jsx(xg,{className:"h-4 w-4 text-slate-400"})}),e.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-slate-300",children:"Subject"}),e.jsx("div",{className:"truncate text-xs font-medium",children:r.address||"—"}),r.cityLine&&e.jsx("div",{className:"truncate text-[11px] font-normal text-slate-400",children:r.cityLine})]}),C.map(({conv:z,values:V},le)=>{const W=p.has(z.index),me=m[z.index];return e.jsxs("th",{className:`sticky top-0 z-20 w-44 min-w-44 border-r border-slate-600 bg-slate-800 px-3 py-2 text-left align-bottom ${W?"opacity-45":""}`,"data-testid":`header-import-${z.index}`,children:[me?e.jsx("button",{type:"button",className:"mb-1.5 block h-14 w-full overflow-hidden rounded bg-cover bg-center",style:{backgroundImage:`url(${me})`},title:"Replace photo",onClick:()=>{O.current=z.index,T.current?.click()},"data-testid":`button-photo-${z.index}`}):e.jsx("button",{type:"button",onClick:()=>{O.current=z.index,T.current?.click()},disabled:b===z.index,className:"mb-1.5 flex h-14 w-full flex-col items-center justify-center gap-0.5 rounded border-2 border-dashed border-slate-500 text-slate-400 hover:border-slate-300 hover:text-slate-200","data-testid":`button-photo-${z.index}`,children:b===z.index?e.jsx(za,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(r2,{className:"h-4 w-4"}),e.jsx("span",{className:"text-[9px] font-medium",children:"Add photo"})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-1",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-indigo-300",children:["Import ",le+1," ",e.jsx(V1,{value:Oh(V.status)})]}),e.jsxs("label",{className:"flex cursor-pointer items-center gap-1 text-[10px] font-normal text-slate-300",children:[e.jsx("input",{type:"checkbox",checked:!W,onChange:()=>u(Z=>{const pe=new Set(Z);return pe.has(z.index)?pe.delete(z.index):pe.add(z.index),pe}),className:"h-3 w-3","data-testid":`checkbox-include-${z.index}`}),"include"]})]}),e.jsx("div",{className:"truncate text-xs font-medium",title:Oh(V.address),children:Oh(V.address)||"—"}),e.jsx("div",{className:"truncate text-[11px] font-normal text-slate-400",children:[Oh(V.city),Oh(V.state)].filter(
45Boolean).join(", ")})]},z.index)})]})}),e.jsxs("tbody",{children:[B.map(z=>e.jsxs(o.Fragment,{children:[e.jsx("tr",{children:e.jsx("td",{colSpan:C.length+(r?2:1),className:"border-y bg-muted/70 px-3 py-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground",children:z.label})}),z.rows.map(V=>{const le=nN[V.key],W=V.label||le?.label||V.key;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsxs("td",{className:"sticky left-0 z-10 border-r bg-muted/40 px-3 py-1.5 font-medium backdrop-blur",children:[W,!s.has(V.key)&&e.jsx("span",{className:"ml-1.5 text-[9px] font-normal uppercase text-muted-foreground",children:"unmapped"})]}),r&&e.jsx("td",{className:"border-r bg-muted/20 px-3 py-1.5 text-muted-foreground",children:Oh(r.values[V.key])||"—"}),C.map(({conv:me,values:Z,flags:pe})=>{const se=p.has(me.index),fe=`${me.index}:${V.key}`,ue=Oh(Z[V.key]),be=pe[V.key],H=s.has(V.key)&&ue===""&&!be,ye=f===fe,de=le?.type==="enum"?le.canonicalValues:le?.type==="status"?["CLSD","PEND","ACTV"]:void 0;return e.jsxs("td",{className:`group relative cursor-text border-r px-3 py-1.5 ${se?"text-muted-foreground/50 opacity-60":""} ${be||H?"bg-amber-50 dark:bg-amber-950/30":""}`,onClick:()=>!se&&!ye&&v(fe),"data-testid":`cell-${me.index}-${V.key}`,children:[ye?de?e.jsxs("select",{autoFocus:!0,defaultValue:ue,className:"w-full rounded border border-primary bg-white dark:bg-background px-1 py-0.5 text-[12.5px] outline-none",onChange:ge=>oe(me.index,V.key,ge.target.value),onBlur:()=>v(null),"data-testid":`edit-${me.index}-${V.key}`,children:[e.jsx("option",{value:"",children:"—"}),de.map(ge=>e.jsx("option",{value:ge,children:ge},ge))]}):e.jsx("input",{autoFocus:!0,defaultValue:ue,className:"w-full rounded border border-primary bg-white dark:bg-background px-1.5 py-0.5 text-[12.5px] outline-none",onBlur:ge=>oe(me.index,V.key,ge.target.value),onKeyDown:ge=>{ge.key==="Enter"&&ge.target.blur(),ge.key==="Escape"&&v(null)},"data-testid":`edit-${me.index}-${V.key}`}):e.jsxs("span",{className:"flex items-center gap-1",children:[be&&e.jsx(Ns,{className:"h-3.5 w-3.5 shrink-0 text-amber-500"}),e.jsx("span",{className:be?"italic text-amber-700":H&&!se?"italic text-amber-600":"",children:V.key==="status"&&ue?e.jsx(V1,{value:ue}):ue||(H?"Fill in…":"—")}),!se&&e.jsx(Ru,{className:"ml-auto h-3 w-3 shrink-0 text-muted-foreground/40 opacity-0 group-hover:opacity-100"})]}),be&&!ye&&e.jsx("div",{className:"pointer-events-none absolute left-2 top-full z-40 mt-0.5 hidden w-56 rounded-md border border-amber-300 bg-popover p-2 text-[11px] leading-snug text-amber-800 shadow-lg group-hover:block",children:be})]},me.index)})]},V.key)})]},z.label)),S&&B.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:C.length+(r?2:1),className:"px-4 py-8 text-center text-sm text-green-700",children:"Nothing missing — every mapped field is filled in."})})]})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[e.jsxs("div",{className:"text-sm text-muted-foreground","data-testid":"text-grid-review-summary",children:[e.jsxs("span",{className:"font-semibold text-foreground",children:[$," of ",t.length]})," comparables will import",_!==$&&e.jsxs("span",{children:[" (",_-$," skipped — missing address or price)"]}),F+A>0&&e.jsxs("span",{className:"text-amber-700",children:[" · ",F+A," value",F+A===1?"":"s"," still need attention"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{variant:"outline",onClick:n,"data-testid":"button-back-to-mapping",children:"Back to mapping"}),e.jsxs(De,{onClick:D,disabled:l||$===0,"data-testid":"button-confirm-grid-import",children:[l?e.jsx(za,{className:"h-4 w-4 animate-spin mr-2"}):null,"Add ",$," Comp",$===1?"":"s"," to Pool"]})]})]})]})}const mQ={high:{label:"High",className:"bg-green-100 text-green-800 border-green-200"},medium:{label:"Medium",className:"bg-amber-100 text-amber-800 border-amber-200"},low:{label:"AI · Low",className:"bg-orange-100 text-orange-800 border-orange-200"},none:{label:"Unmapped",className:"bg-slate-100 text-slate-500 border-slate-200"}},hQ={comps:"Comps (Property Lab pool)",market:"Market (stats pool)",subject:"Subject (never auto-overwrites)"},Vx="__unmapped__";function fQ({open:t,onOpenChange:a,onConfirm:s,loadSavedMapping:r,availableTargets:n=["comps","market","subject"],subjectColumn:i}
45){const l=o.useRef(null),[c,d]=o.useState(!1),[p,u]=o.useState(null),[m,h]=o.useState(null),[f,v]=o.useState(""),[S,N]=o.useState(!1),[x,y]=o.useState("map"),[b,j]=o.useState(null),[T,O]=o.useState({}),[E,R]=o.useState(new Set(["comps","market"].filter(W=>n.includes(W)))),G=o.useCallback(()=>{h(null),u(null),v(""),O({}),d(!1),N(!1),y("map"),j(null)},[]),U=o.useCallback(W=>{W||G(),a(W)},[a,G]),C=o.useCallback(async W=>{d(!0),u(null),h(null),v(W.name);try{const me=new FormData;me.append("file",W);const Z=await fetch("/api/csv-import/parse",{method:"POST",body:me}),pe=await Z.json();if(!Z.ok){u(pe?.error||"Failed to parse the CSV file."),d(!1);return}const se=pe,fe=r?.(se.fingerprint),ue={};for(const be of se.mappings)ue[be.targetKey]=be.header??Vx;if(fe)for(const[be,H]of Object.entries(fe))se.headers.includes(H)&&(ue[be]=H);O(ue),h(se)}catch(me){u(me.message||"Upload failed.")}finally{d(!1)}},[r]),F=o.useMemo(()=>m?m.mappings.map(W=>{const me=T[W.targetKey];return!me||me===Vx?{...W,header:null,parts:void 0,confidence:"none"}:me===W.header?{...W,header:me}:{...W,header:me,parts:void 0,confidence:"high",source:"manual"}}):[],[m,T]),A=o.useMemo(()=>{const W={};for(const me of F)me.header&&(W[me.header]=me.targetKey);return W},[F]),M=o.useMemo(()=>m?_1(m.sampleRows,F,m.valueMappings):[],[m,F]),B=o.useMemo(()=>M.reduce((W,me)=>W+me.issues.length,0),[M]),oe=o.useMemo(()=>M.filter(W=>W.usable).length,[M]),ae=o.useMemo(()=>{const W=F.find(Z=>Z.targetKey==="address")?.header,me=F.find(Z=>Z.targetKey==="price")?.header;return!!(W&&me)},[F]),D=o.useCallback((W,me)=>{O(Z=>{const pe={...Z};if(me!==Vx)for(const se of Object.keys(pe))se!==W&&pe[se]===me&&(pe[se]=Vx);return pe[W]=me,pe})},[]),_=o.useCallback(W=>{R(me=>{const Z=new Set(me);return Z.has(W)?Z.delete(W):Z.add(W),Z})},[]),$=o.useCallback(()=>{if(!m)return;const W=m.rows?.length?m.rows:m.sampleRows;j(_1(W,F,m.valueMappings)),y("grid")},[m,F]),z=o.useCallback(async W=>{if(m){N(!0);try{const me=W.conversions.filter(H=>W.includedIndexes.has(H.index)),Z=`csv-${m.fingerprint}-${Date.now()}`,pe=me.filter(H=>H.usable).map(H=>{const ye=lQ(H,Z),de=W.photosByIndex[H.index];return de?{...ye,photoUrl:de,photos:[de]}:ye}),se={};for(const H of F){if(!H.header)continue;const ye=nN[H.targetKey];ye?.subjectFieldId&&(se[H.targetKey]=ye.subjectFieldId)}const fe=me.find(H=>H.usable)||me[0],ue=fe?cQ(fe,se):{},be={};for(const H of F)H.header&&(be[H.targetKey]=H.header);await s({targets:Array.from(E),comps:pe,subjectValues:ue,fingerprint:m.fingerprint,confirmedMapping:be,rowCount:m.rowCount,usableCount:pe.length}),U(!1)}finally{N(!1)}}},[m,F,E,s,U]),V=o.useMemo(()=>{var me;const W={};for(const Z of uC)(W[me=Z.group]||(W[me]=[])).push(Z);return Object.entries(W)},[]),le=m&&ae&&E.size>0&&!S;return e.jsx(xi,{open:t,onOpenChange:U,children:e.jsxs(bi,{className:`${x==="grid"?"max-w-[96vw] h-[92vh]":"max-w-5xl"} max-h-[92vh] flex flex-col bg-white dark:bg-card`,"data-testid":"dialog-csv-import",children:[e.jsxs($i,{children:[e.jsx(si,{children:"Import MLS / CSV Data"}),e.jsx(pl,{children:"Upload an MLS CSV export. Review the auto-suggested column mapping, then confirm to import. Nothing is saved until you confirm."})]}),!m&&e.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-12 border-2 border-dashed rounded-lg",children:[e.jsx(eT,{className:"h-10 w-10 text-muted-foreground"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:c?"Parsing…":'Choose a .csv or .tsv MLS export to begin ("export all fields" works best)'}),e.jsx("input",{ref:l,type:"file",accept:".csv,.tsv,.txt,text/csv,text/tab-separated-values,text/plain",className:"hidden","data-testid":"input-csv-file",onChange:W=>{const me=W.target.files?.[0];me&&C(me),W.target.value=""}}),e.jsxs(De,{onClick:()=>l.current?.click(),disabled:c,"data-testid":"button-choose-csv",children:[c?e.jsx(za,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(eT,{className:"h-4 w-4 mr-2"}),"Choose CSV"]}),p&&e.jsxs(WE,{variant:"destructive",className:"max-w-md","data-testid":"alert-csv-error",children:[e.jsx(Ns,{className:"h-4 w-4"}),e.jsx(KE,{children:p})]})]}),m&&x==="grid"&&b&&e.jsx(pQ,{conversions:b,valueMappings:m.valueMappings,mappedKeys:new Set(F.filter(W=>W.header).map(W=>W.targetKey)),subject:i,onBack:()=>y("map"),onConfirm:z,confirming:S}),m&&x==="map"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm flex-wrap",children:[e.jsx("span",{className:"font-medium","data-testid":"text-csv-filename",children:f}),e.jsxs(kt,{variant:"outline","data-testid":"badge-row-count",children:[m.rowCount," rows"]}),m.aiAssisted&&e.jsxs(kt,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:[e.jsx(ul,{className:"h-3 w-3 mr-1"})," AI-assisted mapping"]}),B>0?e.jsxs(kt,{variant:"outline",className:"bg-amber-50 text-amber-700 border-amber-200","data-testid":"badge-validation-issues",children:[e.jsx(Ns,{className:"h-3 w-3 mr-1"})," ",B," value warning(s) in sample"]}):e.jsxs(kt,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:[e.jsx(kr,{className:"h-3 w-3 mr-1"})," Sample values valid"]})]}),e.jsx(Qd,{className:"flex-1 border rounded-md",children:e.jsxs(Gd,{children:[e.jsx(Hd,{className:"sticky top-0 bg-white dark:bg-card z-10",children:e.jsxs(gi,{children:[e.jsx(Ds,{className:"w-[220px]",children:"Field"}),e.jsx(Ds,{className:"w-[240px]",children:"CSV Column"}),e.jsx(Ds,{className:"w-[110px]",children:"Confidence"}),e.jsx(Ds,{children:"Sample values"})]})}),e.jsx(Wd,{children:V.map(([W,me])=>e.jsx(gQ,{group:W,fields:me,mappings:F,headers:m.headers,sampleValues:m.sampleValues,claimedHeaders:A,valueMappings:m.valueMappings,onChange:D},W))})]})}),m.unresolvedHeaders.length>0&&e.jsxs("details",{className:"text-xs text-muted-foreground","data-testid":"details-unmapped-columns",children:[e.jsxs("summary",{className:"cursor-pointer select-none",children:[m.unresolvedHeaders.length," column(s) not imported (harmlessly ignored) — click to view"]}),e.jsx("div",{className:"mt-1 max-h-24 overflow-y-auto break-words",children:m.unresolvedHeaders.join(", ")})]}
45),!ae&&e.jsxs(WE,{variant:"destructive","data-testid":"alert-required-missing",children:[e.jsx(Ns,{className:"h-4 w-4"}),e.jsx(KE,{children:"Street Address and Sale Price must be mapped to import comps."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"text-sm font-medium",children:"Import into:"}),e.jsx("div",{className:"flex gap-4 flex-wrap",children:n.map(W=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer","data-testid":`checkbox-target-${W}`,children:[e.jsx(Pa,{checked:E.has(W),onCheckedChange:()=>_(W)}),hQ[W]]},W))}),e.jsxs("div",{className:"text-xs text-muted-foreground","data-testid":"text-usable-count",children:[oe," of ",M.length," sample rows are usable as comps (rows missing a valid address or price are skipped). Imported rows land in the Property Lab candidate pool — you choose which become grid comparables."]})]})]}),x==="map"&&e.jsxs(eb,{children:[e.jsx(De,{variant:"outline",onClick:()=>U(!1),"data-testid":"button-cancel-csv",children:"Cancel"}),m&&e.jsx(De,{onClick:$,disabled:!le,"data-testid":"button-confirm-csv",children:"Continue — review comps in grid"})]})]})})}function gQ({group:t,fields:a,mappings:s,headers:r,sampleValues:n,claimedHeaders:i,valueMappings:l,onChange:c}){return e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"bg-muted/50",children:e.jsx(ws,{colSpan:4,className:"font-semibold text-xs uppercase tracking-wide text-muted-foreground py-1",children:t})}),a.map(d=>{const p=s.find(N=>N.targetKey===d.key),u=p?.header??null,m=p?.parts,h=mQ[p?.confidence??"none"],v=(m?[0,1,2].map(N=>m.map(x=>(n[x]||[])[N]).filter(Boolean).join(" ")).filter(Boolean):u?n[u]||[]:[]).map(N=>{const x=pC(d,N,l),y=x.value!==null&&String(x.value)!==N?`${N} → ${x.value}`:N;return{raw:N,display:y,valid:x.valid}}),S=v.some(N=>!N.valid);return e.jsxs(gi,{"data-testid":`row-field-${d.key}`,children:[e.jsxs(ws,{className:"align-top",children:[e.jsxs("div",{className:"font-medium text-sm",children:[d.label,d.requiredForComp&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.type})]}),e.jsx(ws,{className:"align-top",children:e.jsxs(sr,{value:u??Vx,onValueChange:N=>c(d.key,N),children:[e.jsx(rr,{className:"h-8 text-sm","data-testid":`select-mapping-${d.key}`,children:e.jsx(or,{placeholder:"Unmapped"})}),e.jsxs(nr,{children:[e.jsx(vs,{value:Vx,children:"— Unmapped —"}),m&&u&&e.jsxs(vs,{value:u,children:[u," (composed)"]}),r.map(N=>{const x=i[N],y=!!(x&&x!==d.key);return e.jsxs(vs,{value:N,disabled:y,children:[N,y?" (in use)":""]},N)})]})]})}),e.jsx(ws,{className:"align-top",children:e.jsx(kt,{variant:"outline",className:h.className,"data-testid":`badge-confidence-${d.key}`,children:h.label})}),e.jsx(ws,{className:"align-top",children:u?e.jsxs("div",{className:"text-xs space-y-0.5",children:[v.length?v.map((N,x)=>e.jsx("div",{className:`truncate max-w-[280px] ${N.valid?"":"text-amber-700"}`,children:N.display},x)):e.jsx("span",{className:"text-muted-foreground italic",children:"no sample values"}),S&&e.jsxs("div",{className:"text-amber-600 flex items-center gap-1",children:[e.jsx(Ns,{className:"h-3 w-3"})," unrecognized values import blank (never raw)"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})})]},d.key)})]})}const $1="csv_import_mappings",B1=["/api/v2/user-ui-preferences"];function xQ(){const t=ku(),{data:a}=Vr({queryKey:B1,staleTime:6e4}),s=a?.preferences?.[$1]??{},r=l=>s[l]?.mappings,n=Yd({mutationFn:async({fingerprint:l,mappings:c})=>{const d={...s,[l]:{fingerprint:l,mappings:c,savedAt:new Date().toISOString()}};return Qo("PUT","/api/v2/user-ui-preferences",{key:$1,value:d})},onSuccess:()=>{t.invalidateQueries({queryKey:B1})}});return{loadSavedMapping:r,saveMapping:(l,c)=>{!l||Object.keys(c).length===0||n.mutate({fingerprint:l,mappings:c})}}}const bQ=({assignmentId:t,marketContext:a,marketLocked:s,subMarketLocked:r,lockedMarketCount:n,lockedSubMarketCount:i,lockedMarketResultIds:l,lockedSubmarketResultIds:c,lockedMarketSalesData:d,lockedSubmarketSalesData:p,subjectState:u,subjectZipCode:m,selectedComps:h})=>e.jsx(NM,{marketContext:a,assignmentId:t,marketResultsCount:s?n??0:0,submarketResultsCount:r?i??0:0,marketResultIds:s?l??[]:[],submarketResultIds:r?c??[]:[],marketS
45alesData:s?d:[],submarketSalesData:r?p:[],subjectState:u,subjectZipCode:m,parentMarketLocked:s,parentSubMarketLocked:r,selectedCompsForWizard:h.map(f=>({id:f.snapshotId||f.id,address:f.address,saleDate:f.saleDate||null}))});function yQ(t){if(t.length===0)return 0;const a=[...t].sort((r,n)=>r-n),s=Math.floor(a.length/2);return a.length%2!==0?a[s]:(a[s-1]+a[s])/2}function SQ(t,a,s=new Date,r=12){const n=z1(t,s,r),i=z1(a,s,r);return{marketData:n,subMarketData:i,marketAvgRate:q1(n),subMarketAvgRate:q1(i)}}function z1(t,a=new Date,s=12){const r=t.filter(u=>["CLSD","Sold"].includes(u.status)&&u.price>0&&(u.contractDate||u.saleDate));if(r.length<3)return[];const n={},i=n2(a);for(let u=s-1;u>=0;u--){const m=KO(i,u),h=Vi(m,"yyyy-MM");n[h]=[]}r.forEach(u=>{const m=u.contractDate||u.saleDate;if(!m)return;const h=new Date(m),f=Vi(h,"yyyy-MM");n[f]!==void 0&&n[f].push(u.price)});const l=Object.keys(n).sort();if(l.length===0)return[];const c=[];if(l.forEach(u=>{const m=n[u];m.length>0&&c.push({month:u,median:yQ(m),count:m.length})}),c.length<2)return[];const d=c[c.length-1]?.median;return!d||d<=0?[]:c.map(({month:u,median:m,count:h})=>{const f=(d-m)/m*100,[v,S]=u.split("-"),N=new Date(parseInt(v),parseInt(S)-1,1),x=Vi(N,"MMM yy");return{month:u,monthLabel:x,adjustmentPercent:parseFloat(f.toFixed(2)),saleCount:h,medianPrice:m}})}function q1(t){if(t.length<2)return 0;const a=t[0],s=t[t.length-1];if(!a||!s||a.medianPrice<=0||s.medianPrice<=0)return 0;const r=new Date(a.month+"-01"),n=new Date(s.month+"-01"),i=pb(n,r);if(i<=0)return 0;const l=s.medianPrice/a.medianPrice,c=(Math.pow(l,1/i)-1)*100;return parseFloat(c.toFixed(3))}function vQ(t,a,s=new Date){const r=t.contractDate||t.saleDate;if(!r||a===0)return t;const n=new Date(r),i=pb(s,n);if(i<=0)return t;const l=1+a/100*i,c=Math.round(t.price*l);return{...t,timeAdjustedPrice:c,timeAdjustmentPercent:parseFloat((a*i).toFixed(2))}}function Y1(t,a,s=new Date){return t.map(r=>vQ(r,a,s))}function NQ(t){return!t.some(a=>!!a.polygon)}function kj(t,a,s={}){return a==="Geocoding subject address"||a==="Locate search area"?{title:"We couldn't locate that address",description:"We weren't able to look up the subject property's location. Draw a radius or boundary on the map and use Retry."}:s.timedOut?{title:"Search took longer than expected",description:"The comparable sales search didn't finish in time. Your work is saved — use Retry to try again."}:t instanceof qo&&(t.status===502||t.status===503)||t instanceof TypeError&&typeof t.message=="string"&&(t.message.includes("Failed to fetch")||t.message.includes("NetworkError")||t.message.includes("Load failed"))?{title:"We couldn't load comparable sales right now",description:"This usually clears up in a moment. Your work is saved — use Retry to try again."}:{title:"We couldn't complete the search",description:"Something unexpected happened while loading comparable sales. Your work is saved — use Retry to try again, or contact support if this keeps happening."}}function Ud(t,a){if(t.current)return a()}function AQ(t){const{visibleRowCount:a,stableHeaderCount:s,isCountRefreshInFlight:r,refreshWatchdogTripped:n,reviewingLock:i,settleWindowActive:l=!1}=t;return(n||i)&&a>0?a:l&&s!==null?s:a>0&&(s===null||s<a)?a:r?s:a}const jQ=2e3;function TQ(t){const{lockedViewActive:a,stableHeaderCount:s,visibleRowCount:r}=t;return a&&s!==null&&r>0&&s>r}function IQ(t,a){return t&&t.kickoffToken===a?null:t}async function G1(t,a,s){const r=s.fetchImpl??fetch,n=s.log??(()=>{}),i=s.errorLog??(()=>{});s.setStrAggregatorLoading(!0),s.setStrAggregatorProviders(null),s.resetStrDbMerged();try{const l=s.parseAddress(a.subjectAddress||""),c=l?.city||"",d=l?.state||a.subjectState||"",p=a.subjectZipCode||l?.zip||"",u=new URLSearchParams({address:a.subjectAddress,city:c,state:d,zip:p});a.geometryOverride?(u.set("lat",String(a.geometryOverride.lat)),u.set("lng",String(a.geometryOverride.lng)),u.set("radiusMiles",String(a.geometryOverride.radiusMiles))):a.subjectCoordinates&&(u.set("lat",String(a.subjectCoordinates.lat)),u.set("lng",String(a.subjectCoordinates.lng))),a.subjectBedrooms!=null&&!Number.isNaN(a.subjectBedrooms)&&u.set("bedrooms",String(a.subjectBedrooms)),a.subjectPropertyType&&u.set("propertyType",a.subjectPropertyType);const m=await r(`/api/str/propmix-comps?${u}`,{signal:t.signal});if(t.signal.aborted)return;if(!m.ok)throw new Error(`Aggregator request failed with status ${m.status}`);const h=await m.json();if(t.signal.aborted)return;if(s.setStrAggregatorProviders({queried:h.providersQueried||[],succeeded:h.providersSucceeded||[],errors:h.providerErrors||{},finalRadiusMiles:h.finalRadiusMiles,providerDiag:h.providerDiag||null}),h.success&&h.comps){const f=h.comps.map(s.normalizeStrToCompResult);s.setStrCompResults(f),n("[PropertyLab] Loaded",f.length,"STR comps from aggregator. Providers:",h.providersSucceeded?.join(", "),"Radius:",h.finalRadiusMiles,"mi")}else s.setStrCompResults([]),n("[PropertyLab] Aggregator returned no STR comps. Errors:",h.providerErrors)}catch(l){if(!!l&&(l.name==="AbortError"||t.signal.aborted))return;i("[PropertyLab] Failed to load STR comps from aggregator:",l),s.setStrCompResults([]),s.setStrAggregatorProviders({queried:[],succeeded:[],errors:{aggregator:l?.message||"Failed to reach STR data aggregator"}})}finally{t.signal.aborted||s.setStrAggregatorLoading(!1)}}function cI(t,a){return!(t==null||a==null||typeof t!="number"||typeof a!="number"||Number.isNaN(t)||Number.isNaN(a)||!Number.isFinite(t)||!Number.isFinite(a)||t===0&&a===0)}function CQ(t){const a="adr"in t||"dataSource"in t,s=a?t.adr?parseFloat(String(t.adr)):0:t.strAverageDailyRate?parseFloat(String(t.strAverageDailyRate)):0,r=a?t.occupancyRate!=null?parseFloat(String(t.occupancyRate)):void 0:t.strOccupancyRate?parseFloat(String(t.strOccupancyRate)):void 0,n=a?t.rating!=null?parseFloat(String(t.rating)):void 0:t.strRating?parseFloat(String(t.strRating)):void 0,i=a?t.revenue!=null?parseFloat(String(t.revenue)):void 0:t.strGrossRevenue12mo?parseFloat(String(t.strGrossRevenue12mo)):void 0,l=t.propertyType&&t.propertyType!=="STR"?t.propertyType:"Residential",c=a?t.lat!=null?parseFloat(String(t.lat)):null:t.latitude!=null?parseFloat(String(t.latitude)):null,d=a?t.lng!=null?parseFloat(String(t.lng)):null:t.longitude!=null?parseFloat(String(t.longitude)):null,p=cI(c,d),u=p?c:0,m=p?d:0,h=a?t.zip||"":t.zipCode||"",f=t.sqft??0,v=a?t.beds??0:t.bedrooms??0,S=a?t.baths!=null?parseFloat(String(t.baths)):0:t.bathrooms?parseFloat(String(t.bathrooms)):0,N=a?t.distanceMiles||0:t.distance||0,x=a?t.photoUrl||void 0:t.primaryPhotoUrl||void 0,y=a?t.dataSource||t.platform||"":t.strSource||"",b=a?t.reviewCount:t.strReviewCount;return{id:String(t.id),snapshotId:String(t.id),address:t.address||"Unknown Address",city:t.city||"",state:t.state||"",zip:h,fullAddress:`${t.address||""}, ${t.city||""}, ${t.state||""} ${h}`.trim(),coordinates:p?{lat:u,lng:m}:null,distance:N,status:"CLSD",saleDate:void 0,price:s,pricePerSqft:void 0,gla:f,beds:v,baths:S,yearBuilt:t.yearBuilt??0,lotSize:t.lotSize??void 0,garageSpaces:t.garageSpaces??void 0,dom:0,propertyType:l,photoUrl:x,photos:x?[x]:[],selectionState:"none",isStrProperty:!0,strSource:y,strProviderId:t.strProviderId||t.id,strListingName:t.strListingName||t.listingName||"",strRentalType:t.strRe
45ntalType||"",strAverageDailyRate:s,strOccupancyRate:r,strGrossRevenue12mo:i,strRating:n,strReviewCount:b,strGuestCapacity:t.strGuestCapacity,strMaxGuests:t.strGuestCapacity,strProvider:y,strAmenities:t.strAmenities,derivedAddressSource:t.derivedAddressSource??null,derivedAddressConfidence:t.derivedAddressConfidence??null,sourceAddressWasCityLevel:t.sourceAddressWasCityLevel}}function RQ(t){const a=t.circles.length>0,s=t.polygons.length>0;if(!a&&!s)return;let r,n,i;if(a){const c=t.circles[0];r=c.center.lat,n=c.center.lng,i=c.radiusMeters/1609.34}else{const c=t.polygons[0];if(c.path.length===0)return;const d=c.path.map(v=>v.lat),p=c.path.map(v=>v.lng);r=(Math.min(...d)+Math.max(...d))/2,n=(Math.min(...p)+Math.max(...p))/2;const u=r,m=n,h=(v,S,N,x)=>{const b=(N-v)*Math.PI/180,j=(x-S)*Math.PI/180,T=Math.sin(b/2)**2+Math.cos(v*Math.PI/180)*Math.cos(N*Math.PI/180)*Math.sin(j/2)**2;return 6371*2*Math.atan2(Math.sqrt(T),Math.sqrt(1-T))};i=Math.max(...c.path.map(v=>h(u,m,v.lat,v.lng)))*.621371}const l=c=>typeof c=="number"&&Number.isFinite(c)&&!Number.isNaN(c);if(!(!l(r)||!l(n)||!l(i)||i<=0))return{lat:r,lng:n,radiusMiles:i}}function EQ(t,a){return t.filter(s=>a.has(s.snapshotId||s.id)).sort((s,r)=>(s.dom??0)-(r.dom??0))}function wQ(t){const a=t.coordinates;return!!a&&typeof a.lat=="number"&&typeof a.lng=="number"&&!Number.isNaN(a.lat)&&!Number.isNaN(a.lng)}async function PQ(t,a,s){const r=s.log??(()=>{}),n=s.warn??(()=>{});s.setActiveStreamLoading(!0);try{const i=await s.apiPost("/api/comps/search",a,{throwOnSuccessFalse:!1,signal:t.signal});if(t.signal.aborted)return;if(s.isCurrentSearch&&!s.isCurrentSearch()){r("[PropertyLab] Active stream follow-up superseded by newer search — discarding results");return}const d=(i?.comps||i?.results||[]).filter(wQ).map(p=>({...p,similarityScore:s.scoreComp(p)}));if(d.length===0){r("[PropertyLab] Active stream returned 0 valid comps");return}if(t.signal.aborted)return;if(s.isCurrentSearch&&!s.isCurrentSearch()){r("[PropertyLab] Active stream follow-up superseded by newer search — discarding results before merge");return}s.mergeScoredActiveComps(d)}catch(i){if(!!i&&(i.name==="AbortError"||t.signal.aborted))return;n("[PropertyLab] Active stream follow-up failed:",i)}finally{t.signal.aborted||s.setActiveStreamLoading(!1)}}const OQ=({submarketComps:t,broadComps:a,subject:s,onContinue:r,onSkip:n})=>{const[i,l]=o.useState(null),[c,d]=o.useState(3),p=o.useMemo(()=>{const h=new Map;for(const f of[...t,...a])h.set(f.id,f);return Array.from(h.values())},[t,a]),u=Yd({mutationFn:async()=>(await Qo("POST","/api/multi-method/concessions/analyze",{comps:p})).json(),onSuccess:h=>{l(h),d(Number(h.suggestedThresholdPct.toFixed(1)))}});return o.useEffect(()=>{if(p.length===0){l({prevalencePct:0,averagePct:0,suggestedThresholdPct:3,highConcessionComps:[]}),d(3);return}u.mutate()},[p]),u.isPending?e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(tx,{className:"h-8 w-48"}),e.jsx(tx,{className:"h-4 w-64"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(tx,{className:"h-32 rounded-lg"}),e.jsx(tx,{className:"h-32 rounded-lg"}),e.jsx(tx,{className:"h-32 rounded-lg"})]}),e.jsx(tx,{className:"h-40 rounded-lg"})]}):e.jsxs("div",{className:"space-y-6 p-6 bg-slate-50 min-h-full",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("h2",{className:"text-xl font-semibold text-slate-900",children:"Concession Analysis"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Analyze seller concessions across the selected datasets."})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(ja,{className:"bg-white border-slate-200 shadow-sm",children:e.jsxs(Ta,{className:"pt-6",children:[e.jsx("div",{className:"text-sm font-medium text-slate-500 mb-1",children:"Prevalence"}),e.jsxs("div",{className:"text-2xl font-bold text-slate-900",children:[i?.prevalencePct.toFixed(1),"%"]}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:"Comps with concessions"})]})}),e.jsx(ja,{className:"bg-white border-slate-200 shadow-sm",children:e.jsxs(Ta,{className:"pt-6",children:[e.jsx("div",{className:"text-sm font-medium text-slate-500 mb-1",children:"Average %"}),e.jsxs("div",{className:"text-2xl font-bold text-slate-900",children:[i?.averagePct.toFixed(1),"%"]}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:"Of sale price"})]})}),e.jsx(ja,{className:"bg-white border-slate-200 shadow-sm",children:e.jsxs(Ta,{className:"pt-6",children:[e.jsx("div",{className:"text-sm font-medium text-slate-500 mb-1",children:"Suggested"}),e.jsxs("div",{className:"text-2xl font-bold text-[#C5A572]",children:[i?.suggestedThresholdPct.toFixed(1),"%"]}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-1",children:"Threshold cutoff"})]})})]}),e.jsx(ja,{className:"bg-white border-slate-200 shadow-sm",children:e.jsxs(Ta,{className:"pt-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-blue-50 border border-blue-100 rounded-md",children:[e.jsx(Di,{className:"w-5 h-5 text-blue-500 mt-0.5"}),e.jsx("p",{className:"text-xs text-blue-700 leading-relaxed",children:'Adjustments will only be applied to comps where concessions exceed this threshold. This filters out "standard" market concessions to focus on significant seller contributions.'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-sm font-medium text-slate-700 flex items-center gap-2",children:[e.jsx(xv,{className:"w-4 h-4 text-slate-400"}),"Concession Threshold (%)"]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ze,{type:"number",min:0,max:10,step:.5,value:c,onChange:h=>d(parseFloat(h.target.value)||0),className:"w-32","data-testid":"input-concession-threshold"}),e.jsx("span",{className:"text-sm text-slate-400",children:"Range: 0.0% to 10.0%"})]})]})]})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 pt-4",children:[e.jsx(De,{onClick:()=>r(c),className:"w-full max-w-md bg-emerald-600 hover:bg-emerald-700 text-white py-6","data-testid":"btn-mm-next",children:"Apply Threshold & Continue"}),e.jsx("button",{onClick:n,className:"text-sm text-slate-500 hover:text-slate-700 underline underline-offset-4","data-testid":"btn-mm-skip",children:"Skip — No Concession Adjustment"})]})]})},LQ=({assignmentId:t,subject:a,submarketComps:s,broadComps:r,effectiveDate:n,onContinue:i,onSkip:l,embeddedTimeVault:c})=>{const d=Vr({queryKey:["/api/time-adj/sessions",{assignmentId:t}],queryFn:async()=>{const y=await fetch(`/api/time-adj/sessions?assignmentId=${encodeURIComponent(t)}`,{credentials:"include"});if(y.status===404)return null;if(!y.ok)throw new Error(`Failed to load TimeVault session: ${y.status}`);return y.json()},enabled:!!t,retry:!1}),p=o.useMemo(()=>{const y=new Map;for(const b of[...s,...r])y.set(b.id,b);return Array.from(y.values())},[s,r]),u=n??new Date,m=d.data??null,h=o.useMemo(()=>
45{if(!m||!m.decisionSavedAt)return null;if(m.selectedOption==="zero"||m.finalMethod==="zero")return 0;const y=m.linearRatePctPerMonth;if(y==null)return null;const b=typeof y=="string"?parseFloat(y):y;return Number.isFinite(b)?b:null},[m]),f=y=>{if(p.length===0)return{};if(y===0){const T={};for(const O of p)T[O.id]=O.salePrice;return T}const b=y/100,j={};for(const T of p){if(!T.saleDate)continue;const O=o2(T.saleDate);if(!Ex(O))continue;const E=pb(u,O);if(E<=0){j[T.id]=T.salePrice;continue}const R=1+b*E;j[T.id]=Math.round(T.salePrice*R)}return j},v=o.useMemo(()=>h==null?{}:f(h),[p,h,u]),S=Object.keys(v).length,N=Object.entries(v).slice(0,3),x=`/property-lab/time-vault?assignmentId=${encodeURIComponent(t)}`;return e.jsxs("div",{className:"p-6 bg-slate-50 min-h-full space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pu,{className:"w-5 h-5 text-blue-600"}),e.jsx("h2",{className:"text-xl font-semibold text-slate-900",children:"Time Adjustment"})]}),e.jsx("p",{className:"text-sm text-slate-500",children:c?"Run the TimeVault wizard inline below, then apply the finalized rate to the orchestrator without leaving the drawer.":"The drawer consumes the rate the standalone TimeVault wizard finalized for this assignment so the multi-method math doesn't double-count market drift."})]}),c&&e.jsx(ja,{className:"bg-white border-slate-200 shadow-sm overflow-hidden","data-testid":"card-time-embedded-wizard",children:e.jsx(Ta,{className:"p-0",children:c})}),d.isLoading&&e.jsx(ja,{className:"bg-white border-slate-200 shadow-sm",children:e.jsxs(Ta,{className:"pt-6 flex items-center gap-3 text-sm text-slate-600",children:[e.jsx(za,{className:"w-4 h-4 animate-spin"}),"Loading TimeVault session…"]})}),!d.isLoading&&h!=null&&e.jsxs(ja,{className:"bg-white border-emerald-200 shadow-sm","data-testid":"card-time-session",children:[e.jsx(Do,{className:"pb-2",children:e.jsxs(ko,{className:"text-base font-semibold text-[#072034] flex items-center gap-2",children:[e.jsx(kr,{className:"w-4 h-4 text-emerald-600"}),"TimeVault rate is ready"]})}),e.jsxs(Ta,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-slate-500 uppercase tracking-wide",children:"Monthly rate"}),e.jsxs("div",{className:"text-2xl font-bold text-[#072034]",children:[h.toFixed(3),"%"]}),e.jsxs("div",{className:"text-[11px] text-slate-500",children:["(",(h*12).toFixed(2),"% annualized)"]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-slate-500 uppercase tracking-wide",children:"Source"}),e.jsx("div",{className:"text-sm text-slate-700",children:m?.selectedDataset==="fhfa"?"FHFA HPI":m?.selectedDataset==="submarket"?"Submarket sales":"Market sales"}),e.jsxs("div",{className:"text-[11px] text-slate-500",children:["Method: ",m?.finalMethod??m?.selectedOption??"linear"]})]})]}),S>0&&e.jsxs("div",{className:"rounded-md border border-slate-200 bg-slate-50 p-3 space-y-1","data-testid":"time-preview",children:[e.jsxs("div",{className:"text-[11px] font-semibold text-slate-600 uppercase tracking-wide",children:["Preview (",S," comp",S===1?"":"s",")"]}),N.map(([y,b])=>{const j=p.find(O=>O.id===y);if(!j)return null;const T=b-j.salePrice;return e.jsxs("div",{className:"text-[12px] flex justify-between",children:[e.jsx("span",{className:"text-slate-700 truncate",children:j.address??y.slice(0,8)}),e.jsxs("span",{className:"font-mono",children:["$",j.salePrice.toLocaleString()," → $",b.toLocaleString(),e.jsxs("span",{className:T>=0?"text-emerald-700 ml-2":"text-red-700 ml-2",children:["(",T>=0?"+":"","$",T.toLocaleString(),")"]})]})]},y)}),S>N.length&&e.jsxs("div",{className:"text-[11px] text-slate-500 italic",children:["+",S-N.length," more comp(s)…"]})]})]})]}),!d.isLoading&&h==null&&e.jsx(ja,{className:`bg-white shadow-sm ${c?"border-slate-200":"border-amber-200"}`,"data-testid":"card-time-no-session",children:e.jsxs(Ta,{className:"pt-6 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[c?e.jsx(on,{className:"w-5 h-5 text-slate-400 mt-0.5 shrink-0"}):e.jsx(Ns,{className:"w-5 h-5 text-amber-500 mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-900",children:c?"Finish the TimeVault wizard above":"No finalized TimeVault rate for this assignment"}),e.jsx("p",{className:"text-xs text-slate-600",children:c?"Complete the Decision step in the wizard above to derive a rate. The drawer will pick it up automatically once you save.":d.error?"We could not load a TimeVault session for this assignment. Open the standalone wizard to derive a rate, then return here.":m?"A session exists but no decision has been saved. Finalize the wizard's decision step to derive a rate.":"There is no TimeVault session yet. Open the standalone wizard to derive a market-supported rate, then return here."})]})]}),!c&&e.jsxs("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-700 hover:underline inline-flex items-center gap-1","data-testid":"link-open-timevault-full",children:[e.jsx(rf,{className:"w-4 h-4"}),"Open the TimeVault wizard"]})]})}),e.jsxs("div",{className:"flex flex-col items-center gap-3 pt-2",children:[e.jsxs(De,{onClick:()=>{h!=null&&i(f(h))},disabled:h==null,className:"w-full max-w-md bg-emerald-600 hover:bg-emerald-700 text-white py-6 flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"btn-mm-apply-time",children:[e.jsx(mc,{className:"w-4 h-4"}),h==null?c?"Finalize the wizard's Decision step to continue":"Run TimeVault wizard first":"Apply TimeVault Rate & Continue"]}),e.jsxs(De,{variant:"outline",onClick:l,className:"w-full max-w-md border-slate-200 text-slate-600 flex items-center gap-2 py-6","data-testid":"btn-mm-skip-time",children:[e.jsx(i2,{className:"w-4 h-4"}),"Skip Time Adjustment"]})]})]})},DQ={adjust:"DRIVER",caution:"MINOR","do-not-adjust":"NO SUPPORT"},kQ={adjust:"Driver — this attribute swings price the most across your comp set. The badge ranks effect size, not direction: a negative recommended rate is fine (sign = direction, driver = magnitude). Apply the recommended rate wherever the subject differs.",caution:"Minor — this attribute moves price less across your comp set than the drivers. Still apply the recommended rate where the subject differs; the badge only tells you the swing is smaller, not that the adjustment should be skipped.","do-not-adjust":"No Support — no method produced a defensible automated rate for this attribute. What to do: skip the adjustment, enter a manual rate, or expand the comp set so a method qualifies."},MQ=({headline:t})=>{const a=s=>{switch(s){case"adjust":return"bg-[#D0FAE5] text-[#007A55] hover:bg-[#D0FAE5] border-emerald-200";case"caution":return"bg-[#FEF3C7] text-[#92400E] hover:bg-[#FEF3C7] border-amber-200";case"do-not-adjust":return"bg-[#FEE2E2] text-[#B91C1C] hover:bg-[#FEE2E2] border-red-200";default:return"bg-slate-100 text-slate-600 border-slate-200"}};return e.jsxs(ja,{className:"border-slate-200 rounded-lg overflow-hidden","data-testid":"market-signal-headline",children:[e.jsx(Do,{
45className:"bg-white pb-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ql,{className:"w-5 h-5 text-[#072034] mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ko,{className:"text-[14px] font-bold text-[#072034]",children:"Market Signal Headline"}),e.jsx("p",{className:"text-[11px] text-slate-500",children:"Ranked by effect size — DRIVER attributes carry the bulk of the adjustment weight"}),e.jsxs("div",{className:"mt-2 flex items-start gap-1.5 rounded-md bg-slate-50 border border-slate-200 px-2 py-1.5","data-testid":"market-signal-explainer",children:[e.jsx(on,{className:"w-3.5 h-3.5 text-slate-500 mt-0.5 flex-shrink-0"}),e.jsxs("p",{className:"text-[11px] text-slate-600 leading-snug",children:["Ranked by how much each attribute ",e.jsx("span",{className:"font-semibold",children:"swings price across your comp set"})," —"," ","not which to adjust. Apply the recommended rate for every attribute the subject differs on. A negative recommended rate next to a DRIVER badge is not a contradiction: ",e.jsx("span",{className:"font-semibold",children:"sign = direction, driver = magnitude."})]})]})]})]})}),e.jsxs(Ta,{className:"space-y-4 pt-0",children:[e.jsx("div",{className:"space-y-3",children:t.ranked.map((s,r)=>e.jsxs("div",{className:"space-y-1","data-testid":`headline-entry-${s.attribute}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:Q("inline-flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold flex-shrink-0",r===0?"bg-[#072034] text-white":r<=2?"bg-slate-700 text-white":"bg-slate-200 text-slate-600"),"data-testid":`headline-rank-${s.attribute}`,children:["#",r+1]}),e.jsx("div",{className:"w-20 text-[12px] font-medium text-[#072034] truncate",children:qd[s.attribute]}),e.jsx("div",{className:"flex-1 h-2 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-[#072034] rounded-full transition-all duration-500",style:{width:`${Math.max(0,Math.min(100,s.effectSizePct))}%`}})}),e.jsxs("div",{className:"w-10 text-right text-[11px] font-semibold text-slate-600",children:[Math.round(s.effectSizePct),"%"]}),e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(kt,{tabIndex:0,className:Q("px-2 py-0.5 rounded text-[10px] font-bold border w-[88px] justify-center cursor-help focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-slate-400",a(s.recommendation)),"data-testid":`recommendation-chip-${s.attribute}`,children:DQ[s.recommendation]??s.recommendation.toUpperCase()})}),e.jsxs(Wa,{side:"left",className:"max-w-xs text-[11px] leading-snug space-y-1","data-testid":`recommendation-chip-tooltip-${s.attribute}`,children:[e.jsx("div",{children:kQ[s.recommendation]??s.recommendation}),s.recommendation==="caution"&&s.note&&e.jsxs("div",{className:"pt-1 border-t border-slate-700/30 italic",children:["Demoted because of correlation with another attribute, not because the effect size was small. ",s.note]})]})]})})]}),s.note&&e.jsxs("div",{className:"pl-9 flex items-start gap-1 text-[10px] text-amber-700 italic",children:[e.jsx(Ns,{className:"w-3 h-3 flex-shrink-0 mt-0.5"}),e.jsx("span",{"data-testid":`headline-note-${s.attribute}`,children:s.note})]})]},s.attribute))}),t.multicollinearity.suppressBedBathDollar&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-[#FEF3C7] border border-[#FDE68A] rounded-md","data-testid":"multicollinearity-alert",children:[e.jsx(Ns,{className:"w-4 h-4 text-[#92400E] mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-[11px] text-[#92400E] leading-relaxed",children:[e.jsx("span",{className:"font-bold",children:"Multicollinearity detected"})," — Bedroom/Bathroom dollar adjustments suppressed. Use room-count proxy via GLA instead."]})]})]}),e.jsx(dL,{className:"bg-slate-50 py-2 border-t border-slate-100",children:e.jsx("p",{className:"text-[11px] text-slate-500 italic w-full",children:t.summary})})]})},FQ={concern:{box:"bg-red-50 border-red-200",icon:"text-red-600",label:"text-red-900"},caution:{box:"bg-amber-50 border-amber-200",icon:"text-amber-600",label:"text-amber-900"}},H1={clean:{cls:"bg-emerald-100 text-emerald-800 border-emerald-200",emoji:"✅",short:"Time-scrub clean"},residual:{cls:"bg-amber-100   text-amber-800   border-amber-200",emoji:"⚠️",short:"Residual time trend"},suppressed:{cls:"bg-slate-100   text-slate-600   border-slate-200",emoji:"—",short:"Time-scrub n/a"}},_Q=({subjectFit:t,timeScrubValidation:a,onDismiss:s})=>{const r=t?.warnings??[],n=r.length>0,i=!!a;if(!n&&!i)return null;if(!n&&i){const l=H1[a.status];return e.jsx("div",{className:"flex items-center justify-end mb-2","data-testid":"subject-fit-banner-timescrub-only",children:e.jsxs("span",{className:Q("inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[11px] font-medium",l.cls),title:a.message,"data-testid":`time-scrub-chip-${a.status}
45`,children:[e.jsx("span",{"aria-hidden":!0,children:l.emoji}),e.jsx("span",{children:l.short})]})})}return e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50/40 p-3 mb-3","data-testid":"subject-fit-banner",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ns,{className:"w-4 h-4 text-amber-700 shrink-0"}),e.jsx("span",{className:"text-[12px] font-bold text-amber-900",children:"Heads up — your subject doesn't quite fit the comp pool"})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[i&&(()=>{const l=H1[a.status];return e.jsxs("span",{className:Q("inline-flex items-center gap-1 rounded-full border px-2 py-0 text-[10px] font-semibold leading-none h-5",l.cls),title:a.message,"data-testid":`time-scrub-chip-${a.status}`,children:[e.jsx("span",{"aria-hidden":!0,children:l.emoji}),e.jsx("span",{children:l.short})]})})(),s&&e.jsx(De,{variant:"ghost",size:"sm",onClick:s,className:"h-6 w-6 p-0 text-amber-700 hover:bg-amber-100","data-testid":"button-dismiss-subject-fit-banner","aria-label":"Dismiss subject-fit warnings",children:e.jsx(ur,{className:"w-3.5 h-3.5"})})]})]}),e.jsx("ul",{className:"mt-2 space-y-1.5",children:r.map((l,c)=>{const d=FQ[l.severity],p=l.severity==="concern"?Ns:on;return e.jsxs("li",{className:Q("rounded border px-2.5 py-1.5 flex items-start gap-2",d.box),"data-testid":`subject-fit-warning-${l.kind}-${l.affectedAttribute??"global"}`,children:[e.jsx(p,{className:Q("w-3.5 h-3.5 mt-0.5 shrink-0",d.icon)}),e.jsx("div",{className:"min-w-0",children:e.jsx("p",{className:Q("text-[12px] font-medium leading-snug",d.label),children:l.message})})]},`${l.kind}-${l.affectedAttribute??"global"}-${c}`)})}),e.jsx("p",{className:"mt-2 text-[10px] italic text-amber-800/80",children:"These notes describe the comparable pool the engine is reading from — the recommended rates above are still your starting point, just review them with these caveats in mind."})]})},CM=({diagnostic:t,testIdSuffix:a,className:s})=>{if(!t||t.candidatesEvaluated===0)return null;const r=Object.entries(t.rejections).filter(([,l])=>l>0).sort((l,c)=>c[1]-l[1]),n=r.slice(0,2),i=n.length===0?`${t.candidatesEvaluated} candidates → ${t.passedAllGates} passed all gates`:`${t.candidatesEvaluated} candidates → `+n.map(([l,c])=>`${c} ${_P[l].toLowerCase()}`).join(" · ");return e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("div",{className:Q("text-[10px] text-slate-600 leading-snug cursor-help",s),"data-testid":`paired-rejection-diagnostic-${a}`,children:i})}),e.jsx(Wa,{side:"top",align:"start",className:"max-w-xs",children:e.jsxs("div",{className:"text-[11px] space-y-1","data-testid":`paired-rejection-tooltip-${a}`,children:[e.jsx("div",{className:"font-semibold",children:t.candidatesCapped?`First ${t.candidatesEvaluated} candidate pairs evaluated`:`${t.candidatesEvaluated} candidate pairs evaluated`}),e.jsxs("div",{className:"text-slate-300",children:[t.passedAllGates," passed every gate"]}),r.length>0?e.jsx("ul",{className:"space-y-0.5 pl-1",children:r.map(([l,c])=>e.jsxs("li",{children:[e.jsx("span",{className:"font-semibold",children:c})," · ",_P[l]]},l))}):e.jsx("div",{className:"italic text-slate-300",children:"No candidates were rejected by a gate."}),t.candidatesCapped&&e.jsxs("div",{className:"text-[10px] italic text-slate-300 pt-1 border-t border-slate-700",children:["Search capped at the first ",t.candidatesEvaluated," candidate pairs for performance."]})]})})]})})};function RM(t){if(t.method==="paired"){const a=t.derivation?.kind==="paired"?t.derivation.pairs.length:t.qualified?t.sampleSize:0;return t.qualified?`${a} pair${a===1?"":"s"}`:`${a} pair${a===1?"":"s"} · need 3`}if(t.method==="grouped"){const a=t.derivation?.kind==="grouped"?t.derivation.buckets.length:0;return t.qualified?a>0?`${a} bucket${a===1?"":"s"} · selected`:"selected":`${a} bucket${a===1?"":"s"} · need 2`}return t.method==="regression"?t.qualified?`${t.sampleSize} evaluated · selected`:t.pValue!=null&&t.pValue>.1?`coefficient not significant (p=${t.pValue.toFixed(3)})`:`${t.sampleSize} evaluated · need 15`:t.reason||"no result"}const EM=({data:t,outcome:a,testIdSuffix:s,className:r})=>{if(t.lockedCount===0)return null;const i=t.rejectedCount===0||!t.topRejectionLabel?"all usable":`${t.usableCount} usable (${t.topRejectionLabel})`;return e.jsxs("div",{className:Q("text-[10px] text-slate-600 leading-snug",r),"data-testid":`dataset-funnel-${s}`,children:[t.lockedCount," locked → ",i," → ",a]})},UQ={agree:"What to do: lock the recommended cell with confidence — the methods reinforce each other.",mixed:"What to do: review the recommended cell before locking. The other methods land in the same neighborhood, so a small adju
45stment to the rate is reasonable if you have a defensible reason.",disagree:"What to do: the recommended cell is still the most defensible. Review it before locking, or widen comps if the spread is uncomfortable.",single:"What to do: only one method qualified. Review the rate carefully before locking, or widen comps to see whether other methods agree.",none:"What to do: no automated rate is defensible — skip the adjustment, enter a manual rate, or expand the comp set so a method qualifies."},VQ=({agreement:t,attributeKey:a})=>{if(!t)return null;const r={agree:{cls:"bg-emerald-100 text-emerald-800 border-emerald-200",emoji:"✅",short:"Agree"},mixed:{cls:"bg-amber-100   text-amber-800   border-amber-200",emoji:"⚠️",short:"Mixed"},disagree:{cls:"bg-red-100     text-red-800     border-red-200",emoji:"⚠️",short:"Disagree"},single:{cls:"bg-blue-100    text-blue-800    border-blue-200",emoji:"🔵",short:"Solo"},none:{cls:"bg-slate-100   text-slate-600   border-slate-200",emoji:"—",short:"No data"}}[t.level];return e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsxs("span",{tabIndex:0,className:Q("inline-flex items-center gap-1 rounded-full border px-2 py-0 text-[10px] font-semibold leading-none h-5 cursor-help focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-slate-400",r.cls),"data-testid":`agreement-chip-${a}`,children:[e.jsx("span",{"aria-hidden":!0,children:r.emoji}),e.jsx("span",{children:r.short})]})}),e.jsxs(Wa,{side:"top",className:"max-w-xs text-[11px] leading-snug space-y-1","data-testid":`agreement-chip-tooltip-${a}`,children:[e.jsx("div",{children:t.summary}),e.jsx("div",{className:"font-semibold pt-1 border-t border-slate-700/30",children:UQ[t.level]})]})]})})},$Q=({attribute:t})=>{if(!t.recommendedKey)return null;const a=t.results.find(l=>`${l.method}:${l.dataset}`===t.recommendedKey);if(!a)return null;const s=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}),r=t.whyThisRate?.headline??`Recommended ${qd[t.attribute]} rate: ${s.format(a.rate)}/${a.unit.replace(/^\$\//,"")} (${uf[a.method]} on ${af[a.dataset]}).`,n=t.whyThisRate?.reasons?.[0],i=a.confidence==="green"?"bg-emerald-400":a.confidence==="yellow"?"bg-amber-400":"bg-red-400";return e.jsxs("div",{className:"bg-[#072034] text-white px-3 py-2 border-b border-slate-700","data-testid":`recommended-strip-${t.attribute}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full bg-[#C5A572] text-[#072034] px-1.5 py-0 text-[9px] font-bold uppercase tracking-wide leading-none h-4",children:"Recommended"}),e.jsxs("span",{className:"text-[11px] font-semibold text-slate-100 truncate",children:[uf[a.method]," · ",af[a.dataset]]}),e.jsx("span",{className:Q("w-2 h-2 rounded-full flex-shrink-0",i)}),e.jsxs("span",{className:"ml-auto text-[13px] font-bold tabular-nums",children:[s.format(a.rate),e.jsxs("span",{className:"text-[10px] font-normal text-slate-300 ml-0.5",children:["/",a.unit.replace(/^\$\//,"")]})]})]}),e.jsx("p",{className:"text-[11px] text-slate-200 leading-snug","data-testid":`recommended-strip-headline-${t.attribute}`,children:r}),n&&e.jsx("p",{className:"text-[10px] text-slate-300 italic leading-snug mt-0.5","data-testid":`recommended-strip-reason-${t.attribute}`,children:n})]})},BQ=({attribute:t,selectedKey:a,onSelect:s,onShowDerivation:r,onLockApply:n,onNoAdjustment:i,onManual:l,isLocking:c,submarketFunnel:d,marketFunnel:p})=>{const u=N=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(N.rate),m=N=>{switch(N){case"green":return"bg-emerald-500";case"yellow":return"bg-amber-500";case"red":return"bg-red-500";default:return"bg-slate-300"}},f=t.results.some(N=>N.method==="peeled")?["paired","peeled","grouped","regression"]:["paired","grouped","regression"],v=["submarket","broad"],S=(N,x)=>t.results.find(y=>y.method===N&&y.dataset===x);return e.jsxs(ja,{className:Q("border-slate-200 rounded-lg overflow-hidden",t.insufficientData&&"bg-slate-50 opacity-80"),"data-testid":`attribute-card-${t.attribute}`,children:[e.jsxs(Do,{className:"p-3 border-b bg-white flex flex-row items-center justify-between space-y-0",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ko,{className:"text-[14px] font-bold text-[#072034] truncate",children:qd[t.attribute]}),t.agreement&&e.jsx(VQ,{agreement:t.agreement,attributeKey:t.attribute})]}),l&&e.jsxs(De,{variant:"ghost",size:"sm",onClick:l,className:"h-7 px-2 text-[11px] text-slate-500 hover:text-[#072034] hover:bg-slate-100","data-testid":`button-manual-${t.attribute}`,title:"Enter a manual adjustment rate for this attribute",children:[e.jsx(Ru,{className:"w-3 h-3 mr-1"}),"Manual"]})]}),!t.insufficientData&&e.jsx($Q,{attribute:t}),e.jsxs(Ta,{className:"p-0",children:[t.insufficientData?e.jsxs("div",{className:"p-6 flex flex-col items-center justify-center text-center space-y-2","data-testid":`no-support-state-${t.attribute}`,children:[e.jsxs("p",{className:"text-[12px] text-slate-600 font-semibold",children:["No defensible automated rate for ",qd[t.attribute],"."]}),t.insufficientReason&&e.jsx("p",{className:"text-[11px] text-slate-500 italic",children:t.insufficientReason}),e.jsxs("p",{className:"text-[11px] text-slate-600 leading-snug max-w-sm",children:[e.jsx("span",{className:"font-semibold",children:"What to do:"})," ","skip this adjustment, enter a manual rate, or expand the comp set so a method qualifies."]})]}):e.jsxs("div",{className:"grid grid-cols-2",children:[v.map((N,x)=>{const b=(N==="submarket"?d:p)?.lockedCount??null;return e.jsxs("div",{className:Q("text-[10px] font-bold text-slate-400 uppercase px-3 py-1.5 bg-slate-50/50 border-b flex items-center gap-1",x===0&&"border-r"),"data-testid":`card-dataset-header-${N}-${t.attribute}`,children:[e.jsx("span",{children:af[N]}),b!=null&&b>0&&e.jsxs("span",{className:"font-semibold text-slate-500 normal-case","data-testid":`card-dataset-locked-count-${N}-${t.attribute}`,children:["· ",b," locked"]})]},`header-${N}`)}),f.flatMap((N,x)=>v.map((y,b)=>{const j=y==="submarket"?d:p,T=S(N,y),O=Q(b===0&&"border-r",x>0&&"border-t");if(!T)return e.jsx("div",{className:Q(O,"min-h-[5rem] bg-slate-50/20")},`${N}-${y}`);const E=`${N}:${y}`,R=a===E,G=t.recommendedKey===E,U=T.qualified,C=U?WT(T.sampleSize,t.attribute):null,F=!!C,A=U?C:T.reason,M=N==="paired"?t.results.find(oe=>oe.method==="grouped"&&oe.dataset===y):void 0,B=N==="paired"&&!U&&!!M?.qualified;return e.jsx("div",{className:Q("p-3 min-h-[5rem] transition-all group relative cursor-pointer",O,!U&&"opacity-60 cursor-default",R?"bg-[#072034] text-white":"hover:bg-slate-50",G&&!R&&"ring-2 ring-[#C5A572] ring-inset",U&&F&&!R&&"bg-amber-50/60",!U&&"bg-amber-50/40",U&&!G&&!R&&"opacity-80"),onClick:()=>U&&s(T),"data-testid":`method-cell-${E}`,children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:Q("text-[10px] font-medium inline-flex items-center gap-1",R?"text-slate-300":"text-slate-400"),children:[uf[N],U&&G&&e.jsx("span",{className:Q("text-[9px] font-bold uppercase tracking-wide rounded px-1 py-0 leading-none h-3.5 inline-flex items-center",R?"bg-[#C5A572]/20 text-[#C5A572]":"bg-[#C5A572]/15 text-[#7C5E1F]"),"data-testid":`recommended-tag-${E}`,children:"Recommended"}),U&&!G&&e.jsx("span",{className:Q("text-[9px] font-semibold uppercase tracking-wide rounded px-1 py-0 leading-none h-3.5 inline-flex items-center",R?"bg-slate-700 text-slate-300":"bg-slate-100 text-slate-500"),"data-testid":`alternate-tag-${E}`,title:"The engine considered this method but didn't pick it. Click to override the recommendation.",children:"Alternate"}),N==="peeled"&&e.jsx("span",{className:Q("text-[9px] italic ml-1",R?"text-slate-300":"text-slate-500"),"data-testid":`method-cell-peeled-retired-${E}`,children:"(retired)"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(kt,{variant:"outline",className:Q("text-[9px] px-1 py-0 h-4 border-slate-200",R?"text-slate-300 border-slate-700":"text-slate-500",U&&F&&!R&&"border-amber-300 text-amber-700"),"data-testid":`badge-sample-size-${E}`,title:T.method==="paired"?`${T.sampleSize} qualifying pairs (post-trim) from this method engine.${j?` Dataset funnel: ${j.usableCount} usable of ${j.lockedCount} locked.`:""}`:T.method==="grouped"?`${T.sampleSize} comps across qualifying buckets.${j?` Dataset funnel: ${j.usableCount} usable of ${j.lockedCount} locked.`:""}`:`${T.sampleSize} comps used by this method.${j?` Dataset funnel: ${j.usableCount} usable of ${j.lockedCount} locked.`:""}`,children:["n=",T.sampleSize]}),e.jsx("div",{className:Q("w-2 h-2 rounded-full",m(T.confidence))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[j&&e.jsx(EM,{data:j,outcome:RM(T),testIdSuffix:`drawer-${t.attribute}-${y}-${N}`,className:Q(R?"text-slate-300":"text-slate-500")}),e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:U?e.jsxs("span",{className:Q("text-[14px] font-bold",F&&!R&&"italic text-amber-800"),children:[u(T),e.jsxs("span",{className:"text-[10px] ml-0.5 font-normal",children:["/",T.unit]})]}):e.jsx("span",{className:Q("text-[10px] italic leading-snug",R?"text-amber-200":"text-amber-800/90"),"data-testid":`text-method-reason-${E}`,children:T.reason||"Insufficient data"})}),A&&e.jsx(Wa,{children:e.jsx("p",{className:"text-xs max-w-xs","data-testid":`tooltip-method-${E}`,children:A})})]})}),U&&C&&e.jsx("span",{className:Q("text-[10px] italic leading-snug",R?"text-amber-200":"text-amber-800/90"),"data-testid":`text-low-confidence-reason-${E}`,children:C}),T.sanityWarning&&e.jsxs("span",{className:Q("text-[10px] italic leading-snug",R?"text-amber-200":"text-amber-800"),"data-testid":`text-sanity-warning-${E}`,children:["⚠ ",T.sanityWarning]}),T.method==="peeled"&&T.derivation?.kind==="peeled"&&(()=>{const oe=T.derivation,ae=oe.peelingInputs.filter(le=>le.applied),D=oe.peelingInputs.filter(le=>le.skipped),_=ae.map(le=>qd[le.attribute]),$=D.map(le=>qd[le.attribute]);let z,V;return ae.length>0?(z=`Peeled using ${_.join(", ")}.`,D.length>0&&(z+=` Skipped ${$.join(", ")} (no input rate).`),V=`Per-attribute input rates (regression first, grouped paired fallback): ${ae.map(le=>`${qd[le.attribute]}=$${le.rate?.toFixed(2)}/${le.source}`).join("; ")}.${D.length>0?" Skipped attributes had non-zero deltas in the pairs but no qualifying input rate (regression and grouped both unavailable/red), so their contribution was treated as $0 and the residual stays slightly contaminated — confidence is capped accordingly.":""}`):D.length>0?(z=`Deltas on ${$.join(", ")} skipped — no input rate available.`,V=`${$.join(", ")} had non-zero deltas across the kept pairs but no qualifying input rate (regression and grouped both unavailable/red), so their contribution could not be peeled. The residual is NOT strict-equivalent — it carries those uncorrected deltas. Confidence is capped at yellow.`):(z="No other-attribute deltas in pairs — equivalent to strict pairs.",V="No other attribute had a non-zero delta across the kept pairs, so peeling did n
45ot subtract any contribution. Result is identical to running strict paired with the same sanity bands."),e.jsx("span",{className:Q("text-[9px] italic leading-tight",R?"text-slate-300":"text-slate-500"),"data-testid":`peeled-footnote-${E}`,title:V,children:z})})(),T.method==="regression"&&T.derivation?.kind==="regression"&&(T.derivation.excludedOutliers?.length??0)>0&&e.jsx("span",{className:Q("text-[9px] italic leading-tight",R?"text-slate-300":"text-slate-500"),"data-testid":`regression-outlier-footnote-${E}`,title:T.derivation.excludedOutliers.map(oe=>`${oe.address}: ${oe.reason}`).join(`
46`),children:(()=>{const oe=T.derivation.excludedOutliers.length;return`${oe} unusually-priced comp${oe===1?"":"s"} set aside before fitting.`})()}),B&&M&&e.jsx("button",{onClick:oe=>{oe.stopPropagation(),s(M)},className:Q("text-[10px] font-semibold underline text-left not-italic transition-colors",R?"text-gold-400 hover:text-white":"text-blue-600 hover:text-blue-800"),"data-testid":`try-grouped-${t.attribute}-${y}`,title:`Switch selection to Grouped Paired Sales (${af[y]})`,children:"Try Grouped Paired Sales instead →"}),e.jsx("button",{onClick:oe=>{oe.stopPropagation(),r(T)},className:Q("text-[10px] font-semibold underline text-left transition-colors",R?"text-gold-400 hover:text-white":"text-blue-600 hover:text-blue-800",!U&&"hidden"),"data-testid":`show-derivation-${E}`,children:"Show Derivation"}),!U&&T.method==="paired"&&T.rejectionDiagnostic&&e.jsx("div",{className:"mt-1",children:e.jsx(CM,{diagnostic:T.rejectionDiagnostic,testIdSuffix:`card-${E}`,className:Q(R?"text-amber-200":"text-amber-900/80")})})]})]})},`${N}-${y}`)}))]}),!t.insufficientData&&t.results.some(N=>N.method==="paired"&&!N.qualified)&&e.jsxs("p",{className:"text-[11px] text-slate-500 bg-slate-50 border-t border-slate-100 px-3 py-2 leading-snug","data-testid":`paired-vs-grouped-note-${t.attribute}`,children:[e.jsx("span",{className:"font-semibold text-slate-700",children:"Paired vs. Grouped:"})," ","Strict ",e.jsx("span",{className:"font-medium",children:"Paired Sales"})," only counts near-identical comp pairs (GLA ±10%, beds exact, year ±10, etc.)."," ",e.jsx("span",{className:"font-medium",children:"Grouped Paired Sales"})," averages sale prices within size buckets and usually returns a rate when the dataset has no clean pairs."]})]}),(n||i)&&!t.insufficientData&&e.jsxs(dL,{className:"bg-slate-50 border-t border-slate-100 px-3 py-2 flex items-center justify-between gap-2",children:[i?e.jsxs(De,{variant:"ghost",size:"sm",onClick:i,disabled:c,className:"h-7 text-[11px] text-slate-500 hover:text-red-600 hover:bg-red-50","data-testid":`button-no-adjustment-${t.attribute}`,children:[e.jsx(tL,{className:"w-3 h-3 mr-1"}),"No adjustment"]}):e.jsx("span",{}),n&&(()=>{const N=a??t.recommendedKey,x=N?t.results.find(b=>`${b.method}:${b.dataset}`===N):null,y=!!x&&x.qualified;return e.jsxs(De,{size:"sm",onClick:()=>x&&n(x),disabled:!y||c,className:"h-7 text-[11px] bg-emerald-600 hover:bg-emerald-700 text-white","data-testid":`button-lock-apply-${t.attribute}`,title:y?`Lock ${uf[x.method]} · ${af[x.dataset]}`:"Select a qualified method cell to enable Lock & Apply",children:[c?e.jsx(za,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(Hr,{className:"w-3 h-3 mr-1"}),"Lock & Apply"]})})()]})]})},zQ=({result:t,open:a,onClose:s,whyThisRate:r,agreement:n,recommendedKey:i,perAttributeReconciliation:l})=>{if(!t)return null;const c=m=>{switch(m){case"green":return"bg-emerald-500";case"yellow":return"bg-amber-500";case"red":return"bg-red-500";default:return"bg-slate-300"}},d=m=>
46new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(m),p=()=>{if(!t.derivation)return;let m="";if(t.derivation.kind==="paired")m=`Comp A,Comp B,Delta Unit,Delta Price,Per Unit
47`+t.derivation.pairs.map(h=>`${h.compAId},${h.compBId},${h.deltaValue},${h.deltaPrice},${h.perUnit}`).join(`
48`);else if(t.derivation.kind==="grouped")m=`Label,Center Value,Median Price,Count
49`+t.derivation.buckets.map(h=>`${h.label},${h.centerValue},${h.medianPrice},${h.count}`).join(`
50`);else if(t.derivation.kind==="regression"){const h=t.derivation,f=[`Coefficient (Slope),${h.slope}`,`Intercept,${h.intercept??""}`,`R2,${h.rSquared}`,`P-Value,${h.pValue}`,`T-Stat,${h.tStat??""}`,`Std Error,${h.stdError??""}`,`Observations (N),${h.observations}`,`OLS Variable,${h.coefficientLabel??h.coefficientVariable??""}`,`Dropped Variables,"${(h.droppedVariables??[]).join("; ")}"`];if(h.residuals&&h.residuals.length>0){f.push(""),f.push("Comp ID,Address,Sale Price,Predicted,Residual $,Residual %");for(const v of h.residuals)f.push(`${v.compId},"${v.address.replace(/"/g,'""')}",${Math.round(v.salePrice)},${Math.round(v.predicted)},${Math.round(v.residualDollar)},${(v.residualPct*100).toFixed(2)}%`)}m=f.join(`
51`)}navigator.clipboard.writeText(m)},u=()=>{if(!t.derivation)return e.jsx("div",{className:"p-8 text-center text-slate-500",children:"No derivation data available."});switch(t.derivation.kind){case"paired":{const m=t.derivation;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"bg-slate-50 p-3 rounded-lg border flex-1",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase font-bold",children:"Median $/Unit"}),e.jsx("div",{className:"text-xl font-bold text-[#072034]",children:d(m.median)})]}),e.jsxs("div",{className:"bg-slate-50 p-3 rounded-lg border flex-1",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase font-bold",children:"Mean $/Unit"}),e.jsx("div",{className:"text-xl font-bold text-[#072034]",children:d(m.mean)})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Gd,{children:[e.jsx(Hd,{children:e.jsxs(gi,{className:"bg-slate-50",children:[e.jsx(Ds,{className:"text-[11px] font-bold",children:"COMP A"}),e.jsx(Ds,{className:"text-[11px] font-bold",children:"COMP B"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"Δ UNIT"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"Δ PRICE"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"$/UNIT"})]})}),e.jsx(Wd,{children:m.pairs.map((h,f)=>e.jsxs(gi,{className:"text-[12px]",children:[e.jsxs(ws,{className:"font-medium",children:["#",h.compAId]}),e.jsxs(ws,{className:"font-medium",children:["#",h.compBId]}),e.jsx(ws,{className:"text-right",children:h.deltaValue}),e.jsx(ws,{className:"text-right",children:d(h.deltaPrice)}),e.jsx(ws,{className:"text-right font-bold text-blue-700",children:d(h.perUnit)})]},f))})]})}),e.jsxs("div",{className:"text-[11px] text-slate-500 italic",children:["Total pairs analyzed: ",m.pairs.length]})]})}case"grouped":{const m=t.derivation;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-[#072034] text-white p-4 rounded-lg flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-slate-400 uppercase font-bold",children:"Computed Rate"}),e.jsxs("div",{className:"text-2xl font-bold",children:[d(m.perUnit),e.jsxs("span",{className:"text-sm font-normal text-slate-400",children:["/",t.unit]})]})]}),e.jsx(Pl,{className:"w-8 h-8 opacity-20"})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Gd,{children:[e.jsx(Hd,{children:e.jsxs(gi,{className:"bg-slate-50",children:[e.jsx(Ds,{className:"text-[11px] font-bold",children:"BUCKET LABEL"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"CENTER VALUE"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"MEDIAN PRICE"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"SAMPLE"})]})}),e.jsx(Wd,{children:m.buckets.map((h,f)=>e.jsxs(gi,{className:"text-[12px]",children:[e.jsx(ws,{className:"font-bold",children:h.label}),e.jsx(ws,{className:"text-right",children:h.centerValue}),e.jsx(ws,{className:"text-right font-medium",children:d(h.medianPrice)}),e.jsx(ws,{className:"text-right",children:e.jsxs(kt,{variant:"secondary",className:"text-[10px] font-bold",children:["n=",h.count]})})]},f))})]})})]})}case"regression":{const m=t.derivation,h=m.droppedVariables??[],f=m.residuals??[],v=N=>`${(N*100).toFixed(2)}%`;return m.observations===0||f.length===0&&m.rSquared===0&&m.slope===0?e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-6 flex flex-col items-center justify-center text-center space-y-2","data-testid":"regression-empty-state",children:[e.jsx(Ns,{className:"w-6 h-6 text-amber-700"}),e.jsx("div",{className:"text-[13px] font-semibold text-amber-900",children:"Regression did not produce a fit"}),e.jsx("div",{className:"text-[12px] text-amber-800 max-w-md",children:t.reason||`Need at least 15 closed-sale observations to run OLS — the locked pool has ${m.observations}.`}),e.jsx("div",{className:"text-[11px] text-amber-700/90 italic",children:"Per-comp residuals and dropped-variable diagnostics are unavailable until the regression runs."})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 bg-[#072034] text-white p-4 rounded-lg flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] text-slate-400 uppercase font-bold",children:["Coefficient",m.coefficientLabel&&e.jsxs("span",{className:"ml-1 normal-case text-slate-300 font-medium",children:["· ",m.coefficientLabel]})]}),e.jsxs("div",{className:"text-2xl font-bold",children:[d(m.slope),e.jsxs("span",{className:"text-sm font-normal text-slate-400",children:["/",t.unit]})]})]}),e.jsx(W0,{className:"w-8 h-8 opacity-20"})]}),e.jsxs("div",{className:"bg-slate-50 p-3 rounded-lg border space-y-1","data-testid":"stat-observations",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase font-bold",children:"Observations (N)"}),e.jsx("div",{className:"text-lg font-bold text-[#072034]",children:m.observations}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Comps in fit"})]}),e.jsxs("div",{className:"bg-slate-50 p-3 rounded-lg border space-y-1","data-testid":"stat-r-squared",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase font-bold",children:"R-Squared"}),e.jsx("div",{className:"text-lg font-bold text-[#072034]",children:m.rSquared.toFixed(4)}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Goodness of fit"})]}),e.jsxs("div",{className:"bg-slate-50 p-3 rounded-lg border space-y-1","data-testid":"stat-t-stat",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase font-bold",children:"T-Stat"}),e.jsx("div",{className:"text-lg font-bold text-[#072034]",children:m.tStat!=null?m.tStat.toFixed(2):"N/A"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:m.tStat!=null?Math.abs(m.tStat)>
51=1.96?"|t| ≥ 1.96 — robust":"|t| < 1.96 — weak":"Not available"})]}),e.jsxs("div",{className:"bg-slate-50 p-3 rounded-lg border space-y-1","data-testid":"stat-p-value",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase font-bold",children:"P-Value"}),e.jsx("div",{className:"text-lg font-bold text-[#072034]",children:m.pValue.toFixed(4)}),e.jsx("div",{className:"text-[10px] text-slate-400",children:m.pValue<.05?"Statistically Significant":"Not Significant"})]}),e.jsxs("div",{className:"bg-slate-50 p-3 rounded-lg border space-y-1","data-testid":"stat-std-error",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase font-bold",children:"Std Error"}),e.jsx("div",{className:"text-lg font-bold text-[#072034]",children:m.stdError!=null?d(m.stdError):"N/A"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Coefficient noise"})]}),e.jsxs("div",{className:"bg-slate-50 p-3 rounded-lg border space-y-1","data-testid":"stat-intercept",children:[e.jsx("div",{className:"text-[10px] text-slate-500 uppercase font-bold",children:"Intercept"}),e.jsx("div",{className:"text-lg font-bold text-[#072034]",children:m.intercept?d(m.intercept):"N/A"})]})]}),h.length>0&&e.jsxs("div",{className:"flex items-start gap-2 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2","data-testid":"dropped-variables-banner",children:[e.jsx(Ns,{className:"w-4 h-4 text-amber-700 mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-[12px] font-semibold text-amber-900",children:"Dropped variables (zero variance)"}),e.jsx("div",{className:"text-[11px] text-amber-800",children:"These variables had identical values across every comp in the locked pool, so OLS could not estimate a coefficient and dropped them from the model:"}),e.jsx("ul",{className:"text-[11px] text-amber-900 font-medium list-disc list-inside",children:h.map(N=>e.jsx("li",{"data-testid":`dropped-variable-${N}`,children:N},N))})]})]}),e.jsxs("div",{className:"h-40 bg-white rounded-lg border border-slate-200 relative overflow-hidden p-2",children:[e.jsxs("svg",{width:"100%",height:"100%",viewBox:"0 0 100 60",preserveAspectRatio:"none",className:"text-blue-600",children:[e.jsx("line",{x1:"6",y1:"54",x2:"98",y2:"54",stroke:"#cbd5e1",strokeWidth:"0.4"}),e.jsx("line",{x1:"6",y1:"6",x2:"6",y2:"54",stroke:"#cbd5e1",strokeWidth:"0.4"}),(()=>{const N=m.slope,x=m.intercept??0,y=C=>x+N*C,b=0,j=1,T=y(b),O=y(j),E=Math.min(T,O),G=Math.max(T,O)-E||1,U=C=>54-(C-E)/G*44;return e.jsx("line",{x1:6,y1:U(T),x2:98,y2:U(O),stroke:"currentColor",strokeWidth:"1"})})()]}),e.jsxs("div",{className:"absolute bottom-1 right-2 flex items-center gap-1 text-slate-400 text-[10px] font-medium uppercase tracking-wider",children:[e.jsx(of,{className:"w-3 h-3"})," y = ",m.slope.toFixed(2),"·x",m.intercept!=null?` + ${m.intercept.toFixed(0)}`:""]})]}),f.length>0&&e.jsxs(CN,{"data-testid":"residuals-collapsible",children:[e.jsxs(RN,{className:"w-full flex items-center justify-between gap-2 px-3 py-2 bg-slate-50 hover:bg-slate-100 border border-slate-200 rounded-lg text-left group","data-testid":"residuals-toggle",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(l2,{className:"w-4 h-4 text-slate-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[12px] font-semibold text-[#072034]",children:"Per-comp residuals"}),e.jsxs("div",{className:"text-[10px] text-slate-500",children:[f.length," comp",f.length===1?"":"s"," · sorted by largest absolute residual · outliers float to the top"]})]})]}),e.jsx(Rr,{className:"w-4 h-4 text-slate-400 transition-transform group-data-[state=open]:rotate-180"})]}),e.jsx(EN,{children:e.jsx("div",{className:"border border-slate-200 border-t-0 rounded-b-lg overflow-hidden -mt-px",children:e.jsxs(Gd,{children:[e.jsx(Hd,{children:e.jsxs(gi,{className:"bg-slate-50",children:[e.jsx(Ds,{className:"text-[11px] font-bold",children:"COMP"}),e.jsx(Ds,{className:"text-[11px] font-bold",children:"ADDRESS"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"SALE"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"PREDICTED"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"RESIDUAL $"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"RESIDUAL %"})]})}),e.jsx(Wd,{children:f.map(N=>{const y=Math.abs(N.residualPct)>=.1;return e.jsxs(gi,{className:Q("text-[12px]",y&&"bg-amber-50/60"),"data-testid":`residual-row-${N.compId}`,children:[e.jsxs(ws,{className:"font-medium",children:["#",N.compId]}),e.jsx(ws,{className:"text-slate-600 max-w-[180px] truncate",title:N.address,children:N.address||"—"}),e.jsx(ws,{className:"text-right",children:d(N.salePrice)}),e.jsx(ws,{className:"text-right text-slate-500",children:d(N.predicted)}),e.jsx(ws,{className:Q("text-right font-bold",N.residualDollar<0?"text-red-700":"text-emerald-700"),"data-testid":`residual-dollar-${N.compId}`,children:d(N.residualDollar)}),e.jsx(ws,{className:Q("text-right font-bold",y&&"text-amber-800"),"data-testid":`residual-pct-${N.compId}`,children:v(N.residualPct)})]}
51,N.compId)})})]})})})]})]})}case"peeled":return e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg bg-amber-50/50 border-amber-200","data-testid":"peeled-retired-notice",children:[e.jsx("div",{className:"text-[12px] font-bold text-amber-800 uppercase",children:"Method retired"}),e.jsx("p",{className:"text-[12px] text-amber-900 leading-snug",children:"Peeled Paired Sales was retired in algorithm version 2.0. This cell is shown for audit only — re-run the orchestrator to pick a current method (Strict Paired, Grouped Paired, or Regression)."}),e.jsxs("div",{className:"text-[11px] text-slate-600",children:["Stored rate: ",e.jsxs("strong",{children:["$",t.rate.toLocaleString()]})," · n=",t.sampleSize," · ",t.confidence," confidence"]})]})}};return e.jsx(xi,{open:a,onOpenChange:s,children:e.jsxs(bi,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col p-0",children:[e.jsx($i,{className:"px-6 py-4 border-b bg-white",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(si,{className:"text-lg font-bold text-[#072034]",children:["Derivation: ",qd[t.attribute]]}),e.jsxs("div",{className:"text-[12px] text-slate-500 flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-slate-700",children:uf[t.method]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:af[t.dataset]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-slate-50 rounded border",children:[e.jsx("div",{className:Q("w-2 h-2 rounded-full",c(t.confidence))}),e.jsxs("span",{className:"text-[10px] font-bold uppercase text-slate-600",children:[t.confidence," confidence"]})]}),e.jsxs(kt,{className:"bg-blue-50 text-blue-700 hover:bg-blue-50 border-blue-100 text-[10px] font-bold",children:["n=",t.sampleSize]})]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 bg-white",children:[e.jsx("div",{className:"mb-4",children:t.qualified?e.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 bg-emerald-50 px-3 py-2 rounded-md border border-emerald-100",children:[e.jsx(kr,{className:"w-4 h-4"}),e.jsx("span",{className:"text-[12px] font-medium",children:"Qualified for adjustment calculation"})]}):e.jsxs("div",{className:"flex items-center gap-2 text-red-600 bg-red-50 px-3 py-2 rounded-md border border-red-100",children:[e.jsx(nf,{className:"w-4 h-4"}),e.jsxs("span",{className:"text-[12px] font-medium",children:["Disqualified: ",t.reason]})]})}),r?e.jsxs(up,{defaultValue:"methodology",className:"w-full",children:[e.jsxs(pp,{className:"grid grid-cols-2 w-full mb-3","data-testid":"derivation-tabs",children:[e.jsx($n,{value:"methodology","data-testid":"tab-methodology",children:"Methodology"}),e.jsx($n,{value:"why","data-testid":"tab-why-this-rate",children:"Why this rate?"})]}),e.jsx(Bd,{value:"methodology",className:"mt-0",children:u()}),e.jsx(Bd,{value:"why",className:"mt-0",children:e.jsx(qQ,{result:t,whyThisRate:r,agreement:n,recommendedKey:i,perAttributeReconciliation:l})})]}):u()]}),e.jsxs(eb,{className:"px-6 py-4 border-t bg-slate-50 flex items-center justify-between sm:justify-between",children:[e.jsxs(De,{variant:"outline",size:"sm",className:"text-[12px] gap-2",onClick:p,"data-testid":"copy-derivation",children:[e.jsx(jr,{className:"w-4 h-4"}),"Copy to clipboard"]}),e.jsx(De,{onClick:s,size:"sm",className:"bg-[#072034] text-white hover:bg-[#072034]/90 px-6 text-[12px]","data-testid":"close-derivation",children:"Close"})]})]})})},qQ=({result:t,whyThisRate:a,agreement:s,recommendedKey:r,perAttributeReconciliation:n})=>{const i=async()=>{if(n)try{await navigator.clipboard.writeText(n)}catch{}},l=`${t.method}:${t.dataset}`,c=r===l,d=t.derivation?.kind==="regression"?t.derivation.excludedOutliers??[]:[];return e.jsxs("div",{className:"space-y-4","data-testid":"why-this-rate-panel",children:[c?e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-emerald-100 bg-emerald-50 px-3 py-2",children:[e.jsx(kr,{className:"w-4 h-4 text-emerald-600 mt-0.5 shrink-0"}),e.jsx("p",{className:"text-[12px] text-emerald-900 leading-snug",children:"This is the recommended cell — the explanation below describes why the engine picked it."})]}):e.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-slate-200 bg-slate-50 px-3 py-2",children:[e.jsx(of,{className:"w-4 h-4 text-slate-500 mt-0.5 shrink-0"}),e.jsxs("p",{className:"text-[12px] text-slate-700 leading-snug",children:["You're inspecting an alternate cell. The narrative below explains why the ",e.jsx("span",{className:"font-semibold",children:"recommended"})," cell (",r??"—",") was chosen instead."]})]}),e.jsx("div",{className:"rounded-lg border border-slate-200 bg-white p-3",children:e.jsx("p",{className:"text-[13px] font-semibold text-[#072034] leading-snug","data-testid":"why-this-rate-headline",children:a.headline})}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-[11px] font-bold uppercase text-slate-500 tracking-wide mb-2",children:"Why this won"}),e.jsx("ul",{className:"space-y-2",children:a.reasons.map((p,u)=>e.jsxs("li",{className:"flex items-start gap-2 text-[12px] text-slate-700 leading-snug","data-testid":`why-reason-${u}`,children:[e.jsx(kr,{className:"w-3.5 h-3.5 text-emerald-600 mt-0.5 shrink-0"}),e.jsx("span",{children:p})]},u))})]}),s&&s.level!=="none"&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-[11px] font-bold uppercase text-slate-500 tracking-wide mb-2",children:"Method agreement"}),e.jsx("p",{className:"text-[12px] text-slate-700 leading-snug","data-testid":"why-agreement-summary",children:s.summary})]}),n&&e.jsxs("div",{"data-testid":"why-reconciliation-block",children:[e.jsx("h4",{className:"text-[11px] font-bold uppercase text-slate-500 tracking-wide mb-2",children:"Reconciliation paragraph"}),e.jsxs("div",{className:"rounded-md border border-slate-200 bg-slate-50 px-3 py-2 space-y-2",children:[e.jsx("p",{className:"text-[12px] text-slate-700 leading-snug","data-testid":"text-why-reconciliation",children:n}),e.jsxs(De,{variant:"outline",size:"sm",className:"text-[11px] gap-1.5 h-7",onClick:i,"data-testid":"btn-copy-reconciliation-paragraph",children:[e.jsx(jr,{className:"w-3 h-3"}),"Copy this paragraph"]})]})]}),a.caveats&&a.caveats.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-[11px] font-bold uppercase text-amber-700 tracking-wide mb-2",children:"Things to wat
51ch"}),e.jsx("ul",{className:"space-y-1.5",children:a.caveats.map((p,u)=>e.jsxs("li",{className:"flex items-start gap-2 text-[12px] text-amber-900 bg-amber-50 border border-amber-200 rounded px-2.5 py-1.5 leading-snug","data-testid":`why-caveat-${u}`,children:[e.jsx(Ns,{className:"w-3.5 h-3.5 text-amber-700 mt-0.5 shrink-0"}),e.jsx("span",{children:p})]},u))})]}),t.method==="regression"&&d.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-[11px] font-bold uppercase text-slate-500 tracking-wide mb-2",children:["Comps set aside before fitting (",d.length,")"]}),e.jsx("p",{className:"text-[11px] text-slate-500 italic mb-2 leading-snug",children:"These comps were unusually priced relative to the rest of the pool. The engine refit the regression without them so the rate reflects the typical market relationship."}),e.jsx("div",{className:"rounded-lg border border-slate-200 overflow-hidden",children:e.jsxs(Gd,{children:[e.jsx(Hd,{children:e.jsxs(gi,{className:"bg-slate-50",children:[e.jsx(Ds,{className:"text-[11px] font-bold",children:"ADDRESS"}),e.jsx(Ds,{className:"text-[11px] font-bold text-right",children:"SALE PRICE"}),e.jsx(Ds,{className:"text-[11px] font-bold",children:"REASON"})]})}),e.jsx(Wd,{children:d.map(p=>e.jsxs(gi,{className:"text-[12px]","data-testid":`outlier-row-${p.compId}`,children:[e.jsx(ws,{className:"font-medium",children:p.address}),e.jsx(ws,{className:"text-right",children:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(p.salePrice)}),e.jsx(ws,{className:"text-slate-600 leading-snug",children:p.reason})]},p.compId))})]})})]})]})},id=t=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t),YQ=({indicatedValue:t,range:a,locks:s})=>{if(!t&&!a)return e.jsx(ja,{className:"border-slate-200 bg-white","data-testid":"card-indicated-value-unavailable",children:e.jsxs(Ta,{className:"pt-4 pb-4 flex items-start gap-3",children:[e.jsx(on,{className:"w-5 h-5 text-slate-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-900",children:"Indicated value not yet available"}),e.jsx("p",{className:"text-[12px] text-slate-600 leading-snug",children:"Lock at least one adjustment and run the multi-method engine to see the value implied by your locks."})]})]})});if(!t)return e.jsx(ja,{className:"border-slate-200 bg-white","data-testid":"card-indicated-value-no-locks",children:e.jsxs(Ta,{className:"pt-4 pb-4 flex items-start gap-3",children:[e.jsx(on,{className:"w-5 h-5 text-slate-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-900",children:"No locked adjustments yet"}),e.jsx("p",{className:"text-[12px] text-slate-600 leading-snug",children:"Lock at least one attribute to see the indicated value implied by your locks."}),a&&e.jsxs("p",{className:"text-[12px] text-slate-700 leading-snug","data-testid":"text-range-only",children:["Market-supported range: ",e.jsxs("span",{className:"font-semibold",children:[id(a.low)," – ",id(a.high)]})," ","(point estimate ",id(a.point),")."]})]})]})});if(!a)return e.jsx(ja,{className:"border-slate-200 bg-white","data-testid":"card-indicated-value-no-range",children:e.jsxs(Ta,{className:"pt-4 pb-4 flex items-start gap-3",children:[e.jsx(on,{className:"w-5 h-5 text-slate-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-sm font-semibold text-slate-900",children:["Indicated value: ",e.jsx("span",{"data-testid":"text-indicated-value",children:id(t.median)})]}),e.jsxs("p",{className:"text-[12px] text-slate-600 leading-snug",children:["Median of ",t.perComp.length," comp",t.perComp.length===1?"":"s"," after applying your locked rates. No market-supported range available — regression did not qualify on either dataset (need R² ≥ 0.6 and at least 30 comps)."]})]})]})});if(t.median>=a.low&&t.median<=a.high)return e.jsx(ja,{className:"border-emerald-200 bg-emerald-50","data-testid":"card-indicated-value-within",children:e.jsxs(Ta,{className:"pt-4 pb-4 flex items-start gap-3",children:[e.jsx(kr,{className:"w-5 h-5 text-emerald-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-semibold text-emerald-900",children:"Indicated value sits inside the market-supported range"}),e.jsxs("p",{className:"text-[12px] text-emerald-900 leading-snug",children:["Your locked adjustments imply ",e.jsx("span",{className:"font-semibold","data-testid":"text-indicated-value",children:id(t.median)}),","," ","which falls inside the regression-supported range of"," ",e.jsxs("span",{className:"font-semibold","data-testid":"text-range",children:[id(a.low)," – ",id(a.high)]})," ","(point estimate ",id(a.point),")."]}),e.jsx("p",{className:"text-[11px] text-emerald-800 italic leading-snug","data-testid":"text-range-basis",children:a.basis})]})]})});const n=[];for(const c of s){if(c.recommendedRate==null||c.recommendedRate===0)continue;const d=Math.abs((c.lockedRate-c.recommendedRate)/c.recommendedRate);d<1e-4||n.push({attribute:c.attributeKey,locked:c.lockedRate,recommended:c.recommendedRate,pctDelta:d})}n.sort((c,d)=>d.pctDelta-c.pctDelta);const i=n.slice(0,2),l=t.median<a.low?"below":"above";return e.jsx(ja,{className:"border-amber-300 bg-amber-50","data-testid":"card-indicated-value-outside",children:e.jsxs(Ta,{className:"pt-4 pb-4 flex items-start gap-3",children:[e.jsx(Ns,{className:"w-5 h-5 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-semibold text-amber-900",children:["Indicated value falls ",l," the market-supported range"]}),e.jsxs("p",{className:"text-[12px] text-amber-900 leading-snug",children:["Your locked adjustments imply ",e.jsx("span",{className:"font-semibold","data-testid":"text-indicated-value",children:id(t.median)}),","," ","which sits ",l," the regression-supported range of"," ",e.jsxs("span",{className:"font-semibold","data-testid":"text-range",children:[id(a.low)," – ",id(a.high)]})," ","(point estimate ",id(a.point),")."]}),i.length>0&&e.jsxs("div",{className:"space-y-1","data-testid":"list-divergences",children:[e.jsx("p",{className:"text-[11px] font-semibold text-amber-800 uppercase tracking-wide",children:"Largest deviations from the recommended rate"}),e.jsx("ul",{className:"space-y-1",children:i.map(c=>e.jsxs("li",{className:"text-[12px] text-amber-900 leading-snug","data-testid":`row-divergence-${c.attribute}`,children:[e.jsx("span",{className:"font-semibold",children:qd[c.attribute]}),":"," ","locked at ",id(c.locked)," vs. recommended ",id(c.recommended)," ","(",(c.pctDelta*100).toFixed(0),"% off)."]},c.attribute))})]}),e.jsx("p",{className:"text-[11px] text-amber-800 italic leading-snug","data-testid":"text-range-basis",children:a.basis})]})]})})},GQ="mm-reconciliation-auto-expanded:",HQ=({assignmentId:t,draft:a,totalLockableAttributes:s,lockedAttributesCount:r})=>{const{toast:n}=hc(),i=o.useMemo(()=>(a?.paragraphs??[]).join(`
52
53`),[a]),[l,c]=o.useState(i),[d,p]=o.useState(!1);o.useEffect(()=>{d||c(i)},[i,d]);const u=`${GQ}${t}`,m=o.useMemo(()=>!(s===0||r/s<.8||typeof window>"u"||window.sessionStorage.getItem(u)==="1"),[s,r,u]),[h,f]=o.useState(m);o.useEffect(()=>{m&&typeof window<"u"&&window.sessionStorage.setItem(u,"1")},[m,u]);const v=Yd({mutationFn:async y=>(await Qo("PUT",`/api/multi-method/locks/${encodeURIComponent(t)}/narrative`,{editedNarrative:y})).json(),onSuccess:y=>{n({title:"Reconciliation sent to report",description:`Updated ${y.updated} locked attribute${y.updated===1?"":"s"}.`})},onError:y=>{n({title:"Could not send reconciliation",description:y.message,variant:"destructive"})}}),S=async()=>{try{await navigator.clipboard.writeText(l),n({title:"Reconciliation copied",description:"Paste into your report narrative."})}catch{n({title:"Copy failed",description:"Your browser blocked clipboard access.",variant:"destructive"})}},N=()=>{if(!l.trim()){n({title:"Nothing to send",description:"The reconciliation draft is empty.",variant:"destructive"});return}v.mutate(l.trim())},x=(a?.paragraphs?.length??0)>0;return e.jsx(ja,{className:"border-slate-200 bg-white","data-testid":"card-reconciliation-draft",children:e.jsxs(CN,{open:h,onOpenChange:f,children:[e.jsx(RN,{asChild:!0,children:e.jsxs("button",{type:"button",className:"w-full flex items-center justify-between px-4 py-3 hover:bg-slate-50 rounded-t-lg","data-testid":"btn-reconciliation-toggle",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gn,{className:"w-4 h-4 text-[#072034]"}),e.jsx("span",{className:"text-sm font-semibold text-[#072034]",children:"Reconciliation draft"}),!x&&e.jsx("span",{className:"text-[11px] text-slate-500",children:"(lock at least one attribute to generate)"})]}),e.jsx(Rr,{className:`w-4 h-4 text-slate-500 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(EN,{children:e.jsx(Ta,{className:"pt-0 pb-4 space-y-3",children:x?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-[11px] text-slate-500 leading-snug",children:["Auto-drafted from the engine's signals. Edit freely — your changes only persist when you press ",e.jsx("span",{className:"font-semibold",children:"Send to report"}),"."]}),e.jsx(yi,{value:l,onChange:y=>{p(!0),c(y.target.value)},className:"text-[12px] leading-snug min-h-[160px] font-serif","data-testid":"textarea-reconciliation-draft",placeholder:"Reconciliation paragraph will appear here once you lock at least one attribute."}),e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsxs(De,{size:"sm",variant:"outline",onClick:S,"data-testid":"btn-reconciliation-copy",children:[e.jsx(jr,{className:"w-3.5 h-3.5 mr-1.5"}),"Copy"]}),e.jsxs(De,{size:"sm",onClick:N,disabled:v.isPending,className:"bg-[#072034] text-white hover:bg-[#072034]/90","data-testid":"btn-reconciliation-send",children:[v.isPending?e.jsx(za,{className:"w-3.5 h-3.5 mr-1.5 animate-spin"}):e.jsx(gI,{className:"w-3.5 h-3.5 mr-1.5"}),"Send to report"]})]})]}):e.jsx("p",{className:"text-[12px] text-slate-600 leading-snug",children:"The reconciliation draft is generated once you have locked at least one attribute. Lock & Apply your selections, then expand this panel."})})})]})})},W1={gla:"gla",bedrooms:"aboveGrade",bathrooms:"aboveGrade",garage:"garageCarport",basement:"basement",site:"site",condition:"qualityCondition",quality:"qualityCondition",location:"location"},iN=t=>{if(!t)return null;const a=String(t).match(/(\d+)/);return a?parseInt(a[1],10):null},K1=(t,a)=>{switch(t){case"gla":return a.gla??null;case"bedrooms":return a.bedrooms??null;case"bathrooms":return a.bathrooms??null;case"garage":return a.garageSpaces??0;case"basement":return a.basementSqft??0;case"site":return a.lotSize??null;case"condition":return iN(a.condition);case"quality":return iN(a.quality);case"location":return a.elsScore??null}},Q1=(t,a)=>{switch(t){case"gla":return a.gla??null;case"bedrooms":return a.bedrooms??null;case"bathrooms":return a.bathrooms??null;case"garage":return a.garageSpaces??0;case"basement":return a.basementSqft??0;case"site":return a.lotSize??null;
53case"condition":return iN(a.condition);case"quality":return iN(a.quality);case"location":return a.elsScore??null}},WQ=({assignmentId:t,subject:a,submarketComps:s,broadComps:r,concessionThresholdPct:n,timeAdjustedPrices:i,currentAdjustments:l,onLockApplied:c,onComplianceComputed:d,submarketFunnel:p,marketFunnel:u})=>{const{toast:m}=hc(),[h,f]=o.useState({}),v=Vr({queryKey:["/api/multi-method/skips",t],enabled:!!t,retry:!1}),S=o.useMemo(()=>{const ye=new Set;for(const de of v.data?.skips??[])ye.add(de.attributeKey);return ye},[v.data]),[N,x]=o.useState(null),y=o.useMemo(()=>["/api/multi-method/skips",t],[t]),b=Yd({mutationFn:async ye=>(await Qo("POST","/api/multi-method/skips",{assignmentId:t,attributeKey:ye})).json(),onMutate:async ye=>{await fi.cancelQueries({queryKey:y});const de=fi.getQueryData(y),ge={skips:[...(de?.skips??[]).filter(Be=>Be.attributeKey!==ye),{id:`optimistic-${ye}`,attributeKey:ye}]};return fi.setQueryData(y,ge),{previous:de}},onError:(ye,de,ge)=>{ge?.previous&&fi.setQueryData(y,ge.previous),m({title:'Could not save "No adjustment"',description:ye.message,variant:"destructive"})},onSettled:()=>{fi.invalidateQueries({queryKey:y})}}),j=Yd({mutationFn:async ye=>(await Qo("DELETE",`/api/multi-method/skips/${encodeURIComponent(t)}/${encodeURIComponent(ye)}`)).json(),onMutate:async ye=>{await fi.cancelQueries({queryKey:y});const de=fi.getQueryData(y),ge={skips:(de?.skips??[]).filter(Be=>Be.attributeKey!==ye)};return fi.setQueryData(y,ge),{previous:de}},onError:(ye,de,ge)=>{ge?.previous&&fi.setQueryData(y,ge.previous),m({title:'Could not clear "No adjustment"',description:ye.message,variant:"destructive"})},onSettled:()=>{fi.invalidateQueries({queryKey:y})}}),T=ye=>{S.has(ye)&&j.mutate(ye)},O=Yd({mutationFn:async ye=>(await Qo("POST","/api/multi-method/run",ye)).json()}),E=Vr({queryKey:["/api/multi-method/locks",t],enabled:!!t,retry:!1}),R=o.useMemo(()=>{const ye={},de=E.data?.locks??[];for(const ge of de)ye[ge.attributeKey]=`${ge.method}:${ge.dataset}`;return ye},[E.data]),G=o.useMemo(()=>(E.data?.locks??[]).map(de=>({attributeKey:de.attributeKey,lockedRate:typeof de.lockedRate=="string"?Number(de.lockedRate):de.lockedRate,rateUnit:de.rateUnit,method:de.method,dataset:de.dataset})),[E.data]),U=o.useMemo(()=>({assignmentId:t,subject:a,submarket:s,broad:r,options:{...n!=null?{concessionThresholdPct:n}:{},...Object.keys(i).length>0?{timeAdjustedPrices:i}:{}},...G.length>0?{locks:G}:{}}),[t,a,s,r,n,i,G]),[C,F]=o.useState(!1);o.useEffect(()=>{C||E.data&&(Object.keys(R).length>0&&f(ye=>({...R,...ye})),F(!0))},[E.data,R,C]),o.useEffect(()=>{s.length===0&&r.length===0||O.mutate(U)},[U]);const A=O.data;o.useEffect(()=>{if(!A)return;const ye={};for(const de of A.attributes)de.recommendedKey&&(ye[de.attribute]=de.recommendedKey);f(de=>({...ye,...R,...de}))},[A,R]);const M=(ye,de)=>ye.results.find(ge=>`${ge.method}:${ge.dataset}`===de),[B,oe]=o.useState(null),[ae,D]=o.useState(!1),[_,$]=o.useState(null),[z,V]=o.useState(null),[le,W]=o.useState(null),[me,Z]=o.useState(null),[pe,se]=o.useState(!1),fe=async()=>{if(!(!le||!z)){se(!0),Z(null);try{const de=await(await Qo("POST","/api/multi-method/compliance",{comps:le,adjustments:z,subject:a})).json();oe(de),D(!1),!de.acknowledgmentRequired&&_?(c(_),$(null),V(null),W(null),m({title:"Adjustments applied",description:`${_.length} comp(s) updated after compliance retry.`})):m({title:"Compliance retry succeeded",description:"Soft caps still exceeded — acknowledge to apply."})}catch(ye){const de=ye instanceof Error?ye.message:"Unknown error";Z(de),m({title:"Compliance retry failed",description:de,variant:"destructive"})}finally{se(!1)}}};o.useEffect(()=>{d?.(B)},[B,d]);const ue=Yd({mutationFn:async()=>{if(!A)throw new Error("No orchestrator response");const ye=A.attributes.filter(ge=>!ge.insufficientData).filter(ge=>!S.has(ge.attribute)).map(ge=>{const Be=h[ge.attribute]??ge.recommendedKey;if(!Be)return null;const He=M(ge,Be);if(!He||!He.qualified)return null;const Ie=ge.recommendedKey?M(ge,ge.recommendedKey):void 0;return{attributeKey:ge.attribute,lockedRate:He.rate,rateUnit:He.unit,method:He.method,dataset:He.dataset,sampleSize:He.sampleSize,confidence:He.confidence,alternatives:ge.results,recommendation:Ie??null,wasRecommendationFollowed:Be===ge.recommendedKey}}
53).filter(Boolean);return(await Qo("POST","/api/multi-method/lock",{assignmentId:t,runId:A.runId,concessionThresholdPct:n??void 0,timeAdjustmentApplied:Object.keys(i).length>0,locks:ye})).json()},onSuccess:async()=>{if(!A)return;const ye=new Set,de=[];for(const Pe of[...s,...r])if(!ye.has(Pe.id)&&(ye.add(Pe.id),de.push(Pe),de.length>=50))break;const ge=new Map;for(const Pe of A.attributes){if(Pe.insufficientData)continue;const We=h[Pe.attribute]??Pe.recommendedKey;if(!We)continue;const Re=M(Pe,We);if(!Re||!Re.qualified)continue;const ne=Re.rate,Me=K1(Pe.attribute,a);if(Me==null)continue;const lt=W1[Pe.attribute];for(const Tt of de){const je=Q1(Pe.attribute,Tt);if(je==null)continue;const Le=Math.round(ne*(Me-je));if(Le===0)continue;ge.has(Tt.id)||ge.set(Tt.id,{});const ut=ge.get(Tt.id);ut[lt]=(ut[lt]??0)+Le}}const Be=Array.from(ge.entries()).map(([Pe,We])=>({compId:Pe,adjustments:We})),He={};for(const Pe of Be)He[Pe.compId]=Pe.adjustments;const Ie=de.map(Pe=>({id:Pe.id,salePrice:Pe.salePrice}));W(Ie),V(He);let ce;try{ce=await(await Qo("POST","/api/multi-method/compliance",{comps:Ie,adjustments:He,subject:a})).json()}catch(Pe){const We=Pe instanceof Error?Pe.message:"Unknown error";$(Be),oe(null),Z(We),m({title:"Compliance check failed",description:`Adjustments are locked but NOT applied. ${We}. Retry the check or acknowledge to apply manually.`,variant:"destructive"});return}if(oe(ce),Z(null),D(!1),ce.acknowledgmentRequired){$(Be),m({title:"Adjustments locked — review compliance",description:"Fannie soft caps exceeded. Acknowledge below the grid to apply."});return}c(Be),$(null),V(null),W(null),m({title:"Adjustments locked",description:`${Be.length} comp(s) updated with multi-method adjustments.`})},onError:ye=>{m({title:"Lock failed",description:ye.message,variant:"destructive"})}});if(O.isPending)return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-[400px] p-8 bg-slate-50",children:[e.jsx(za,{className:"w-8 h-8 text-[#072034] animate-spin"}),e.jsx("p",{className:"text-sm text-slate-600 mt-3",children:"Running paired sales, grouped sales & regression on submarket and broad-market datasets…"})]});if(O.isError)return e.jsx("div",{className:"p-6 bg-slate-50 min-h-full","data-testid":"multi-method-error",children:e.jsx(ja,{className:"border-red-200 bg-red-50",children:e.jsxs(Ta,{className:"pt-6 flex items-start gap-3",children:[e.jsx(Di,{className:"w-5 h-5 text-red-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-red-900",children:"Multi-method run failed"}),e.jsx("p",{className:"text-xs text-red-700 mt-1",children:O.error.message}),e.jsx(De,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>O.mutate(U),"data-testid":"btn-mm-retry",children:"Retry"})]})]})})});if(!A)return e.jsx("div",{className:"p-6 bg-slate-50 min-h-full",children:e.jsx(ja,{className:"border-slate-200 bg-white",children:e.jsx(Ta,{className:"pt-6",children:e.jsx("p",{className:"text-sm text-slate-600",children:"No data available yet."})})})});const be=A.attributes.filter(ye=>{if(S.has(ye.attribute))return!1;const de=h[ye.attribute]??ye.recommendedKey;return de?!!M(ye,de)?.qualified:!1}).length,H=[];if(l&&(E.data?.locks?.length??0)>0){const ye=[...s,...r],de=new Map;for(const ge of E.data.locks){const Be=K1(ge.attributeKey,a);if(Be==null)continue;const He=W1[ge.attributeKey],Ie=typeof ge.lockedRate=="string"?Number(ge.lockedRate):ge.lockedRate;for(const ce of ye){const Pe=Q1(ge.attributeKey,ce);if(Pe==null)continue;const We=Math.round(Ie*(Be-Pe));de.has(ce.id)||de.set(ce.id,{});const Re=de.get(ce.id);Re[He]=(Re[He]??0)+We}}for(const[ge,Be]of de.entries()){const He=l[ge]??{};for(const Ie of Object.keys(Be)){const ce=He[Ie]??0,Pe=Be[Ie];Math.abs(ce-Pe)>=1&&H.push({compId:ge,field:Ie,expected:Pe,actual:ce})}}}return e.jsxs("div",{className:"p-6 bg-slate-50 min-h-full space-y-4","data-testid":"multi-method-step",children:[e.jsx(_Q,{subjectFit:A.subjectFit,timeScrubValidation:A.timeScrubValidation}),e.jsx(MQ,{headline:A.headline}),A.concessions&&e.jsx(ja,{className:"border-slate-200 bg-white","data-testid":"card-concession-summary",children:e.jsx(Ta,{className:"pt-4 pb-4",children:e.jsxs("p",{className:"text-[12px] text-slate-600",children:[e.jsx("span",{className:"font-semibold text-[#072034]",children:"Concessions applied:"})," ",A.concessions.prevalencePct.toFixed(1),"% of comps had concessions averaging"," ",A.concessions.averagePct.toFixed(1),"% of price."," ",n!=null?`Threshold ${n}% used to net comps before adjustments.`:"No threshold applied."]})})}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:A.attributes.map(ye=>{const de=S.has(ye.attribute);return e.jsx(BQ,{attribute:ye,submarketFunnel:p,marketFunnel:u,selectedKey:h[ye.attribute]??ye.recommendedKey,onSelect:ge=>{T(ye.attribute),f(Be=>({...Be,[ye.attribute]:`${ge.method}:${ge.dataset}`}))},onShowDerivation:ge=>x(ge),onLockApply:ge=>{f(Be=>({...Be,[ye.attribute]:`${ge.method}:${ge.dataset}`})),T(ye.attribute),ue.mutate()},onNoAdjustment:()=>{de?(j.mutate(ye.attribute),m({title:`${ye.attribute} adjustment re-enabled`,description:"Will lock at the selected rate on the next Lock & Apply."})):(b.mutate(ye.attribute),m({title:`${ye.attribute} marked "no adjustment"`,description:"This attribute will be excluded from the next Lock & Apply (saved across sessions)."}))},isLocking:ue.isPending},ye.attribute)})}),e.jsx(YQ,{indicatedValue:A.indicatedValueFromLocks??null,range:A.marketSupportedRange??null,locks:(E.data?.locks??[]).map(ye=>{const de=A.attributes.find(Be=>Be.attribute===ye.attributeKey);let ge;if(de?.recommendedKey){const Be=de.results.find(He=>`${He.method}:${He.dataset}`===de.recommendedKey);Be&&(ge=Be.rate)}return{attributeKey:ye.attributeKey,lockedRate:typeof ye.lockedRate=="string"?Number(ye.lockedRate):ye.lockedRate,rateUnit:ye.rateUnit,method:ye.method,dataset:ye.dataset,recommendedRate:ge,wasRecommendationFollowed:ge!=null?Math.abs((typeof ye.lockedRate=="string"?Number(ye.lockedRate):ye.lockedRate)-ge)<.5:void 0}})}),e.jsx(HQ,{assignmentId:t,draft:A.reconciliationDraft,totalLockableAttributes:A.attributes.filter(ye=>!ye.insufficientData).length,lockedAttributesCount:E.data?.locks?.length??0}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsxs(De,{onClick:()=>ue.mutate(),disabled:ue.isPending||be===0,className:"bg-emerald-600 hover:bg-emerald-700 text-white flex items-center gap-2 min-w-[200px]","data-testid":"btn-mm-lock-apply",children:[ue.isPending?e.jsx(za,{className:"w-4 h-4 animate-spin"}):e.jsx(Hr,{className:"w-4 h-4"}),"Lock & Apply ",be," Attribute",be===1?"":"s"]})}),H.length>0&&e.jsx(ja,{className:"border-slate-300 bg-white","data-testid":"card-manual-overrides",children:e.jsxs(Ta,{className:"pt-4 pb-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ZR,{className:"w-4 h-4 text-amber-600"}),e.jsxs("p",{className:"text-sm font-semibold text-slate-900",children:["Manual overrides since lock (",H.length,")"]})]}),e.jsx("p",{className:"text-[12px] text-slate-600",children:"The grid no longer matches the locked rates for these adjustments. The lock-and-apply audit trail captures the locked value; the appraiser is responsible for justifying the override."}),e.jsx("div",{className:"max-h-40 overflow-y-auto border border-slate-200 rounded",children:e.jsxs("table",{className:"w-full text-[11px]","data-testid":"table-manual-overrides",children:[e.jsx("thead",{className:"bg-slate-50 sticky top-0",children:e.jsxs("tr",{className:"text-left text-slate-600",children:[e.jsx("th",{className:"px-2 py-1",children:"Comp"}),e.jsx("th",{className:"px-2 py-1",children:"Field"}),e.jsx("th",{className:"px-2 py-1 text-right",children:"Locked"}),e.jsx("th",{className:"px-2 py-1 text-right",children:"Grid"}),e.jsx("th",{className:"px-2 py-1 text-right",children:"Δ"})]})}),e.jsx("tbody",{children:H.slice(0,20).map((ye,de)=>e.jsxs("tr",{className:"border-t border-slate-100","data-testid":`row-override-${ye.compId}-${ye.field}`,children:[e.jsx("td",{className:"px-2 py-1 font-mono text-slate-700",children:ye.compId.slice(0,8)}),e.jsx("td",{className:"px-2 py-1",children:ye.field}),e.jsxs("td",{className:"px-2 py-1 text-right",children:["$",ye.expected.toLocaleStr
53ing()]}),e.jsxs("td",{className:"px-2 py-1 text-right",children:["$",ye.actual.toLocaleString()]}),e.jsxs("td",{className:"px-2 py-1 text-right text-amber-700",children:[ye.actual-ye.expected>0?"+":"","$",(ye.actual-ye.expected).toLocaleString()]})]},`${ye.compId}-${ye.field}-${de}`))})]})}),H.length>20&&e.jsxs("p",{className:"text-[10px] text-slate-500",children:["Showing first 20 of ",H.length," overrides."]})]})}),_&&(B?.acknowledgmentRequired||me)&&e.jsx(ja,{className:me?"border-red-300 bg-red-50":"border-amber-300 bg-amber-50","data-testid":"card-compliance-pending",children:e.jsxs(Ta,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ZR,{className:`w-5 h-5 mt-0.5 shrink-0 ${me?"text-red-600":"text-amber-600"}`}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:`text-sm font-semibold ${me?"text-red-900":"text-amber-900"}`,children:me?"Compliance check failed — apply blocked":"Fannie soft caps exceeded"}),e.jsx("p",{className:`text-xs ${me?"text-red-800":"text-amber-800"}`,children:me?`Adjustments are locked but were not applied because the Fannie compliance check could not run (${me}). Retry the check, or acknowledge to apply manually without compliance verification.`:"Review the per-comp net % / gross % bars in the Compliance panel below the Sales Comparison Grid. Tick the acknowledgment there, then return here to apply."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"checkbox",id:"mm-acknowledge-inline",checked:ae,onChange:ye=>D(ye.target.checked),className:"h-4 w-4","data-testid":"checkbox-mm-acknowledge"}),e.jsx("label",{htmlFor:"mm-acknowledge-inline",className:`text-xs ${me?"text-red-900":"text-amber-900"}`,children:me?"I accept that compliance was not verified and want to apply the adjustments anyway.":"I have reviewed the compliance panel and accept the exceedances."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[me&&e.jsxs(De,{variant:"outline",onClick:fe,disabled:pe,className:"min-w-[160px]","data-testid":"btn-mm-retry-compliance",children:[pe?e.jsx(za,{className:"w-4 h-4 animate-spin mr-2"}):null,"Retry compliance"]}),e.jsx(De,{onClick:()=>{if(!_)return;c(_);const ye=_.length;$(null),V(null),W(null),m({title:"Adjustments applied",description:`${ye} comp(s) updated after ${me?"manual override":"compliance acknowledgment"}.`})},disabled:!ae,className:"bg-emerald-600 hover:bg-emerald-700 text-white min-w-[200px]","data-testid":"btn-mm-apply-acknowledged",children:"Apply to Grid"})]})]})}),e.jsx(zQ,{result:N,whyThisRate:N?A.attributes.find(ye=>ye.attribute===N.attribute)?.whyThisRate:void 0,agreement:N?A.attributes.find(ye=>ye.attribute===N.attribute)?.agreement:void 0,recommendedKey:N?A.attributes.find(ye=>ye.attribute===N.attribute)?.recommendedKey:void 0,perAttributeReconciliation:N?A.reconciliationDraft?.perAttribute?.[N.attribute]:void 0,open:N!==null,onClose:()=>x(null)})]})},Z1=[{id:1,label:"Concessions"},{id:2,label:"Time"},{id:3,label:"Multi-Method"}],wM=({open:t,onOpenChange:a,assignmentId:s,subject:r,submarketComps:n,broadComps:i,marketLocked:l,subMarketLocked:c,locksHydrating:d=!1,currentAdjustments:p,onApplyAdjustments:u,onComplianceComputed:m,embeddedTimeVault:h,submarketFunnel:f,marketFunnel:v})=>{const[S,N]=o.useState(1),[x,y]=o.useState(!1),[b,j]=o.useState(null),[T,O]=o.useState({}),E=l||c,R=!!s&&r!==null&&r!==void 0,G=o.useRef(null);o.useEffect(()=>{if(!t)return;const M=B=>{B.key==="Escape"&&(B.stopPropagation(),a(!1))};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[t,a]),o.useEffect(()=>{if(!t)return;const M=requestAnimationFrame(()=>{G.current&&G.current.focus({preventScroll:!0})});return()=>cancelAnimationFrame(M)},[t]);const U=()=>{S<3&&N(M=>M+1)},C=()=>{S>1&&N(M=>M-1)},F=()=>{if(!E)return d?e.jsx("div",{className:"flex flex-col items-center justify-center h-full p-8 bg-slate-50","data-testid":"state-mm-locks-hydrating",children:e.jsx(ja,{className:"max-w-md border-slate-200 bg-white",children:e.jsxs(Ta,{className:"pt-6 text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center",children:e.jsx(za,{className:"w-6 h-6 text-slate-500 animate-spin"})}),e.jsx("p",{className:"text-sm font-medium text-slate-700",children:"Loading locked Market and Sub-Market datasets…"})]})})}):e.jsx("div",{className:"flex flex-col items-center justify-center h-full p-8 bg-slate-50",children:e.jsx(ja,{className:"max-w-md border-amber-200 bg-amber-50",children:e.jsxs(Ta,{className:"pt-6 text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-12 h-12 bg-amber-100 rounded-full flex items-center justify-center",children:e.jsx(Ns,{className:"w-6 h-6 text-amber-600"})}),e.jsx("p",{className:"text-sm font-medium text-amber-900",children:"Lock at least one dataset (M
53arket or Sub-Market) on Property Lab before running multi-method adjustments."})]})})});if(!R)return e.jsx("div",{className:"flex flex-col items-center justify-center h-full p-8 bg-slate-50","data-testid":"state-mm-awaiting-prereqs",children:e.jsx(ja,{className:"max-w-md border-slate-200 bg-white",children:e.jsxs(Ta,{className:"pt-6 text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center",children:e.jsx(Ns,{className:"w-6 h-6 text-slate-500"})}),e.jsx("p",{className:"text-sm font-medium text-slate-700",children:"Waiting for the verified subject and assignment to finish loading…"}),e.jsx("p",{className:"text-xs text-slate-500",children:"If this persists, return to the Subject step and confirm the property is verified before running adjustments."})]})})});switch(S){case 1:return e.jsx(OQ,{submarketComps:n,broadComps:i,subject:r,onContinue:M=>{j(M),N(2)},onSkip:()=>{j(null),N(2)}});case 2:return e.jsx(LQ,{assignmentId:s,subject:r,submarketComps:n,broadComps:i,embeddedTimeVault:h,onContinue:M=>{O(M),N(3)},onSkip:()=>N(3)});case 3:return e.jsx(WQ,{assignmentId:s,subject:r,submarketComps:n,broadComps:i,concessionThresholdPct:b,timeAdjustedPrices:T,currentAdjustments:p,onComplianceComputed:m,onLockApplied:M=>{u(M)},submarketFunnel:f,marketFunnel:v});default:return null}};if(!t||typeof document>"u")return null;const A=e.jsxs("div",{"data-testid":"mm-drawer-portal-root",role:"presentation",className:"pointer-events-none",children:[e.jsx("div",{"data-testid":"mm-drawer-overlay",onClick:()=>a(!1),className:"fixed inset-0 bg-black/50 pointer-events-auto",style:{zIndex:999}}),e.jsxs("div",{ref:G,role:"dialog","aria-modal":"true","aria-label":"Multi-Method Adjustments",tabIndex:-1,"data-testid":"mm-drawer-panel",className:Q("fixed inset-y-0 right-0 bg-background shadow-2xl flex flex-col border-l border-slate-200 outline-none pointer-events-auto",x?"left-0 w-screen":"w-[min(960px,90vw)]"),style:{zIndex:1e3},children:[e.jsxs("div",{className:"h-[56px] bg-[#072034] flex items-center justify-between px-4 shrink-0 shadow-md",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("h2",{className:"text-white text-base font-semibold","data-testid":"text-mm-drawer-title",children:"Multi-Method Adjustments"}),e.jsx("div",{className:"hidden md:flex items-center gap-1",children:Z1.map((M,B)=>{const oe=S===M.id,ae=S>M.id;return e.jsxs(Mn.Fragment,{children:[e.jsx("div",{className:Q("px-3 py-1 rounded-full text-[12px] font-medium flex items-center gap-2",oe?"bg-[#C5A572] text-[#072034]":ae?"bg-[#D0FAE5] text-[#065F46]":"text-slate-400"),"data-testid":`btn-mm-step-${M.id}`,children:e.jsxs("span",{children:[M.id,". ",M.label]})}),B<Z1.length-1&&e.jsx("div",{className:"w-2 h-px bg-slate-700"})]},M.id)})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"text-[12px] text-slate-400 mr-2",children:["Step ",S," of 3"]}),e.jsx("button",{type:"button",onClick:()=>y(!x),className:"p-2 text-slate-400 hover:text-white rounded-md transition-colors","data-testid":"btn-mm-expand",children:x?e.jsx(eL,{size:18}):e.jsx(ub,{size:18})}),e.jsx("button",{type:"button",onClick:()=>a(!1),className:"p-2 text-slate-400 hover:text-white rounded-md transition-colors","data-testid":"btn-mm-close","aria-label":"Close Multi-Method Adjustments",children:e.jsx(ur,{size:20})})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:F()}),e.jsxs("div",{className:"h-[64px] border-t bg-white px-6 flex items-center justify-between shrink-0",children:[e.jsx("div",{children:e.jsx(De,{variant:"outline",onClick:()=>a(!1),className:"text-slate-600","data-testid":"btn-mm-cancel",children:"Cancel"})}),e.jsx("div",{className:"flex items-center gap-3",children:E&&R&&e.jsxs(e.Fragment,{children:[S>1&&e.jsxs(De,{variant:"ghost",onClick:C,className:"text-slate-600","data-testid":"btn-mm-back",children:[e.jsx(oy,{className:"w-4 h-4 mr-1"})," Back"]}),S<3&&e.jsxs(De,{onClick:U,className:"bg-emerald-600 hover:bg-emerald-700 text-white min-w-[100px]","data-testid":"btn-mm-next",children:["Next ",e.jsx(fo,{className:"w-4 h-4 ml-1"})]})]})})]})]})]});return Wp.createPortal(A,document.body)},J1=7,KQ={green:"●●●",yellow:"●●○",red:"●○○"},QQ={green:"text-emerald-500",yellow:"text-amber-500",red:"text-red-500"},ZQ={adjust:"DRIVER",caution:"MINOR","do-not-adjust":"NO SUPPORT"},JQ={adjust:"bg-[#D0FAE5] text-[#007A55] border-emerald-200",caution:"bg-[#FEF3C7] text-[#92400E] border-amber-200","do-not-adjust":"bg-[#FEE2E2] text-[#B91C1C] border-red-200"},X1={adjust:"Driver — carries the bulk of the adjustment weight; this attribute materially affects value.",caution:"Minor — small effect; adjust only if defensible.","do-not-adjust":"No support — data does not justify a defensible adjustment."};function eO(t,a){const s=t==="green"?"high":t==="yellow"?"medium":"low";if(a==null)return`Confidence: ${s} — sample-size signal (n vs. ${qh}-comp floor)`;const r=a>=qh?`meets the ${qh}-comp floor`:`below the ${qh}-comp floor`;return`Confidence: ${s} — n=${a} ${r}`}function tO(t,a){if(a.startsWith("%"))return`${t.toFixed(2)}${a}`;const s=Math.round(t);return`${s<0?"-":""}
53$${Math.abs(s).toLocaleString("en-US")}${a.startsWith("$/")?a.slice(1):""}`}const XQ=({assignmentId:t,subject:a,submarketComps:s,broadComps:r,marketLocked:n,subMarketLocked:i,onApplyAdjustments:l,onOpenDrawer:c,onOpenTimeWizard:d,compEmptyHint:p=null,submarketFunnel:u,marketFunnel:m})=>{const[h,f]=o.useState(!1),[v,S]=o.useState(null),[N,x]=o.useState(null),[y,b]=o.useState(!1),j=n||i,T=s.length>0||r.length>0,O=d??c,E=o.useMemo(()=>({assignmentId:t,subject:a,submarket:s,broad:r}),[t,a,s,r]),R=Vr({queryKey:["/api/multi-method/run",t,s.length,r.length],queryFn:async()=>(await Qo("POST","/api/multi-method/run",E)).json(),enabled:!!t&&T&&j,staleTime:30*1e3}),G=Vr({queryKey:["/api/multi-method/locks",t],enabled:!!t,retry:!1}),U=o.useMemo(()=>["/api/time-adj/sessions",{assignmentId:t}],[t]),C=Vr({queryKey:U,queryFn:async()=>{if(!t)return null;const be=await fetch(`/api/time-adj/sessions?assignmentId=${encodeURIComponent(t)}`,{credentials:"include"});if(be.status===404)return null;if(!be.ok)throw new Error(`Failed to load TimeVault session: ${be.status}`);return be.json()},enabled:!!t,retry:!1}),F=o.useMemo(()=>{const be=C.data;if(!be||!be.decisionSavedAt)return{isLocked:!1,label:void 0};if(be.selectedOption==="zero"||be.finalMethod==="zero")return{isLocked:!0,label:"0.00%/mo"};const H=be.linearRatePctPerMonth,ye=typeof H=="string"?parseFloat(H):H;return ye==null||!isFinite(ye)?{isLocked:!1,label:void 0}:{isLocked:!0,label:`${ye>=0?"+":""}${ye.toFixed(2)}%/mo`}},[C.data]),A=o.useMemo(()=>zk(C.data??null),[C.data]),M=o.useMemo(()=>qk(C.data??null),[C.data]),B=C.data?.id??null,oe=!C.data?.isLocked||!C.data?.derivedAt,[ae,D]=o.useState(!1),[_,$]=o.useState(null),z=o.useCallback(async be=>{if(!B){$("Open the full wizard first to lock and derive a rate.");return}$(null),D(!0);try{const H=be.isRecommended?void 0:"Selected via inline AdjustmentBar Time chip",ye=await fetch(`/api/time-adj/sessions/${B}/decision`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({selectedDataset:be.dataset,selectedMethod:be.method,...H?{overrideReason:H}:{},decisionSavedAt:new Date().toISOString()})});if(!ye.ok){const de=await ye.json().catch(()=>({}));throw new Error(de&&de.error||`Save failed (${ye.status})`)}await fi.invalidateQueries({queryKey:U}),b(!1)}catch(H){$(H instanceof Error?H.message:"Failed to save method")}finally{D(!1)}},[B,U]),V=o.useCallback(async(be,H)=>{if(!B)throw new Error("Open the full wizard first to lock and derive the time session.");$(null);const ye=await fetch(`/api/time-adj/sessions/${B}/decision`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({selectedDataset:C.data?.selectedDataset??"submarket",selectedMethod:"manual",manualRatePctPerMonth:be,priceBasis:H,decisionSavedAt:new Date().toISOString()})});if(!ye.ok){const de=await ye.json().catch(()=>({}));throw new Error(de&&de.error||`Save failed (${ye.status})`)}await fi.invalidateQueries({queryKey:U})},[B,U,C.data?.selectedDataset]),le=o.useMemo(()=>{const be=C.data,H=be?.selectedMethod==="manual";let ye="SALE";if(be?.overrideReason){const He=String(be.overrideReason).match(/\[basis:(CTR|SALE)\]/);He&&(ye=He[1])}const de=be?.linearRatePctPerMonth,ge=typeof de=="string"?parseFloat(de):de,Be=H&&ge!=null&&Number.isFinite(ge)?ge:null;return{isManualLocked:!!H,basis:ye,rate:Be}},[C.data]),W=o.useCallback(async()=>{if(B){$(null),D(!0);try{const be=await fetch(`/api/time-adj/sessions/${B}/clear-decision`,{method:"POST",credentials:"include"});if(!be.ok){const H=await be.json().catch(()=>({}));throw new Error(H&&H.error||`Clear failed (${be.status})`)}await fi.invalidateQueries({queryKey:U})}catch(be){$(be instanceof Error?be.message:"Failed to remove time adjustment")}finally{D(!1)}}},[B,U]),me=o.useMemo(()=>{const be={};for(const H of G.data?.locks??[])be[H.attributeKey]=H;return be},[G.data]),Z=o.useMemo(()=>{const be={};for(const H of R.data?.headline.ranked??[])be[H.attribute]=H.recommendation;return be},[R.data]),pe=Yd({mutationFn:async({attribute:be,result:H})=>{const ye=be.recommendedKey?be.results.find(ge=>`${ge.method}:${ge.dataset}`===be.recommendedKey):void 0;return(await Qo("POST","/api/multi-method/lock",{assignmentId:t,runId:R.data?.runId,locks:[{attributeKey:be.attribute,lockedRate:H.rate,rateUnit:H.unit,method:H.method,dataset:H.dataset,sampleSize:H.sampleSize,confidence:H.confidence,alternatives:be.results,recommendation:ye??null,wasRecommendationFollowed:`${H.method}:${H.dataset}`===be.recommendedKey}]})).json()},onSuccess:async(be,{attribute:H,result:ye})=>{await fi.invalidateQueries({queryKey:["/api/multi-method/locks",t]});const de={};for(const He of G.data?.locks??[]){const Ie=typeof He.lockedRate=="number"?He.lockedRate:parseFloat(String(He.lockedRate));isFinite(Ie)&&(de[He.attributeKey]={rate:Ie,unit:He.rateUnit})}de[H.attribute]={rate:ye.rate,unit:ye.unit};const ge=new Set;for(const He of Object.keys(de))ge.add(Fm[He]);const Be=KT(de,a,(()=>{const He=new Set,Ie=[];for(const ce of[...s,...r])if(!He.has(ce.id)&&(He.add(ce.id),Ie.push(ce),Ie.length>=50))break;return Ie})(),ge);l(Be,[Fm[H.attribute]])}}),se=(be,H)=>{S(be.attribute),x(null),pe.mutate({attribute:be,result:H},{onSettled:()=>S(null)})},fe=R.isLoading||!R.data&&T,ue=o.useMemo(()=>{const be=R.data;if(!be)return[];const H=new Map;for(const Be of be.attributes)H.set(Be.attribute,Be);const ye=[],de=new Set,ge=H.get("gla");ge&&(ye.push(ge),de.add(ge.attribute));for(const Be of be.headline.ranked){if(de.has(Be.attribute))continue;const He=H.get(Be.attribute);if(He&&!He.insufficientData&&(ye.push(He),de.add(He.attribute)),ye.length>=J1)break}if(ye.length<=1){for(const Be of be.attributes)if(!de.has(Be.attribute)&&(Be.insufficientData||(ye.push(Be),de.add(Be.attribute)),ye.length>=J1))break}return ye},[R.data]);return!j||!a?null:h?e.jsxs("div",{className:"shrink-0 border-b border-slate-200/80 bg-slate-50/60 px-4 py-1.5 flex items-center gap-2 text-[11px] text-slate-500","data-testid":"adjustment-bar-collapsed",children:[e.jsx(ul,{className:"w-3.5 h-3.5 text-[#072034]"}),e.jsxs("span",{className:"font-medium text-slate-700",children:["Adjustment rates ",ue.length>0?`(${ue.length})`:""]}),e.jsx("span",{className:"text-slate-400",children:"— hidden"}),e.jsxs("button",{onClick:()=>f(!1),className:"ml-auto inline-flex items-center gap-1 text-[11px] text-blue-600 hover:text-blue-800 font-medium","data-testid":"button-show-adjustment-bar",children:["Show ",e.jsx(Rr,{className:"w-3.5 h-3.5"})]})]}):e.jsx(gr,{children:e.jsxs("div",{className:"shrink-0 border-b border-slate-200/80 bg-slate-50/60 px-4 py-2 flex items-center gap-2 flex-wrap","data-testid":"adjustment-bar",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mr-2",children:[e.jsx(ul,{className:"w-3.5 h-3.5 text-[#072034]"}),e.jsx("span",{className:"text-[11px] font-semibold text-slate-700 uppercase tracking-wide",children:"Rates"}),e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex items-center text-slate-400 hover:text-slate-600 focus:outline-none","aria-label":"What do the chip pill and dots mean?","data-testid":"button-rates-legend",children:e.jsx(Xx,{className:"w-3.5 h-3.5"})})}),e.jsx(Wa,{side:"bottom",align:"start",className:"max-w-[320px]","data-testid":"tooltip-rates-legend",children:e.jsxs("div",{className:"text-[11px] leading-snug space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Pill"})," = effect-size class (DRIVER / MINOR / NO SUPPORT) — how much this attribute moves value."]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Dots"})," = sample-size confidence vs. the n=",qh," comp floor."]})]})})]})]}),fe&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-slate-500","data-testid":"adjustment-bar-loading",children:[e.jsx(za,{className:"w-3.5 h-3.5 animate-spin"}),"Computing rates…"]}),R.isError&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-red-600","data-testid":"adjustment-bar-error",children:[e.jsx(Di,{className:"w-3.5 h-3.5"}),R.error.message]}),e.jsx(eZ,{isLocked:F.isLocked,label:F.label,isHydrating:C.isLoading,isOpen:y,onOpenChange:b,options:A,activeMethodId:M,needsWizard:oe,isWorking:ae,errorMessage:_,onSelect:z,onRemove:W,onOpenFullWizard:O,manualState:le,onManualApply:V}),!fe&&!R.isError&&ue.length===0&&e.jsx("span",{className:"text-[11px] text-slate-500","data-testid":"adjustment-bar-empty",children:p||"No qualifying rates yet. Open the drawer for detail."}),ue.map(be=>e.jsx(tZ,{attribute:be,lockedRow:me[be.attribute]??null,isApplying:v===be.attribute,isOpen:N===be.attribute,onOpenChange:H=>x(H?be.attribute:null),onSelect:H=>se(be,H),submarketFunnel:u,marketFunnel:m,recommendation:Z[be.attribute]??null},be.attribute)),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e.jsx("button",{onClick:c,className:"text-[11px] text-blue-600 hover:text-blue-800 font-medium","data-testid":"button-open-drawer-from-bar",children:"Open full review"}),e.jsxs("button",{onClick:()=>f(!0),className:"inline-flex items-center gap-1 text-[11px] text-slate-500 hover:text-slate-700","data-testid":"button-hide-adjustment-bar",children:["Hide ",e.jsx(Du,{className:"w-3.5 h-3.5"})]})]})]})})},eZ=({isLocked:t,label:a,isHydrating:s,isOpen:r,onOpenChange:n,options:i,activeMethodId:l,needsWizard:c,isWorking:d,errorMessage:p,onSelect:u,onRemove:m,onOpenFullWizard:h,manualState:f,onManualApply:v})=>{const S=a??(s?"Loading…":"Pick a method"),N=o.useCallback(()=>{n(!1),h()},[n,h]);return e.jsxs(xn,{open:r,onOpenChange:n,children:[e.jsx(bn,{asChild:!0,children:e.jsxs("button",{type:"button",className:Q("inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[11px] font-semibold border transition-colors",t?"bg-emerald-50 border-emerald-200 text-emerald-800 hover:bg-emerald-100":c?"bg-white border-dashed border-slate-300 text-slate-500 italic hover:bg-slate-50":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50"),"data-testid":"bar-chip-time","data-locked":t||void 0,title:c?"Open the full wizard to lock the market and derive rates":t?`Time adjustment locked at ${a}`:"Pick a time-adjustment method",children:[d?e.jsx(za,{className:"w-3 h-3 animate-spin"}):t?e.jsx(Hr,{className:"w-3 h-3"}):e.jsx(Pu,{className:"w-3 h-3"}),e.jsx("span",{className:"text-slate-500 font-medium",children:"Time"}),e.jsx("span",{className:"font-bold",children:S})]})}),e.jsxs(yn,{className:"w-[380px] p-3 space-y-3",align:"start","data-testid":"popover-bar-chip-time",children:[e.jsx(Yk,{options:i,activeMethodId:l,needsWizard:c,isWorking:d,isHydrating:s,errorMessage:p,onSelect:u,onRemove:m,onOpenFullWizard:N}),e.jsx("div",{className:"border-t border-slate-100 pt-2",children:e.jsx(Gk,{currentRatePct:f.rate,currentBasis:f.basis,isManualLocked:f.isManualLocked,disabledReason:c?"Open the full wizard to lock + derive rates first.":null,onApply:v})})]})]})},tZ=({attribute:t,lockedRow:a,isApplying:s,isOpen:r,onOpenChange:n,onSelect:i,submarketFunnel:l,marketFunnel:c,recommendation:d})=>{const p=t.recommendedKey,u=p?t.results.find(R=>`${R.method}:${R.dataset}`===p):void 0,h=(a?typeof a.lockedRate=="number"?a.lockedRate:parseFloat(String(a.lockedRate)):null)??u?.rate??null,f=a?.rateUnit??u?.unit??HT[t.attribute],v=a?.sampleSize??u?.sampleSize??null,S=u?.confidence??"red",N=!!a,x=v!=null?WT(v,t.attribute):null,y=!!x,b=a?`${a.method}:${a.dataset}`:null,j=!!(N&&p&&b&&b!==p),T=h!=null?tO(h,f):"No rate",O=!N&&h!=null,E=e.jsxs("button",{type:"button",className:Q("inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[11px] font-semibold border transition-colors",N?"bg-emerald-50 border-emerald-200 text-emerald-800 hover:bg-emerald-100":"bg-white border-slate-200 text-slate-700 hover:bg-slate-50",O&&!y&&"border-dashed border-slate-300 text-slate-500 bg-slate-50/40",y&&!N&&"italic bg-amber-50/70 border-amber-200 text-amber-800 hover:bg-amber-100/70",y&&N&&"italic"),"data-testid":`bar-chip-${t.attribute}`,"data-locked":N||void 0,"data-recommendation":O||void 0,title:O?"Recommendation — click to apply this rate to the grid":N?"Locked rate — click to change method/dataset":void 0,children:[s?e.jsx(za,{className:"w-3 h-3 animate-spin"}):N?e.jsx(Hr,{className:"w-3 h-3"}):null,e.jsx("span",{className:"text-slate-500 font-medium",children:qd[t.attribute]}),e.jsx("span",{className:"font-bold",children:T}),v!=null&&e.jsxs(kt,{variant:"outline",className:Q("text-[9px] px-1 py-0 h-4 border-slate-200 text-slate-500",y&&"border-amber-300 text-amber-700"),"data-testid":`bar-chip-sample-size-${t.attribute}`,children:["n=",v]}),e.jsx("span",{className:Q("text-[10px] tracking-tight",QQ[S]),"aria-label":eO(S,v),title:eO(S,v),"data-testid":`bar-chip-confidence-${t.attribute}`,children:KQ[S]}),j&&e.jsx("span",{className:"text-[8px] font-bold px-1 py-0 rounded bg-amber-100 text-amber-800 border border-amber-200 tracking-wide","data-testid":`bar-chip-override-${t.attribute}`,title:`Override — locked ${a?.method}/${a?.dataset}; model recommended ${p}`,children:"OVR"}),d&&e.jsx("span",{className:Q("text-[8px] font-bold px-1 py-0 rounded border tracking-wide",JQ[d]),"data-testid":`bar-chip-recommendation-${t.attribute}`,"data-recommendation-class":d,"aria-label":X1[d],title:X1[d],children:ZQ[d]})]});return e.jsxs(xn,{open:r,onOpenChange:n,children:[e.jsx(bn,{asChild:!0,children:y?e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:E}),e.jsx(Wa,{children:e.jsx("p",{className:"text-xs max-w-xs","data-testid":`tooltip-bar-chip-${t.attribute}`,children:x})})]}):E}),e.jsx(yn,{className:"w-[420px] p-3",align:"start","data-testid":`popover-bar-chip-${t.attribute}`,children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-[11px] font-semibold text-slate-700",children:[qd[t.attribute]," · pick method × dataset"]}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:["submarket","broad"].map(R=>{const G=R==="submarket"?l:c,U=G?.lockedCount??null;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"text-[10px] font-bold text-slate-400 uppercase flex items-center gap-1","data-testid":`bar-popover-dataset-header-${R}-${t.attribute}`,children:[e.jsx("span",{children:af[R]}),U!=null&&U>0&&e.jsxs("span",{className:"font-semibold text-slate-500 normal-case","data-testid":`bar-popover-dataset-locked-count-${R}-${t.attribute}`,children:["· ",U," locked"]})]}),["paired","grouped","regression"].map(C=>{const F=t.results.find(V=>V.method===C&&V.dataset===R);if(!F)return e.jsxs("div",{className:"px-2 py-1.5 text-[10px] text-slate-300 border border-dashed border-slate-200 rounded",children:[uf[C]," — n/a"]},C);const A=F.qualified?WT(F.sampleSize,t.attribute):null,M=a?.method===C&&a?.dataset===R,B=p===`${C}:${R}`,oe=Q("w-full text-left px-2 py-1.5 rounded border text-[11px] transition-colors relative",!F.qualified&&"opacity-80 curs
53or-default border-amber-200/70 bg-amber-50/40",F.qualified&&!M&&"border-slate-200 hover:bg-slate-50",M&&"border-emerald-300 bg-emerald-50",B&&!M&&"ring-2 ring-[#C5A572] ring-inset",A&&F.qualified&&!M&&"italic bg-amber-50/60 border-amber-200 text-amber-800"),ae=A??F.reason??void 0,D=`bar-method-cell-${t.attribute}-${C}-${R}`,_=B||void 0,$=M||void 0,z=e.jsxs(e.Fragment,{children:[B&&e.jsx("span",{className:"absolute -top-1.5 -right-1.5 bg-[#C5A572] text-white text-[8px] font-bold px-1 py-0 rounded leading-tight tracking-wide","data-testid":`bar-method-cell-rec-badge-${t.attribute}-${C}-${R}`,children:"REC"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-slate-500 inline-flex items-center gap-1",children:[M&&e.jsx(Hr,{className:"w-2.5 h-2.5 text-emerald-600"}),uf[C]]}),e.jsxs("span",{className:"text-[9px] text-slate-400","data-testid":`bar-method-cell-n-${t.attribute}-${C}-${R}`,title:G?`${G.usableCount} usable of ${G.lockedCount} locked (post-conversion). Method engine consumed ${F.sampleSize}.`:`Method engine consumed ${F.sampleSize}.`,children:["n=",G?G.usableCount:F.sampleSize]})]}),G&&e.jsx(EM,{data:G,outcome:RM(F),testIdSuffix:`bar-${t.attribute}-${R}-${C}`,className:"mt-0.5 mb-0.5 text-slate-500"}),F.qualified?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"font-bold text-slate-800",children:tO(F.rate,F.unit)}),F.method==="peeled"&&e.jsx("div",{className:"text-[9px] italic text-slate-500 leading-tight mt-0.5","data-testid":`bar-peeled-retired-footnote-${t.attribute}-${R}`,children:"Method retired in v2.0 — displayed for audit."})]}):e.jsxs("div",{className:"space-y-1 mt-0.5",children:[e.jsx("div",{className:"text-[10px] italic text-amber-800/90 leading-snug","data-testid":`bar-method-cell-reason-${t.attribute}-${C}-${R}`,children:F.reason||"Insufficient data"}),F.method==="paired"&&F.rejectionDiagnostic&&e.jsx("div",{className:"mt-1",children:e.jsx(CM,{diagnostic:F.rejectionDiagnostic,testIdSuffix:`bar-${t.attribute}-${R}`,className:"text-amber-900/80"})})]})]});return F.qualified?e.jsx("button",{type:"button",onClick:()=>i(F),className:oe,title:ae,"data-testid":D,"data-recommended":_,"data-locked":$,children:z},C):e.jsx("div",{className:oe,title:ae,"data-testid":D,"data-recommended":_,"data-locked":$,children:z},C)})]},R)})}),x&&e.jsx("div",{className:"text-[10px] text-amber-700 bg-amber-50 border border-amber-200 rounded px-2 py-1","data-testid":`popover-low-confidence-note-${t.attribute}`,children:x}),t.results.some(R=>R.method==="paired"&&!R.qualified)&&e.jsxs("p",{className:"text-[10px] text-slate-500 bg-slate-50 border border-slate-200 rounded px-2 py-1 leading-snug","data-testid":`popover-paired-vs-grouped-note-${t.attribute}`,children:[e.jsx("span",{className:"font-semibold text-slate-700",children:"Paired vs. Grouped:"})," ","Strict ",e.jsx("span",{className:"font-medium",children:"Paired Sales"})," needs near-identical comp pairs (GLA ±10%, beds exact, year ±10, etc.)."," ",e.jsx("span",{className:"font-medium",children:"Grouped Paired Sales"})," averages prices within size buckets, so it usually returns a rate when the dataset has no clean pairs."]}),v!=null&&v>=qh&&e.jsx("p",{className:"text-[10px] text-slate-400",children:"Selecting an option locks that rate and cascades through the grid."})]})})]})},aZ={salePrice:"sale price",saleDate:"sale date",gla:"GLA",bedrooms:"bedrooms",bathrooms:"bathrooms"};function sZ(t){const a=t.price??t.listPrice??null,s=t.saleDate??t.contractDate??t.listDate??null,r=t.sqft??t.sqftPR??null,n=t.beds,i=t.baths,l=[];return a==null&&l.push("salePrice"),s||l.push("saleDate"),r==null&&l.push("gla"),n==null&&l.push("bedrooms"),i==null&&l.push("bathrooms"),l.length>0?{comp:null,missingFields:l}:{comp:{id:t.snapshotId??t.id,address:t.address,salePrice:a,saleDate:s,gla:r,bedrooms:n,bathrooms:i,yearBuilt:t.yearBuilt??t.yearBuiltPR??void 0,lotSize:t.lotSqft??t.lotSqftPR??void 0,garageSpaces:t.garageSpaces??void 0,condition:t.conditionRating??void 0,quality:t.qualityRating??void 0,elsScore:t.echoLocationScore?.score},missingFields:[]}}function aO(t){const a=[],s={};let r=0;for(const n of t){const{comp:i,missingFields:l}=sZ(n);if(i)a.push(i);else{r++;
53for(const c of l)s[c]=(s[c]??0)+1}}return{comps:a,rejectionCounts:s,rejectedCount:r}}function $S(t,a=2){const s=Object.entries(t);return s.length===0?"":(s.sort((n,i)=>i[1]-n[1]||n[0].localeCompare(i[0])),s.slice(0,a).map(([n,i])=>`${i} missing ${aZ[n]}`).join(" · "))}function rZ(t){const{assignmentId:a,verifiedSubject:s,lockedSubmarketPropertyCards:r,lockedMarketPropertyCards:n,marketLocked:i,subMarketLocked:l,locksHydrating:c=!1,enabled:d=!0,subjectElsScore:p,currentAdjustments:u,onApplyAdjustments:m,onComplianceComputed:h,embeddedTimeVault:f}=t,[v,S]=o.useState(!1),N=o.useMemo(()=>aO(r),[r]),x=o.useMemo(()=>aO(n),[n]),y=l?N.comps:[],b=i?x.comps:[],j=o.useMemo(()=>{const z=r.length,V=y.length,le=N.rejectedCount;return{lockedCount:z,usableCount:V,rejectedCount:le,topRejectionLabel:$S(N.rejectionCounts,1)||null}},[r.length,y.length,N.rejectedCount,N.rejectionCounts]),T=o.useMemo(()=>{const z=n.length,V=b.length,le=x.rejectedCount;return{lockedCount:z,usableCount:V,rejectedCount:le,topRejectionLabel:$S(x.rejectionCounts,1)||null}},[n.length,b.length,x.rejectedCount,x.rejectionCounts]),O=o.useMemo(()=>{if(!s)return null;const z=s.lotSizeAcres;return{gla:s.gla,bedrooms:s.bedrooms,bathrooms:s.bathrooms,yearBuilt:s.yearBuilt,lotSize:z?Math.round(z*43560):void 0,garageSpaces:s.garageSpaces,basementSqft:s.basementSqft,condition:s.condition,qual
53ity:s.quality,elsScore:p}},[s,p]),E=i||l,R=E&&O!==null&&(y.length>0||b.length>0),G=o.useMemo(()=>{const z=[];c||!i&&!l&&z.push("Lock the Market or Sub-Market dataset on Property Lab"),O===null&&z.push("Verify the subject property");const V=l?r.length:0,le=i?n.length:0;if(y.length+b.length,E&&y.length===0&&b.length===0){const W=V+le;if(W===0)z.push("Locked datasets are empty — re-run the Sub-Market or Market search on Property Lab");else{const me={};if(l)for(const[se,fe]of Object.entries(N.rejectionCounts))me[se]=(me[se]??0)+fe;if(i)for(const[se,fe]of Object.entries(x.rejectionCounts))me[se]=(me[se]??0)+fe;const Z=$S(me),pe=l&&V>0&&i&&le>0?` (${V} sub-market, ${le} market)`:i&&le>0?` (${le} market)`:l&&V>0?` (${V} sub-market)`:"";z.push(`${W} locked comp${W===1?"":"s"} unusable${pe} — ${Z||"missing required fields"}. Re-verify on Property Lab.`)}}return z},[i,l,E,c,O,y.length,b.length,r.length,n.length,N.rejectionCounts,x.rejectionCounts]),U=o.useMemo(()=>{if(y.length>0||b.length>0||!E)return null;const z=l?r.length:0,V=i?n.length:0,le=z+V;if(le===0)return"No comps in the locked datasets yet. Re-run the Sub-Market or Market search on Property Lab.";const W={};if(l)for(const[pe,se]of Object.entries(N.rejectionCounts))W[pe]=(W[pe]??0)+se;if(i)for(const[pe,se]of Object.entries(x.rejectionCounts))W[pe]=(W[pe]??0)+se;const me=$S(W),Z=z>0&&V>0?` (${z} sub-market, ${V} market)`:"";return`${le} locked comp${le===1?"":"s"} unusable${Z} — ${me||"missing required fields"}. Re-verify on Property Lab.`},[E,y.length,b.length,r.length,n.length,N.rejectionCounts,x.rejectionCounts]),C=o.useCallback(()=>{S(!0)},[]),F=C,A=C,M=o.useMemo(()=>{const z=new Set,V=[];for(const le of[...y,...b])z.has(le.id)||(z.add(le.id),V.push(le));return V},[y,b]),B=o.useMemo(()=>R||c?null:!i&&!l?"Lock a dataset to enable":O===null?"Subject not verified":y.length===0&&b.length===0?"No usable locked comps":null,[R,c,i,l,O,y.length,b.length]),oe=e.jsxs("button",{type:"button",onClick:F,disabled:!R,"data-testid":"btn-toolbar-run-adjustments",title:R?"Run multi-method adjustments":G.length>0?`To enable: ${G.join(" · ")}`:"Lock the Market or Sub-Market dataset first",className:Q("flex items-center gap-1.5 h-[36px] px-3 rounded text-[12px] font-semibold transition-all",R?"bg-[#072034] text-white hover:bg-[#0c2f4d]":"bg-slate-50 text-slate-300 cursor-not-allowed"),children:[e.jsx(ul,{size:12})," Run Adjustments"]}),ae=R?oe:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx("span",{className:"inline-flex","data-testid":"btn-toolbar-run-adjustments-tooltip-trigger",children:oe})}),e.jsx(Wa,{side:"bottom",className:"max-w-xs",children:e.jsxs("div",{className:"text-xs","data-testid":"tooltip-run-adjustments-disabled",children:[e.jsx("div",{className:"font-semibold mb-1",children:"Run Adjustments needs:"}),e.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:G.length>0?G.map(z=>e.jsx("li",{children:z},z)):e.jsx("li",{children:"Lock the Market or Sub-Market dataset on Property Lab"})})]})})]})}),B&&e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight pl-0.5","data-testid":"text-run-adjustments-inline-blocker",children:B})]}),D=o.useMemo(()=>({open:v,onOpenChange:S,assignmentId:a,subject:O,submarketComps:y,broadComps:b,marketLocked:i,subMarketLocked:l,locksHydrating:c,currentAdjustments:u,onApplyAdjustments:m,onComplianceComputed:h,embeddedTimeVault:f,submarketFunnel:j,marketFunnel:T}),[v,a,O,y,b,i,l,c,u,m,h,f,j,T]),_=o.useMemo(()=>e.jsx(wM,{...D}),[D]),$=a&&O?e.jsx(XQ,{assignmentId:a,subject:O,submarketComps:y,broadComps:b,marketLocked:i,subMarketLocked:l,onApplyAdjustments:m,onOpenDrawer:A,onOpenTimeWizard:A,compEmptyHint:U,submarketFunnel:j,marketFunnel:T}):null;return d?{button:ae,drawer:_,drawerProps:D,bar:$,canRun:R,orchestratorSubject:O,orchestratorComps:M,openDrawer:A}:{button:null,drawer:null,drawerProps:null,bar:null,canRun:!1,orchestratorSubject:null,orchestratorComps:[],openDrawer:()=>{}}}const PM=o.createContext(null),nZ=({children:t})=>{const[a,s]=o.useState(null),r=o.useCallback(n=>{s(i=>
53i===n?i:n)},[]);return e.jsxs(PM.Provider,{value:r,children:[t,a?e.jsx(wM,{...a}):null]})};function iZ(){return o.useContext(PM)??oZ}const oZ=()=>{},Yf=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}),lZ=({compliance:t,acknowledged:a,onAcknowledgeChange:s})=>{const{tightness:r,perComp:n,anyExceedance:i}=t,{adjustedPriceMin:l,adjustedPriceMax:c,adjustedPriceMedian:d,spread:p,spreadPct:u,coefficientOfVariation:m}=r,h=v=>v<5?"from-emerald-500 to-emerald-400":v<10?"from-amber-400 to-amber-300":"from-red-500 to-red-400",f=(d-l)/(c-l)*100;return e.jsxs(ja,{className:"rounded-lg border-slate-200 bg-white shadow-sm",children:[e.jsx(Do,{className:"pb-3",children:e.jsx(ko,{className:"text-[16px] font-bold text-[#072034]",children:"Compliance Check"})}),e.jsxs(Ta,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"rounded-lg bg-slate-50 p-3 border border-slate-100",children:[e.jsx("div",{className:"text-[12px] text-slate-500 font-medium",children:"Adjusted Range"}),e.jsxs("div",{className:"text-[14px] font-bold text-[#072034]",children:[Yf.format(l)," - ",Yf.format(c)]})]}),e.jsxs("div",{className:"rounded-lg bg-slate-50 p-3 border border-slate-100",children:[e.jsx("div",{className:"text-[12px] text-slate-500 font-medium",children:"Spread"}),e.jsxs("div",{className:"text-[14px] font-bold text-[#072034]",children:[Yf.format(p)," (",u.toFixed(1),"%)"]})]}),e.jsxs("div",{className:"rounded-lg bg-slate-50 p-3 border border-slate-100",children:[e.jsx("div",{className:"text-[12px] text-slate-500 font-medium",children:"Tightness CV"}),e.jsxs("div",{className:"text-[14px] font-bold text-[#072034]",children:[m.toFixed(1),"%"]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"relative h-2 w-full rounded-full bg-slate-100 overflow-hidden",children:[e.jsx("div",{className:Q("absolute inset-0 bg-gradient-to-r",h(u))}),e.jsx("div",{className:"absolute top-0 bottom-0 w-0.5 bg-[#072034] shadow-sm z-10",style:{left:`${f}%`}})]}),e.jsxs("div",{className:"flex justify-between text-[10px] text-slate-400 font-medium px-0.5",children:[e.jsxs("span",{children:["Min: ",Yf.format(l)]}),e.jsxs("span",{children:["Max: ",Yf.format(c)]})]})]})]}),e.jsx("div",{className:"rounded-md border border-slate-200 overflow-hidden",children:e.jsxs(Gd,{children:[e.jsx(Hd,{className:"bg-slate-50",children:e.jsxs(gi,{className:"hover:bg-transparent",children:[e.jsx(Ds,{className:"text-[11px] font-semibold text-slate-600 h-8 px-3",children:"Comp ID"}),e.jsx(Ds,{className:"text-[11px] font-semibold text-slate-600 h-8 px-2 text-right",children:"Net Adj"}),e.jsx(Ds,{className:"text-[11px] font-semibold text-slate-600 h-8 px-2 text-right",children:"Net %"}),e.jsx(Ds,{className:"text-[11px] font-semibold text-slate-600 h-8 px-2 text-right",children:"Gross Adj"}),e.jsx(Ds,{className:"text-[11px] font-semibold text-slate-600 h-8 px-2 text-right",children:"Gross %"}),e.jsx(Ds,{className:"text-[11px] font-semibold text-slate-600 h-8 px-2 text-right",children:"Max Line %"}),e.jsx(Ds,{className:"text-[11px] font-semibold text-slate-600 h-8 px-3 text-center",children:"Status"})]})}),e.jsx(Wd,{children:n.map(v=>{const S=v.netExceeded||v.grossExceeded||v.individualExceeded,N=[v.netExceeded&&"Net (15%)",v.grossExceeded&&"Gross (25%)",v.individualExceeded&&"Individual Line (10%)"].filter(Boolean).join(", ");return e.jsxs(gi,{className:"hover:bg-slate-50/50",children:[e.jsx(ws,{className:"text-[11px] py-2 px-3 font-medium text-slate-700 truncate max-w-[80px]",children:v.compId}),e.jsx(ws,{className:Q("text-[11px] py-2 px-2 text-right",v.netExceeded&&"text-[#B91C1C] bg-[#FEE2E2]/30"),children:Yf.format(v.netAdjustment)}),e.jsxs(ws,{className:Q("text-[11px] py-2 px-2 text-right",v.netExceeded&&"text-[#B91C1C] bg-[#FEE2E2]/30"),children:[v.netAdjustmentPct.toFixed(1),"%"]}),e.jsx(ws,{className:Q("text-[11px] py-2 px-2 text-right",v.grossExceeded&&"text-[#B91C1C] bg-[#FEE2E2]/30"),children:Yf.format(v.grossAdjustment)}),e.jsxs(ws,{className:Q("text-[11px] py-2 px-2 text-right",v.grossExceeded&&"text-[#B91C1C] bg-[#FEE2E2]/30"),children:[v.grossAdjustmentPct.toFixed(1),"%"]}),e.jsxs(ws,{className:Q("text-[11px] py-2 px-2 text-right",v.individualExceeded&&"text-[#B91C1C] bg-[#FEE2E2]/30"),children:[v.individualLineMaxPct.toFixed(1),"%"]}),e.jsx(ws,{className:"text-[11px] py-2 px-3 text-center",children:S?e.jsx(gr,{children:e.jsxs(Ga,{children:[e.jsx(Ha,{asChild:!0,children:e.jsx(Ns,{className:"w-4 h-4 text-[#92400E] mx-auto cursor-help"})}),e.jsx(Wa,{children:e.jsxs("p",{children:["Exceeds: ",N]})})]})}):e.jsx(kr,{className:"w-4 h-4 text-[#007A55] mx-auto"})})]},v.compId)})})]})}),i?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg bg-[#FEF3C7] p-3 border border-[#FDE68A] flex gap-3",children:[e.jsx(Ns,{className:"w-5 h-5 text-[#92400E] shrink-0"}),e.jsx("p",{className:"text-[12px] text-[#92400E] leading-relaxed",children:"One or more comps exceed Fannie Mae soft caps (Net 15% / Gross 25% / Single Line 10%). Per USPAP and FNMA Selling Guide, you may proceed if the adjustments are market-supported."})]}),e.jsxs("div",{className:"flex items-start gap-2 pt-1",children:[e.jsx(Pa,{id:"fnma-acknowledge",checked:a,onCheckedChange:v=>s(!!v),"data-testid":"checkbox-fnma-acknowledge",className:"mt-0.5 border-slate-300 data-[state=checked]:bg-[#072034] data-[state=checked]:border-[#072034]"}),e.jsx("label",{htmlFor:"fnma-acknowledge",className:"text-[12px] text-slate-600 leading-snug cursor-pointer select-none",children:"I have reviewed the exceedances and confirm the adjustments are market-supported and properly documented."})]})]}):e.jsx("div",{className:"flex justify-center",children:e.jsxs(kt,{className:"bg-[#D0FAE5] text-[#007A55] border-[#A7F3D0] hover:bg-[#D0FAE5] px-3 py-1 text-[12px] font-medium shadow-none",children:[e.jsx(kr,{className:"w-3.5 h-3.5 mr-1.5"}),"All comps within Fannie Mae soft caps."]})})]})]})},sO={n:"north",north:"north",s:"south",south:"south",e:"east",east:"east",w:"west",west:"west",ne:"northeast",northeast:"northeast",nw:"northwest",northwest:"northwest",se:"southeast",southeast:"southeast",sw:"southwest",s
53outhwest:"southwest"},rO={st:"street",str:"street",street:"street",ave:"avenue",av:"avenue",avenue:"avenue",rd:"road",road:"road",dr:"drive",drv:"drive",drive:"drive",blvd:"boulevard",boulevard:"boulevard",ln:"lane",lane:"lane",ct:"court",court:"court",pl:"place",place:"place",hwy:"highway",highway:"highway",pkwy:"parkway",pky:"parkway",parkway:"parkway",ter:"terrace",terr:"terrace",terrace:"terrace",cir:"circle",circle:"circle",way:"way",trl:"trail",trail:"trail",sq:"square",square:"square",loop:"loop",pt:"point",point:"point",plz:"plaza",plaza:"plaza",xing:"crossing",crossing:"crossing",expy:"expressway",expressway:"expressway",fwy:"freeway",freeway:"freeway",cv:"cove",cove:"cove",hl:"hill",hill:"hill",mtn:"mountain",mountain:"mountain",vw:"view",view:"view",vly:"valley",valley:"valley"},cZ=new Set(["apt","apartment","unit","suite","ste","no","num","#"]);function dZ(t){return sO[t]?sO[t]:rO[t]?rO[t]:t}function uZ(t){if(!t)return"";const r=(t.split(",")[0]||t).toLowerCase().replace(/[.,]/g," ").replace(/#/g," # ").replace(/\s+/g," ").trim().split(" ").filter(Boolean),n=[];for(let i=0;i<r.length;i++){const l=r[i];if(cZ.has(l)||l==="#"){i+=1;continue}n.push(dZ(l))}return n.map(i=>i.replace(/[^a-z0-9]/g,"")).filter(Boolean).join(" ")}function nO(t){const a=uZ(t.address||"");if(!a)return"";const s=(t.city||"").toLowerCase().replace(/[^a-z0-9]/g,""),r=(t.state||"").toLowerCase().replace(/[^a-z]/g,""),n=(t.zip||"").replace(/[^0-9]/g,"").slice(0,5);return`${a}|${s||n}|${r}`}function T0(t,a){return!t||!a?!1:t.snapshotId&&a.snapshotId?t.snapshotId===a.snapshotId:!!(t.id&&a.id&&t.id===a.id||t.mlsNumber&&a.mlsNumber&&t.mlsNumber===a.mlsNumber)}function iO(t,a){if(a)return t.find(s=>T0(s,a))}function pZ(t,a,s){return a&&!s&&t==="NeighborhoodName"?"neighborhoodName":t}function OM(t){const a=t.mlsData&&typeof t.mlsData=="object"?t.mlsData:{},s=a.mlsNumber??a.MlsListingNumber??a.ListingId;return Array.from(new Set([t.snapshotId,t.id,t.mlsNumber,s].filter(r=>typeof r=="string"&&r.trim()!=="")))}function mZ(t,a,s){for(const r of OM(a))t[r]=s}function hZ(t,a){const s=t.filter(l=>OM(l).includes(a));if(s.length!==1)return{compId:a};const r=s[0],n=r.mlsData&&typeof r.mlsData=="object"?r.mlsData:{},i=n.mlsNumber??n.MlsListingNumber??n.ListingId;return{compId:r.id||a,...r.snapshotId?{snapshotId:r.snapshotId}:{},...r.mlsNumber||i?{mlsNumber:String(r.mlsNumber||i)}:{},...r.address?{address:r.address}:{}}}function fZ(t,a,s,r,n=!1,i=!1){const l={...t};if(i){const d=Object.values(dk).find(p=>p.includes(a));for(const p of d??[])p!==a&&delete l[p]}const c=["attachedDetached","attachmentType","AttachmentType","AttachedDetached"];if(c.includes(a)){const d=c.map(p=>l[p]).find(p=>p&&typeof p=="object");for(const p of c)delete l[p];l.attachedDetached={...n?d:{},value:s,source:r}}else{const d=l[a];l[a]={...n&&d&&typeof d=="object"?d:{},value:s,source:r}}return l}const oO=t=>t.snapshotId||t.id;function gZ(t,a,s){if(a.length===0)return{merged:t,freshMatches:[]};const r=new Set(t.map(oO)),n=a.filter(i=>r.has(oO(i))?!1:PV(i.status??void 0,s));return n.length===0?{merged:t,freshMatches:[]}:{merged:[...t,...n],freshMatches:n}}function xZ(t){return!t||!t.locked?"missing":Array.isArray(t.propertyCards)&&t.propertyCards.length>0?"valid":"legacy"}function lO(t){const{classification:a,restoredCardCount:s,clientBelievedLocked:r}=t;switch(a){case"valid":return!1;case"legacy":return s===0;case"missing":return r}}const bZ=3958.8;function yZ(t,a,s,r){const n=(s-t)*Math.PI/180,i=(r-a)*Math.PI/180,l=Math.sin(n/2)**2+Math.cos(t*Math.PI/180)*Math.cos(s*Math.PI/180)*Math.sin(i/2)**2;return bZ*2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))}function SZ(t){const{allCachedSales:a,visibleAliasSet:s,getAliases:r,drawnIds:n,hasGeometry:i,radiusMiles:l,subject:c}=t,d=[];for(const p of a){const u=p.coordinates?.lat,m=p.coordinates?.lng;if(!u||!m||r(p).some(v=>s.has(v)))continue;const f=p.snapshotId||p.id||"";if(i&&n&&n.size>0){if(!n.has(f))continue}else if(l&&c&&yZ(c.lat,c.lng,u,m)>l)continue;d.push({id:f,lat:u,lng:m,label:p.address||"Unknown",type:"background-sale",mlsNumber:p.mlsNumber??null,snapshotId:p.snapshotId??null})}return d}function cO(t){return!t||t.locked!==!0?!0:typeof t.locksEnrichedAt=="string"&&t.locksEnrichedAt.length>0}function vZ(t){return!t||!(t.marketLock?.locked===!0||t.submarketLock?.locked===!0)?!1:cO(t.marketLock)&&cO(t.submarketLock)}function NZ(t){return{success:!0,marketLock:t.marketLock?.locked===!0?{...t.marketLock,utilityBands:t.marketLock.utilityBands??null}:null,submarketLock:t.submarketLock?.locked===!0?{...t.submarketLock,utilityBands:t.submarketLock.utilityBands??null}:null,fromSlimPayload:!0}}function AZ(t,a,s,r){const n=[];for(const c of t??[])if(c.polygon)try{const d=c.polygon.type==="MultiPolygon"?vI(c.polygon.coordinates):NI(c.polygon.coordinates);n.push(c2(d,{reverse:!1}))}catch{}const i=!!a&&(a.circles.length>0||a.polygons.length>0),l=s!=null&&s>0&&r?{center:r,radiusMeters:s*OV}:null;return n.length===0&&!i&&!l?null:{boundaryPolys:n,shapes:i?a:null,radiusCircle:l}}function LM(t,a){const s=a.boundaryPolys.length>0,r=!!a.shapes;if(!s&&!r)return a.radiusCircle?LV(t,a.radiusCircle.center)<=a.radiusCircle.radiusMeters:!1;if(s){const n=bv([t.lng,t.lat]);let i=!1;for(const l of a.boundaryPolys)try{if(d2(n,l)){i=!0;break}}catch{}if(!i)return!1}return!(r&&!DV(t,a.shapes))}function dO(t,a,s){return s?t.filter(r=>{const n=r.snapshotId||r.id;return a.has(n)||a.has(r.id)?!0:r.coordinates?LM(r.coordinates,s):!1}):t}const jZ=/^\s*(none|n\/?a|unknown|null|-|–|—)\s*$/i;function Tl(t){return!(t==null||t===""||typeof t=="string"&&jZ.test(t))}function uO(t){const a=t.mlsData;if(!a)return!0;const s=Tl(a.lotSize)||Tl(a.LotSizeSquareFeet)||Tl(a.LotSizeAcres),r=Tl(a.basementSqft)||Tl(a.BasementArea)||Tl(a.basement)||Tl(a.Basement)||Tl(a.basementType),n=Tl(a.garageSpaces)||Tl(a.GarageSpaces)||Tl(a.garageType)||Tl(a.GarageType)||Tl(a.GarageYN),i=Tl(a.PatioAndPorchFeatures)||Tl(a.patioFeatures)||Tl(a.PorchFeatures)||Tl(a.OutdoorFeatures);return!s||!r||!n||!i}function DM(t,a){if(!a)return t||void 0;if(!t)return a;const s={...a};for(const[r,n]of Object.entries(t))Tl(n)&&(s[r]=n);return s}function TZ(t,a){return{...t,lotSize:t.lotSize??(a.lotSize?Number(a.lotSize):void 0),saleDate:t.saleDate||a.saleDate||void 0,contractDate:t.contractDate||a.contractDate||void 0,mlsData:DM(t.mlsData,a.mlsData),publicRecordData:t.publicRecordData||a.publicRecordData||void 0}}function IZ(t,a){return{...t,lotSize:t.lotSize??(a.lotSize?Number(a.lotSize):void 0),saleDate:t.saleDate||a.saleDate||void 0,contractDate:t.contractDate||a.contractDate||void 0,mlsData:DM(t.mlsData,a.mlsData),publicRecordData:t.publicRecordData||a.publicRecordData||void 0,prLotSize:t.prLotSize??a.prLotSize,lotSizeAcres:t.lotSizeAcres??a.lotSizeAcres}}const pO=8e3;function CZ(t){if(!t)return!1;const a=t.allCachedSales;return!(Array.isArray(a)&&a.length>0)}function RZ(t){return t.eligible&&!t.hasArrived&&!t.timedOut}function EZ({initialCachedLabState:t,lateAllCachedSales:a,searchInFlight:s}){const r=o.useRef(CZ(t)),[n,i]=o.useState(!1),[l,c]=o.useState(!1);return o.useEffect(()=>{Array.isArray(a)&&i(!0)},[a]),o.useEffect(()=>{s&&i(!0)},[s]),o.useEffect(()=>{if(!r.current||n||l)return;const d=setTimeout(()=>{console.warn(`[PropertyLab] Heavy-cache gate timed out after ${pO}ms — showing available data`),c(!0)},pO);return()=>clearTimeout(d)},[n,l]),RZ({eligible:r.current,hasArrived:n,timedOut:l})}const z0=5,mC=[{id:"proximity",label:"Distance",tooltip:"Proximity of comp to subject — closer comps are generally more reliable."},{id:"gla",label:"GLA",tooltip:"Gross Living Area — the single most impactful adjustment in most residential appraisals."}
53,{id:"bedsBaths",label:"Bed/Bath",tooltip:"Combined bedroom and bathroom count affects marketability."},{id:"lotSize",label:"Lot Size",tooltip:"Site area drives value in markets where land is scarce."},{id:"yearBuilt",label:"Year Built",tooltip:"Age/effective age impacts condition assumptions."},{id:"bedrooms",label:"Bedrooms",tooltip:"Bedroom count affects marketability."},{id:"bathrooms",label:"Bathrooms",tooltip:"Bathroom count — full and half."},{id:"basement",label:"Basement",tooltip:"Basement type and finish level."},{id:"quality",label:"Quality",tooltip:"Construction quality rating (Q1-Q6)."},{id:"condition",label:"Condition",tooltip:"Overall condition rating (C1-C6)."},{id:"stories",label:"Stories",tooltip:"Number of stories — affects layout comparability and per-floor living area."},{id:"style",label:"Style",tooltip:"Architectural style."},{id:"pool",label:"Pool",tooltip:"In-ground pool presence."},{id:"els",label:"ELS",tooltip:"Environmental Location Score."}],Qx=new Set(mC.map(t=>t.id));function kM(t){if(!Array.isArray(t)||t.length===0)return[];const a=t.filter(i=>Qx.has(i.fieldId));if(a.length===0)return[];const s=a.reduce((i,l)=>i+(typeof l.weight=="number"?l.weight:0),0),r=a.map((i,l)=>({fieldId:i.fieldId,label:i.label,rank:l+1,weight:s>0?Math.round(i.weight/s*100):Math.floor(100/a.length),locked:!!i.locked})),n=r.reduce((i,l)=>i+l.weight,0);if(n!==100&&r.length>0){const i=r.findIndex(c=>!c.locked),l=i>=0?i:0;r[l].weight+=100-n}return r}function BS(t){const a={};return t.forEach(r=>{a[r.fieldId]=r.weight}),{priorities:[...t].sort((r,n)=>r.rank-n.rank).map(r=>r.fieldId),weightOverrides:a}}function wZ(t,a,s){const r=t.filter(x=>x.locked),n=t.filter(x=>!x.locked),i=r.reduce((x,y)=>x+y.weight,0);if(t.length===0)return{items:t,clamped:!1,maxAllowed:0,lockedTotal:0,locksFillBudget:!1};const l=t.find(x=>x.fieldId===a);if(!l||l.locked)return{items:t,clamped:!1,maxAllowed:l?.weight??0,lockedTotal:i,locksFillBudget:i>=100};const c=Math.max(0,100-i),d=n.filter(x=>x.fieldId!==a),p=d.length;if(c<=n.length)return{items:t.map(y=>y.locked?y:{...y,weight:1}),clamped:s>1,maxAllowed:1,lockedTotal:i,locksFillBudget:!0};if(d.length===0)return{items:t.map(y=>y.fieldId===a?{...y,weight:c}:y),clamped:s!==c,maxAllowed:c,lockedTotal:i,locksFillBudget:!1};const u=c-p,m=Math.min(Math.max(s,1),u),h=m!==s,f=c-m,v=d.reduce((x,y)=>x+y.weight,0);let S;if(v===0){const x=Math.floor(f/d.length);S=d.map((y,b)=>b===0?f-x*(d.length-1):x)}else{const x=d.map(E=>E.weight/v*f);S=x.map(E=>Math.max(1,Math.floor(E)));let y=S.reduce((E,R)=>E+R,0);const b=x.map((E,R)=>({i:R,frac:E-Math.floor(E)})).sort((E,R)=>R.frac-E.frac);let j=0;for(;y<f&&j<b.length;)S[b[j].i]+=1,y+=1,j++;const T=S.map((E,R)=>({i:R,v:E})).sort((E,R)=>R.v-E.v);let O=0;for(;y>f&&O<T.length;)S[T[O].i]>1&&(S[T[O].i]-=1,y-=1),O++}return{items:t.map(x=>{if(x.locked)return x;if(x.fieldId===a)return{...x,weight:m};const y=d.findIndex(b=>b.fieldId===x.fieldId);return{...x,weight:S[y]}}),clamped:h,maxAllowed:u,lockedTotal:i,locksFillBudget:!1}}function PZ(t){if(t.length===0)return t;const a=t.filter(c=>c.locked),s=t.filter(c=>!c.locked),r=a.reduce((c,d)=>c+d.weight,0);if(s.length===0)return t;const n=Math.max(0,100-r);if(n<=s.length)return t.map(c=>c.locked?c:{...c,weight:1});const i=s.reduce((c,d)=>c+d.weight,0);let l;if(i===0){const c=Math.floor(n/s.length);l=s.map((d,p)=>p===0?n-c*(s.length-1):c)}else{const c=s.map(f=>f.weight/i*n);l=c.map(f=>Math.max(1,Math.floor(f)));let d=l.reduce((f,v)=>f+v,0);const p=c.map((f,v)=>({i:v,frac:f-Math.floor(f)})).sort((f,v)=>v.frac-f.frac);let u=0;for(;d<n&&u<p.length;)l[p[u].i]+=1,d+=1,u++;const m=l.map((f,v)=>({i:v,v:f})).sort((f,v)=>v.v-f.v);let h=0;for(;d>n&&h<m.length;)l[m[h].i]>1&&(l[m[h].i]-=1,d-=1),h++}return t.map(c=>{if(c.locked)return c;const d=s.findIndex(p=>p.fieldId===c.fieldId);return{...c,weight:l[d]}})}function OZ(t){const a={};return t.forEach(s=>{s.locked?a[s.fieldId]={weight:s.weight,locked:!0}:a[s.fieldId]=s.weight}),a}function MM(t){if(typeof t=="number"&&Number.isFinite(t))return{weight:t,locked:!1};if(t&&typeof t=="object"){const a=t.weight,s=t.locked;if(typeof a=="number"&&Number.isFinite(a))return{weight:a,locked:!!s}}return null}function LZ(t){if(t===0)return[];if(t===1)return[100];if(t===2)return[60,40];if(t===3)return[50,30,20];if(t===4)return[40,30,20,10];if(t===5)return[35,25,20,12,8];const a=Array.from({length:t},(i,l)=>Math.pow(.7,l)),s=a.reduce((i,l)=>
53i+l,0),r=a.map(i=>Math.round(i/s*100)),n=100-r.reduce((i,l)=>i+l,0);return r[0]+=n,r}function DZ(t){return[...t].sort((a,s)=>a.rank-s.rank)}function Mj(t){const a=t.map((n,i)=>({...n,rank:i+1})),s=LZ(a.length),r=a.map((n,i)=>n.locked?n:{...n,weight:s[i]||1});return PZ(r)}function kZ({boostItems:t,onBoostItemsChange:a,orderId:s,onSave:r,onReset:n,embedded:i=!1}){const[l,c]=o.useState(!0),[d,p]=o.useState(!1),[u,m]=o.useState(null),h=o.useRef(null),f=o.useMemo(()=>DZ(t),[t]),v=f.length>=z0,S=o.useMemo(()=>f.filter(C=>C.locked).reduce((C,F)=>C+F.weight,0),[f]),N=f.filter(C=>!C.locked).length,x=N>0&&100-S<=N;o.useEffect(()=>()=>{h.current&&clearTimeout(h.current)},[]);const y=o.useCallback((C,F)=>{m({fieldId:C,lockedTotal:F}),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>m(null),2400)},[]),b=o.useCallback(C=>{a(Mj(C))},[a]),j=o.useCallback(C=>{const F=t.filter(A=>A.fieldId!==C);a(Mj(F))},[t,a]),T=o.useCallback((C,F)=>{if(f.length>=z0)return;const A=[...f,{fieldId:C,label:F,weight:1,rank:f.length+1,locked:!1}];a(Mj(A))},[f,a]),O=o.useCallback(()=>{m(null),n?n():a([{fieldId:"proximity",label:"Distance",weight:35,rank:1,locked:!1},{fieldId:"gla",label:"GLA",weight:35,rank:2,locked:!1},{fieldId:"bedsBaths",label:"Bed/Bath",weight:30,rank:3,locked:!1}])},[a,n]),E=o.useCallback((C,F)=>{const A=wZ(f,C,F);A.clamped&&y(C,A.lockedTotal);const M=[...A.items].sort((B,oe)=>oe.weight-B.weight).map((B,oe)=>({...B,rank:oe+1}));a(M)},[f,a,y]),R=o.useCallback(C=>{const F=f.map(A=>A.fieldId===C?{...A,locked:!A.locked}:A);a(F),m(null)},[f,a]),G=o.useMemo(()=>mC.filter(C=>!t.some(F=>F.fieldId===C.id)).sort((C,F)=>C.label.localeCompare(F.label)),[t]),U=i?"auto":l?280:32;return e.jsxs(Kh.div,{className:Q("bg-white border border-slate-200 flex flex-col",i?"relative rounded-lg overflow-hidden max-h-[62vh]":"absolute bottom-0 left-0 right-0 border-x-0 border-b-0 shadow-[0_-4px_12px_rgba(0,0,0,0.06)] z-10"),animate:{height:U},transition:{type:"spring",damping:25,stiffness:300},"data-testid":"boost-panel",children:[e.jsxs("div",{onClick:()=>c(!l),className:"h-[32px] px-5 flex items-center justify-between shrink-0 bg-[#072034] hover:bg-[#0a2f4c] transition-colors cursor-pointer",role:"button",tabIndex:0,"data-testid":"button-toggle-boost",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nL,{size:12,className:"text-[#C5A572]"}),e.jsx("span",{className:"text-[11px] font-bold text-white",children:"Comp Search Priorities"}),e.jsxs("span",{className:"text-[9px] bg-white/15 text-white/70 px-1.5 py-0.5 rounded-full font-medium",children:[t.length," ranked · 100%"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:C=>{C.stopPropagation(),r?.(t)},className:"flex items-center gap-1 px-2.5 py-1 rounded text-[10px] font-bold transition-colors bg-white/15 text-white/80 hover:bg-white/25 hover:text-white border border-white/10","data-testid":"button-save-boost",children:[e.jsx(ZO,{size:10}),"Save as Default"]}),e.jsx(Du,{size:14,className:Q("text-white/50 transition-transform",!l&&"rotate-180")})]})]}),l&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"flex-1 grid grid-cols-[repeat(auto-fit,minmax(min(100%,320px),1fr))] overflow-y-auto min-h-0 px-4 py-2 gap-4","data-testid":"boost-responsive-layout",children:[e.jsxs("div",{className:"flex flex-col min-w-0 min-h-[220px]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-slate-400",children:"Drag to reorder · Slide to adjust % · Lock to pin"}),e.jsxs("button",{onClick:()=>p(!d),className:Q("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors",d?"bg-blue-50 text-blue-600 border border-blue-200":"text-slate-400 hover:text-slate-600 hover:bg-slate-100"),"data-testid":"button-boost-guide",children:[e.jsx(on,{size:10}),d?"Hide":"?"]})]}),e.jsxs("button",{onClick:O,className:"flex items-center gap-1 text-[10px] font-medium text-slate-500 hover:text-slate-800 transition-colors px-2 py-0.5 rounded hover:bg-slate-100","data-testid":"button-reset-boost",children:[e.jsx(bg,{size:10})," Reset"]})]}),x&&e.jsxs("div",{className:"mb-1.5 px-2 py-1 rounded bg-amber-50 border border-amber-200 text-[10px] text-amber-700 flex items-center gap-1.5","data-testid":"boost-locks-fill-warning",children:[e.jsx(Hr,{size:10}),"Locked items take ",S,"% — unlocked items pinned at 1%. Unlock one to free budget."]}),e.jsxs(u2,{axis:"y",values:f,onReorder:b,className:"space-y-1 flex-1 overflow-y-auto",children:[e.jsx(I0,{children:f.map((C,F)=>{const A=C.weight,M=!!C.locked,B=u?.fieldId===C.fieldId;return e.jsxs(p2,{value:C,initial:{opacity:0,y:6}
53,animate:{opacity:1,y:0},exit:{opacity:0,scale:.95},transition:{duration:.15},className:Q("flex items-stretch bg-white border rounded shadow-sm hover:shadow transition-shadow group relative z-0",M?"border-[#C5A572]/40 bg-[#C5A572]/5":"border-slate-200 hover:border-slate-300"),"data-testid":`boost-rank-item-${C.fieldId}`,children:[e.jsx("div",{className:Q("flex items-center justify-center w-6 border-r rounded-l",M?"border-[#C5A572]/30 bg-[#C5A572]/10 text-[#A18A60] cursor-not-allowed":"border-slate-100 bg-slate-50 cursor-grab active:cursor-grabbing text-slate-400 group-hover:text-slate-600"),children:e.jsx(pN,{size:12})}),e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-2.5 py-2",children:[e.jsxs("div",{className:"w-5 text-[10px] font-bold text-slate-400 shrink-0",children:["#",F+1]}),e.jsx("div",{className:"text-[12px] font-semibold text-slate-800 w-[70px] shrink-0 truncate",children:C.label}),e.jsxs("div",{className:"flex-1 flex items-center gap-2 min-w-0",children:[e.jsx("input",{type:"range",min:1,max:f.length===1?100:100-(f.length-1),value:A,disabled:M,onChange:oe=>{oe.stopPropagation(),E(C.fieldId,parseInt(oe.target.value,10))},onPointerDown:oe=>oe.stopPropagation(),className:Q("flex-1 h-2 appearance-none rounded-full accent-[#C5A572] bg-slate-200","[&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-[#C5A572] [&::-webkit-slider-thumb]:border-2 [&::-webkit-slider-thumb]:border-white [&::-webkit-slider-thumb]:shadow-md","[&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-[#C5A572] [&::-moz-range-thumb]:border-2 [&::-moz-range-thumb]:border-white [&::-moz-range-thumb]:shadow-md",M?"opacity-40 cursor-not-allowed [&::-webkit-slider-thumb]:cursor-not-allowed [&::-moz-range-thumb]:cursor-not-allowed":"cursor-pointer [&::-webkit-slider-thumb]:cursor-grab [&::-webkit-slider-thumb]:active:cursor-grabbing [&::-moz-range-thumb]:cursor-grab"),"data-testid":`slider-weight-${C.fieldId}`}),e.jsxs("span",{className:Q("w-[36px] text-[12px] font-bold tabular-nums text-right shrink-0",M?"text-[#A18A60]":"text-[#C5A572]"),"data-testid":`text-weight-${C.fieldId}`,children:[A,"%"]})]})]}),e.jsx("button",{onClick:()=>R(C.fieldId),"aria-pressed":M,"aria-label":M?`Unlock ${C.label}`:`Lock ${C.label}`,title:M?`Unlock ${C.label} (${A}%)`:`Lock ${C.label} at ${A}%`,className:Q("w-7 flex items-center justify-center border-l transition-colors",M?"text-[#A18A60] bg-[#C5A572]/10 hover:bg-[#C5A572]/20 border-[#C5A572]/30":"text-slate-300 hover:text-[#A18A60] hover:bg-[#C5A572]/10 border-slate-100"),"data-testid":`button-lock-boost-${C.fieldId}`,children:M?e.jsx(Hr,{size:11}):e.jsx(lf,{size:11})}),e.jsx("button",{onClick:()=>j(C.fieldId),className:"w-6 flex items-center justify-center text-slate-300 hover:text-red-500 hover:bg-red-50 border-l border-slate-100 transition-colors rounded-r","data-testid":`button-remove-boost-${C.fieldId}`,children:e.jsx(ur,{size:12})}),B&&e.jsxs("div",{className:"absolute -top-7 right-0 px-2 py-1 rounded bg-slate-800 text-white text-[10px] font-medium shadow-md whitespace-nowrap z-30 flex items-center gap-1","data-testid":`hint-clamp-${C.fieldId}`,children:[e.jsx(Hr,{size:9}),"Locked items take ",u?.lockedTotal,"% — unlock one to go higher"]})]},C.fieldId)})}),f.length===0&&e.jsx("div",{className:"py-3 text-center text-slate-400 text-[11px] border-2 border-dashed border-slate-200 rounded","data-testid":"boost-empty-state",children:"Add features from the pool on the right →"})]})]}),e.jsxs("div",{className:"flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("h3",{className:"text-[10px] font-bold uppercase tracking-wider text-slate-400",children:"Available Features"}),v&&e.jsxs("span",{className:"text-[9px] font-medium text-amber-600 bg-amber-50 px-1.5 py-0.5 rounded border border-amber-200","data-testid":"boost-cap-badge",children:["Max ",z0]})]}),e.jsxs("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(112px,1fr))] gap-1.5 content-start","data-testid":"boost-available-grid",children:[e.jsx(I0,{children:G.map(C=>e.jsxs(Kh.button,{initial:{opacity:0,scale:.9}
53,animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},onClick:()=>T(C.id,C.label),disabled:v,title:v?`Remove a priority to add ${C.label}`:C.tooltip,className:Q("flex items-center gap-1 px-2 py-1 rounded-full border text-[10px] font-medium transition-colors text-left whitespace-normal leading-tight min-h-7",v?"bg-slate-50 border-slate-100 text-slate-300 cursor-not-allowed":"bg-slate-100 border-slate-200 text-slate-600 hover:bg-white hover:border-[#C5A572] hover:text-[#C5A572]"),"data-testid":`chip-feature-${C.id}`,children:[e.jsx(un,{size:9}),C.label]},C.id))}),G.length===0&&e.jsx("div",{className:"text-[10px] text-slate-400 italic py-1",children:"All features added"})]})]})]}),e.jsx(I0,{children:d&&e.jsx(Kh.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden shrink-0",children:e.jsx("div",{className:"px-4 py-2 text-[10px] text-slate-600 bg-blue-50/50 border-t border-blue-100",children:e.jsxs("p",{className:"leading-relaxed",children:[e.jsx("strong",{children:"How it works:"})," These priorities control how Echo scores comparable sales. Higher rank = more weight. Drag items to reorder, or use the slider to adjust a percentage — the others will auto-adjust to keep the total at 100%. Click the lock icon on any row to pin its weight; locked items keep their exact value while only unlocked items absorb the redistribution. Add features from the pool or remove with ×."]})})})})]})]})}function Gf(t){const a=String(t?.source||"").toLowerCase();return a.includes("public")||a==="pr"?"PR":a.includes("ai")||a.includes("echo")?"AI":t?.value!=null&&t?.value!==""?"MLS":"Unavailable"}function Po(t){if(t==null||t==="")return;const a=Number(String(t).replace(/[^0-9.-]/g,""));return Number.isFinite(a)&&a>0?a:void 0}function Fj(t){const a=Po(t);if(a)return/acre/i.test(String(t))?Math.round(a*43560):Math.round(a)}function mO(t){const{verifiedSubject:a,propertyData:s,subjectCoordinates:r,subjectElsScore:n,mlsData:i,publicRecordData:l}=t,c=(A,M,B=Po)=>{const oe=B(A);return oe!=null&&oe!==""?{value:oe,source:"Verified"}:{value:B(M?.value),source:Gf(M)}},d=c(a?.bedrooms,s.bedrooms),p=c(a?.bathrooms,s.bathrooms),u=c(a?.gla,s.gla?.value?s.gla:s.squareFeet),m=c(a?.lotSizeAcres?a.lotSizeAcres*43560:void 0,s.lotSize,Fj),h=c(a?.yearBuilt,s.yearBuilt),f=c(a?.garageSpaces,s.garageCars),v=a?.design??s.designStyle?.value,S=a?.design?"Verified":Gf(s.designStyle),N=a?.condition??s.condition?.value,x=a?.quality??s.quality?.value,y=s.basement,b=s.pool,j=s.stories,T=a?.basement??y?.value,O=a?.pool??b?.value,E=O==null||O===""?void 0:/^(true|yes|y|1)$/i.test(String(O)),R=A=>{if(!(A==null||A===""))return/^(true|yes|y|1|pool)$/i.test(String(A).trim())?"Yes":"No"},G=Po(a?.stories??j?.value),U={beds:d.value,baths:p.value,gla:u.value,lotSize:m.value,yearBuilt:h.value,garage:f.value,style:v?String(v):void 0,latitude:r?.lat,longitude:r?.lng,echoLocationScore:n??void 0,conditionRating:N?String(N):void 0,qualityRating:x?String(x):void 0,basement:T?String(T):void 0,pool:E,stories:G},C=(A,M,B)=>{const oe=B?B(M):M;if(!(oe==null||oe===""))return{source:A,value:String(oe),usedForMatching:!1}},F=(A,M,B,oe,ae=[])=>{const D=B!=null&&B!=="",_=D&&oe!=="Unavailable"?{source:oe,value:String(B),usedForMatching:!0}:void 0,$=D?[_,...ae].filter(V=>!!V).filter((V,le,W)=>W.findIndex(me=>me.source===V.source&&me.value===V.value)===le):[],z=new Set($.map(V=>V.value.trim().toLowerCase()));return{fieldId:A,label:M,available:D,value:D?String(B):"Unavailable",source:D?oe:"Unavailable",candidates:$,hasConflict:z.size>1}};return{subject:U,facts:[F("proximity","Location",r?"Subject coordinates":void 0,"Location"),F("gla","GLA",u.value,u.source,[C("MLS",i?.squareFeet??i?.livingArea??i?.gla??s.gla?.alternatives?.mls,Po),C("PR",l?.livingArea??l?.squareFeet??l?.gla??s.gla?.alternatives?.public_record,Po)]),F("els","ELS",n,n!=null?"AI":"Unavailable"),F("bedsBaths","Bed / Bath",d.value!=null||p.value!=null?`${d.value??"—"} / ${p.value??"—"}`:void 0,d.source,[C("MLS",i?.bedrooms!=null||i?.bathrooms!=null?`${Po(i?.bedrooms)??"—"} / ${Po(i?.bathrooms)??"—"}`:void 0),C("PR",l?.bedrooms!=null||l?.bathrooms!=null?`${Po(l?.bedrooms)??"—"} / ${Po(l?.bathrooms)??"—"}`:void 0)]),F("bedrooms","Bedrooms",d.value,d.source,[C("MLS",i?.bedrooms,Po),C("PR",l?.bedrooms,Po)]),F("bathrooms","Bathrooms",p.value,p.source,[C("MLS",i?.bathrooms,Po),C("PR",l?.bathrooms,Po)]),F("lotSize","Lot Size",m.value,m.source,[C("MLS",i?.lotSize,Fj),C("PR",l?.lotSize??(Po(l?.lotAcres)?Po(l?.lotAcres)*43560:void 0),Fj)]),F("yearBuilt","Year Built",h.value,h.source,[C("MLS",i?.yearBuilt,Po),C("PR",l?.yearBuilt,Po)]),F("style","Style",v,S,[C("MLS",i?.style),C("PR",l?.style)]),F("basement","Basement",T,a?.basement?"Verified":Gf(y),[C("MLS",i?.basement),C("PR",l?.basement)]),F("pool","Pool",E==null?void 0:E?"Yes":"No",a?.pool!=null?"Verified":Gf(b),[C("MLS",i?.pool,R),C("PR",l?.pool,R)]),F("stories","Stories",G,a?.stories!=null?"Verified":Gf(j),[C("MLS",i?.stories,Po),C("PR",l?.stories,Po)]),F("condition","Condition",N,a?.condition?"Verified":Gf(s.condition),[C("AI",s.aiPhotoRatings?.condition?.rating)]),F("quality","Quality",x,a?.quality?"Verified":Gf(s.quality),[C("AI",s.aiPhotoRatings?.quality?.rating)]),F("garage","Garage",f.value,f.source,[C("MLS",i?.garageSpaces??i?.garage,Po),C("PR",l?.garageSpaces??l?.garage,Po)])]}}function MZ(t){return!t}function FZ(t){return{garageSpaces:t.garageSpaces,mlsData:t.mlsData,publicRecordData:t.publicRecordData}}const _Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function r0(t){const a=typeof t.snapshotId=="string"?t.snapshotId.trim():"";return _Z.test(a)?a:void 0}function dI(t){const a=t.compSnapshotId??t.snapshotId;
53return typeof a=="string"&&a.trim()?a.trim():void 0}function UZ(t){return t==="dataSource"||t==="DataSource"||t==="dataSources"||t==="DataSources"?"DataSources":t}function hO(t,a){return t===a}function VZ(t){return t.requestGeneration===t.currentGeneration&&t.requestAssignmentId===t.currentAssignmentId&&t.pendingCount===0}async function $Z(t,a){for(;t.size>0;)await Promise.allSettled([...t]);return a()}function BZ(t,a){return a>=t}function Dx(t,a,s,r,n,i={}){const l=t.map(T=>({...T}));if(i.promoteCurrentSale&&a===0){const T=l[0]?.OwnershipTransferTransactionType;(T&&typeof T=="object"&&"value"in T?T.value:T)!=="Sale"&&l.unshift({OwnershipTransferTransactionType:{value:"Sale",source:"user",confidence:"manual",userEdited:!0}})}for(;l.length<=a;)l.push({});const c=l[a][s],d=c&&typeof c=="object"?c:{};if(n==="Delete")return l[a][s]={value:null,source:"user",sourceCandidates:{},userEdited:!0},l;const p=d.sourceCandidates&&typeof d.sourceCandidates=="object"?{...i.candidateSeed??{},...d.sourceCandidates}:{...i.candidateSeed??{}},u={...p,...p.mls===void 0&&p.MLS!==void 0?{mls:p.MLS}:{},...p.public_records===void 0&&p.publicRecord!==void 0?{public_records:p.publicRecord}:{},...p.ai_derived===void 0&&p.ai!==void 0?{ai_derived:p.ai}:{},...p.user===void 0&&p.User!==void 0?{user:p.User}:{}},m=d.source,h=m==="mls"?"mls":m==="public_records"?"public_records":m==="ai_derived"?"ai_derived":m==="comps"?"mls":null,f=h&&u[h]===void 0&&d.value!==void 0&&d.value!==null&&d.value!==""?{...u,[h]:d.value}:u,v=n==="ClearUser"||n?.startsWith("ClearUser:")===!0,S=n?.startsWith("SelectOnly:")===!0,x=(v?n.slice(10):S?n.slice(11):n)?.toLowerCase(),b=(x==="mls"?"mls":x==="publicrecord"||x==="public_records"?"public_records":x==="ai"||x==="ai_derived"?"ai_derived":null)??(S?x==="user"?"user":x==="publicrecord"||x==="public_records"?"public_records":x==="ai"||x==="ai_derived"?"ai_derived":"mls":v?["mls","public_records","ai_derived"].find(T=>{const O=f[T];return O!=null&&O!==""})??"user":"user");if(S)return l[a][s]={...d,value:f[b]??(r===""?null:r),source:b,sourceCandidates:f},l;const j=v?b==="user"?null:f[b]??null:r;return l[a][s]={...d,value:j===""?null:j,confidence:b==="user"?"manual":d.confidence??"high",source:b,sourceCandidates:{...f,...v?{user:null}:{[b]:r===""?null:r}},userEdited:!0},l}function zZ(t,a,s,r,n){let i=t.map(d=>({...d}));const l=s.toLowerCase()==="publicrecord"||s.toLowerCase()==="public_records"?"public_records":s.toLowerCase()==="ai"||s.toLowerCase()==="ai_derived"?"ai_derived":s.toLowerCase()==="user"?"user":"mls",c=["SalesConcessionIndicator","SalesConcessionAmountKnownIndicator","TotalSalesConcessionAmount","SalesConcessionsTypicalToMarketIndicator"];if(l==="user")return i=Dx(i,a,c[0],r==="Clear"?null:r!=="None","User"),i=Dx(i,a,c[1],r==="Clear"?null:r==="Amount","User"),i=Dx(i,a,c[2],r==="Clear"?null:r==="Amount"?n??"":"","User"),Dx(i,a,c[3],r==="Clear"?null:"","User");for(const d of c){const p=i[a]?.[d],u=p&&typeof p=="object"?p:{},h=(u.sourceCandidates&&typeof u.sourceCandidates=="object"?u.sourceCandidates:{})[l]??(u.source===l?u.value:"");i=Dx(i,a,d,h,`SelectOnly:${s}`)}return i}function FM(t){if(!t)return{};const a=t,s=a.sourceCandidates??{};return{...s,...s.mls===void 0&&s.MLS!==void 0?{mls:s.MLS}:{},...s.public_records===void 0&&s.publicRecord!==void 0?{public_records:s.publicRecord}:{},...s.ai_derived===void 0&&s.ai!==void 0?{ai_derived:s.ai}:{},...s.user===void 0&&s.User!==void 0?{user:s.User}:{},...s.mls===void 0&&s.MLS===void 0&&a.mlsValue!==void 0?{mls:a.mlsValue}:{},...s.public_records===void 0&&s.publicRecord===void 0&&a.prValue!==void 0?{public_records:a.prValue}:{},...s.ai_derived===void 0&&s.ai===void 0&&a.aiValue!==void 0?{ai_derived:a.aiValue}:{},...s.user===void 0&&s.User===void 0&&a.userValue!==void 0?{user:a.userValue}:{}}}function qZ(t){return Object.fromEntries(t.map(a=>{const s=Object.fromEntries(Object.entries(a.adjustments??{}).flatMap(([r,n])=>{const i=n&&typeof n=="object"&&"value"in n?n.value:n;if(i==null||i==="")return[];const l=Number(i);return Number.isFinite(l)?[[r,l]]:[]}));return Object.prototype.hasOwnProperty.call(s,"catalog_SalesContractDate_auto")&&(Object.prototype.hasOwnProperty.call(s,"SalesContractDate")||(s.SalesContractDate=s.catalog_SalesContractDate_auto),delete s.catalog_SalesContractDate_auto),Ob
53ject.prototype.hasOwnProperty.call(s,"AttachedOrDetached")&&(s.attachedDetached=s.AttachedOrDetached,delete s.AttachedOrDetached),[a.id,s]}))}function zS(t){if(!t||typeof t!="object")return[];const a=t;if(Array.isArray(a.items))return a.items.filter(l=>!!(l&&typeof l=="object"&&typeof l.id=="string"));const s=a.orderedComparables;if(!s||typeof s!="object")return[];const r=s.value;if(!r||typeof r!="object")return[];const n=r;if(!Array.isArray(n.order)||!n.items||typeof n.items!="object")return[];const i=n.items;return n.order.map(l=>typeof l=="string"?i[l]:void 0).filter(l=>!!(l&&typeof l=="object"&&typeof l.id=="string"))}function YZ(t,a){const s=typeof a?.quality=="string"?a.quality.trim():"",r=typeof t.qualityRating=="string"?t.qualityRating.trim():"",n=typeof a?.condition=="string"?a.condition.trim():"",i=typeof t.conditionRating=="string"?t.conditionRating.trim():"",l=[s,r].find(d=>/^Q[1-6]$/.test(d)),c=[n,i].find(d=>/^C[1-6]$/.test(d));return{quality:l,condition:c}}const GZ=["FinalListPriceAmount","ListingStatusType","DaysOnMarketCount","listPrice","listingStatus","daysOnMarket"];function fO(t,...a){const s=Object.assign({},t,...a);for(const r of GZ)t&&Object.prototype.hasOwnProperty.call(t,r)&&(s[r]=t[r]);return s}function MN(t={}){const a=new Set(["Active","Pending","OffMarket","SettledSale"]),s=(l,c)=>l==="ListingStatusType"&&(typeof c!="string"||!a.has(c))?null:c,r=l=>l==="user"?"User":l==="public_record"||l==="public_records"?"PublicRecord":l==="ai"||l==="ai_derived"?"AI":"MLS",n=Object.fromEntries(Object.entries(t).map(([l,c])=>{const d=c&&typeof c=="object"?c:{value:c},p=d.sourceCandidates??{},u={...p,...p.mls===void 0&&p.MLS!==void 0?{mls:p.MLS}:{},...p.public_records===void 0&&p.publicRecord!==void 0?{public_records:p.publicRecord}:{},...p.ai_derived===void 0&&p.ai!==void 0?{ai_derived:p.ai}:{},...p.user===void 0&&p.User!==void 0?{user:p.User}:{}},m=s(l,u.mls),h=s(l,u.public_records),f=s(l,u.ai_derived),v=s(l,u.user),S=l==="SiteInfluences"||l==="SiteViews",N=l===U0||l===Yv||l===Gv,x=r(d.source),y=N?f??(x!=="User"?s(l,d.value):m??h):null,b=N?v??(x==="User"?s(l,d.value):null):null,j=b!=null&&b!=="";return[l,{value:N?j?b:y:s(l,d.value),source:N?j?"User":"AI":x,...N?{sourceCandidates:{...y!=null?{ai_derived:y}:{},...j?{user:b}:{}}}:d.sourceCandidates?{sourceCandidates:d.sourceCandidates}:{},..."sourceIdentities"in d&&d.sourceIdentities?{sourceIdentities:d.sourceIdentities}:{},..."userEdited"in d&&d.userEdited===!0?{userEdited:!0}:{},...!N&&!S&&m!=null?{mlsValue:m}:{},...!N&&!S&&h!=null?{prValue:h}:{},...N&&y!=null?{aiValue:y}:{},...!N&&!S&&f!=null?{aiValue:f}:{},...N&&j?{userValue:b}:{},...!N&&!S&&v!=null?{userValue:v}:{}}]})),i=[["FinalListPriceAmount","listPrice"],["ListingStatusType","listingStatus"],["DaysOnMarketCount","daysOnMarket"]];for(const[l,c]of i){const d=t[l];if(!d||typeof d!="object")continue;const p=d;n[c]={...n[l],value:n[l].value,source:r(p.source)}}if(n.AttachmentType&&!n.attachedDetached){const l=t.AttachmentType,c=l?.source,d=l?.sourceCandidates,{sourceCandidates:p,sourceIdentities:u,...m}=n.AttachmentType;n.attachedDetached={...m,...d?.mls!==void 0?{mlsValue:d.mls}:c==="mls"?{mlsValue:n.AttachmentType.value}:{},...d?.public_records!==void 0?{prValue:d.public_records}:c==="public_records"||c==="public_record"?{prValue:n.AttachmentType.value}:{},...d?.ai_derived!==void 0?{aiValue:d.ai_derived}:c==="ai_derived"||c==="ai"?{aiValue:n.AttachmentType.value}:{},...d?.user!==void 0?{userValue:d.user}:c==="user"?{userValue:n.AttachmentType.value}:{}}}return n}function uI(t){const a=EI(t);return a.record?Object.fromEntries([["OwnershipTransferTransactionAmount","OwnershipTransferTransactionAmount","amount"],["TotalSalesConcessionAmount","TotalSalesConcessionAmount",null],["SaleType","SaleType","terms"],["OwnershipTransferDate","OwnershipTransferDate","date"],["SalesConcessionIndicator","SalesConcessionIndicator",null],["SalesConcessionAmountKnownIndicator","SalesConcessionAmountKnownIndicator",null],["SalesConcessionsTypicalToMarketIndicator","SalesConcessionsTypicalToMarketIndicator",null],["saleTypeOtherDescription","SaleTypeOtherDescription",null]].map(([s,r,n])=>{const i=MN({[r]:a.record?.[r]})[r],l=n?iV(a,n):i?.value;return[s,{...i,value:typeof l=="string"||typeof l=="number"||typeof l=="boolean"?l:""}]})):{}}function HZ(t){if(t==null)return;const a=typeof t=="object"&&t!==null&&"value"in t?t:{value:t,source:"user"};return MN({AttachmentType:a}).attachedDetached}function WZ(t,a,s,r){const n=t&&typeof t=="object"&&"value"in t?t:{},i=r==="MLS"?"mls":r==="PublicRecord"?"public_records":r==="AI"?"ai_derived":"user",l={...n.sourceCandidates&&typeof n.sourceCandidates=="object"?n.sourceCandidates:{},...a?.mlsValue!==void 0?{mls:a.mlsValue}:{},...a?.prValue!==void 0?{public_records:a.prValue}:{},...a?.aiValue!==void 0?{ai_derived:a.aiValue}:{},...a?.userValue!==void 0?{user:a.userValue}:{},[i]:s===""?null:s};return{...n,value:s===""?null:s,confidence:i==="user"?"manual":typeof n.confidence=="string"?n.confidence:"high",source:i,sourceCandidates:l,userEdited:!0}}function KZ(t,a){const s=a.sourceCandidates&&typeof a.sourceCandidates=="object",r=s?a.sourceCandidates:void 0,n=(...i)=>{if(!r)return null;const l=i.find(d=>Object.prototype.hasOwnProperty.call(r,d));if(!l)return null;const c=r[l];return c===void 0?null:c};return{...t,...a,value:a.value,source:a.source,...s?{mlsValue:n("mls","MLS"),prValue:n("public_records","publicRecord","PR"),aiValue:n("ai_derived","ai","AI"),userValue:n("user","User")}:{},hasConflict:!1,isVerified:!0}}const gO={MLS:"mlsValue",PublicRecord:"prValue",AI:"aiValue",User:"userValue"};function QZ(t){if(t==null)return!1;if(typeof t!="string")return!0;const a=t.trim();return a!==""&&a!=="undefined"&&a!=="null"&&a!=="NaN"}function ZZ(t,a={}){const s={[U0]:t[U0],[Yv]:t[Yv],[Gv]:t[Gv]},r=qT(s),n=Object.values(s).filter(c=>QZ(c?.value)).map(c=>c?.source).filter(c=>!!c),i=n.length>0&&n.every(c=>c===n[0])?n[0]:s[U0]?.source??a.source??"AI",l=Object.fromEntries(Object.keys(gO).flatMap(c=>{const d=gO[c],p=Object.fromEntries(Object.entries(s).map(([m,h])=>[m,h?.[d]??(h?.source===c?h.value:void 0)])),u=qT(p);return u?[[d,u]]:[]}));return{...a,...l,value:r||null,source:i}}function xO(t,a,s,r){const n=t&&typeof t=="object"&&"value"in t?t:{},i=n.sourceCandidates&&typeof n.sourceCandidates=="object"?n.sourceCandidates:{},l={...FM(a),...i},c=u=>u==="MLS"||u==="mls"?"mls":u==="PublicRecord"||u==="public_records"?"public_records":u==="AI"||u==="ai_derived"?"ai_derived":"user",d=s===""?null:s;if(r.startsWith("SelectOnly:")){const u=r.slice(11);return{...n,value:d,source:c(u),sourceCandidates:l,userEdited:n.userEdited===!0||c(u)==="user"}}
53if(r.startsWith("ClearUser")){const u={...l,user:null},m=r.split(":")[1],f=(m?[c(m)]:["mls","public_records","ai_derived"]).find(v=>{const S=u[v];return S!=null&&S!==""});return{...n,value:f?u[f]:null,source:f??c(String(n.source??"user")),sourceCandidates:u,userEdited:!0}}const p=c(r);return{...n,value:d,source:p,sourceCandidates:{...l,[p]:d},confidence:p==="user"?"manual":typeof n.confidence=="string"?n.confidence:"high",userEdited:p==="user"||n.userEdited===!0}}function JZ(t,a,s,r){const n=RU(a,s??r)??"MLS",i=s!==void 0;return{value:t,source:n,mlsValue:i?a?.mlsValue:n==="MLS"?t:void 0,prValue:a?.prValue,aiValue:a?.aiValue,userValue:i?a?.userValue:n==="User"?t:void 0,hasConflict:!1,isVerified:n==="User"}}const q0={MLS:"mlsValue",PublicRecord:"prValue",AI:"aiValue",User:"userValue"};function XZ(t,a,s){const r=t?.source==="MLS"||t?.source==="PublicRecord"||t?.source==="AI"||t?.source==="User"?t.source:"User",n={value:t?.value??null,source:r,mlsValue:t?.mlsValue,prValue:t?.prValue,aiValue:t?.aiValue,userValue:t?.userValue,hasConflict:!1,isVerified:!0},i=q0[r];if(i&&n[i]===void 0&&(n[i]=t?.value===""?null:t?.value??null),s==="ClearUser"){if(n.userValue=null,t?.source!=="User")return n;for(const[d,p]of[["MLS","mlsValue"],["PublicRecord","prValue"],["AI","aiValue"]]){const u=n[p];if(u!=null&&u!=="")return{...n,value:u,source:d,hasConflict:!1,isVerified:!0}}return{...n,value:"",source:"User",hasConflict:!1,isVerified:!0}}const l=q0[s];return l&&(n[l]=a===""?null:a),{...n,value:a,source:s==="MLS"||s==="PublicRecord"||s==="AI"||s==="User"?s:"User",hasConflict:!1,isVerified:!0}}function eJ(t,a,s){return{...t?.source?{source:t.source}:{},fields:{...t?.fields??{},[a]:s}}}function tJ(t,a,s,r,n=!1){if(r&&n&&s==="User"&&a===""){const l={...t??{},userValue:null},c=l.aiValue;if(c!=null&&c!=="")return{...l,value:c,source:"AI"}}if(r&&s.startsWith("Select:")){const l=s.slice(7);return{...t??{},value:a,source:l}}if(r&&s.startsWith("ClearUser")){const l={...t??{},userValue:null};if(t?.source==="User"){const c=s.split(":")[1],d=q0[c];if(c&&d){const p=l[d];return{...l,value:p!=null&&p!==""?p:a,source:c}}for(const[p,u]of[["MLS","mlsValue"],["PublicRecord","prValue"],["AI","aiValue"]]){const m=l[u];if(m!=null&&m!=="")return{...l,value:m,source:p}}}return{...l,value:t?.source==="User"?"":typeof t?.value=="string"||typeof t?.value=="number"?t.value:a,source:typeof t?.source=="string"?t.source:"User"}}const i={};if(r){const l=q0[typeof t?.source=="string"?t.source:""];l&&t?.value!==void 0&&t.value!==null&&(i[l]=t.value);const c=q0[s];c&&(i[c]=s==="User"&&a===""?null:a)}return{...t??{},...i,value:a,source:s}}function ld(...t){for(const a of t){if(a==null||a==="")continue;const s=Number(a);if(Number.isFinite(s)&&s>0)return s}}function bO(...t){for(const a of t){if(a==null||a==="")continue;const s=Number(a);if(Number.isFinite(s))return s}}function aJ({compSnapshotId:t,snapshot:a,photos:s,scores:r}){const n=a.mlsData??{},i=a.publicRecordData??{},l=n.rawMlsStatus??n.status??a.rawMlsData?.rawMlsStatus??a.rawMlsData?.StandardStatus??a.rawMlsData?.standardStatus??a.mlsStatus??null,c=(s??[]).map(u=>u.originalUrl??u.url??u.src??u.imageUrl).filter(u=>typeof u=="string"&&u.trim()!==""),d=bO(a.latitude,n.latitude),p=bO(a.longitude,n.longitude);return{...a,id:t,snapshotId:t,mlsNumber:a.mlsNumber,address:a.address??"",fullAddress:[a.address,a.city,a.state,a.zipCode].filter(Boolean).join(", "),city:a.city??"",state:a.state??"",zip:a.zipCode??"",price:ld(a.salePrice)??0,saleDate:a.saleDate??void 0,status:a.mlsStatus??"CLSD",rawMlsStatus:l==null?null:String(l),gla:ld(a.sqft,n.squareFeet,n.LivingArea),sqftPR:ld(a.prLivingArea,i.squareFeet,i.livingArea,i.LivingArea),beds:ld(a.bedrooms,n.bedrooms,n.BedroomsTotal),baths:ld(a.bathrooms,n.bathrooms,n.BathroomsTotalInteger),lotSize:ld(a.lotSize,n.lotSize,n.LotSizeSquareFeet),lotSqft:ld(a.lotSize,n.lotSize,n.LotSizeSquareFeet),lotSqftPR:ld(a.prLotSize,i.lotSize,i.LotSizeSquareFeet),yearBuilt:ld(a.yearBuilt,n.yearBuilt,n.YearBuilt),style:a.architecturalStyle??n.style??n.ArchitecturalStyle??i.style??void 0,garageSpaces:ld(a.garageSpaces,n.garageSpaces),stories:ld(a.stories,n.stories),basement:a.basement??n.basement??i.basement??void 0,hasPool:a.hasPool??n.pool??i.pool??void 0,hasFireplace:a.hasFireplace??n.fireplace??i.fireplace??void 0,view:a.view??n.view??i.view??void 0,coordinates:d!==void 0&&p!==void 0?{lat:d,lng:p}:void 0,photos:c,photoUrl:c[0]??a.primaryPhotoUrl,qualityRating:r?.qualityRating??a.btQualityRating,conditionRating:r?.conditionRating??a.btConditionRating??a.aiConditionRating,echoLocationScore:r?.echoLocationScore??void 0,selectionState:"selected"}}function yO(t){const a=t&&typeof t=="object"&&!Array.isArray(t)&&"value"in t?t.value:t;return a===!0||a==="true"?!0:a===!1||a==="false"?!1:null}function n0(t,a){const s=new Map;for(const r of a){const n=dI(r),i=typeof r.rawMlsStatus=="string"&&r.rawMlsStatus.trim()?r.rawMlsStatus.trim():typeof r.status=="string"?r.status.trim():"";n&&i&&!s.has(n)&&s.set(n,i)}return t.map(r=>{const n=dI(r),i=n?s.get(n):void 0;return i?{...r,rawMlsStatus:i}:r})}function sJ(t,a){const s=ld(t.sqft),r=ld(t.sqftPR),n=ld(t.btNormalizedGla),i=a==="ai"?n??s??r:a==="public-record"?r:s;return{id:t.id,beds:t.beds??void 0,baths:t.baths??void 0,gla:i,lotSize:t.lotSqft??void 0,yearBuilt:t.yearBuilt??void 0,style:t.style??void 0,pool:t.hasPool??t.mlsData?.hasPool??t.publicRecordData?.hasPool??void 0,garage:t.garageSpaces??void 0,basement:t.basement??void 0,fireplace:t.hasFireplace??t.mlsData?.hasFireplace??t.publicRecordData?.fireplace??void 0,view:t.view??t.mlsData?.view??t.publicRecordData?.view??void 0,stories:t.stories??void 0,latitude:t.coordinates?.lat,longitude:t.coordinates?.lng,echoLocationScore:t.echoLocationScore?.score,conditionRating:t.conditionRating??void 0,qualityRating:t.qualityRating??void 0}}function _j(t,a){return t?{gridCount:Math.max(0,t.gridCount+a),selectedCount:Math.max(0,t.selectedCount+a),available:Math.max(0,t.available-a)}:null}function rJ(t){if(t.enableUad36&&t.compSelectionMode==="sale")return!0;const a=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return!t.snapshotId||!a.test(t.snapshotId)}function SO(t,a){const s=new Set([a.id,a.snapshotId].filter(r=>typeof r=="string"&&r.length>0));return t.filter(r=>!s.has(r.id)&&!(r.snapshotId&&s.has(r.snapshotId)))}function nJ(t,a){return a?.snapshotId?t.some(s=>s.snapshotId===a.snapshotId):!1}function _M(t){const a=t.mlsData,s=[t.mlsNumber,a?.mlsNumber,a?.MlsListingNumber,a?.ListingId].find(r=>r!=null&&String(r).trim()!=="");return s==null?t.id:String(s)}function iJ(t){const a=t.mlsData,s=[t.mlsNumber,a?.mlsNumber,a?.MlsListingNumber,a?.ListingId].find(r=>r!=null&&String(r).trim()!=="");return s==null?void 0:String(s).trim()}function oJ(t){const a=_M(t);return t.canonicalSnapshotId&&a===t.id?void 0:a}function i0(t){const a=t.mlsData,s=[t.mlsBoard,a?.mlsBoard,a?.MlsBoard,a?.boardName,a?.OriginatingSystemName].find(r=>r!=null&&String(r).trim()!=="");return s==null?void 0:String(s).trim()}function lJ(t,a){return a.snapshotId?`/api/uad36/comparables/${encodeURIComponent(t)}/memberships/${encodeURIComponent(a.snapshotId)}`:`/api/uad36/comparables/${encodeURIComponent(t)}/items/${encodeURIComponent(a.id)}`}function vO(t,a){const s=Array.isArray(t)?t.filter(i=>!!(i&&typeof i=="object")):[],r=a.includes("None")?["None"]:a.filter(i=>i!=="None");if(r.length===0)return[];const n=new Set;return r.map((i,l)=>{const c=s.findIndex((p,u)=>!n.has(u)&&p.statusType===i),d=c>=0?c:!n.has(l)&&l<s.length?l:-1;return d>=0&&n.add(d),{...d>=0?s[d]:{},statusType:i}})}const cJ=new Map;function dJ(t,a){cJ.get(t)?.forEach(s=>s(a))}const uJ=new Map;function pJ(t,a){uJ.get(t)?.forEach(s=>s(a))}function Im(t,a,s,r){const n=t.get(a)??Promise.resolve();let i;const l=async()=>{const c=await s();t.get(a)===i&&r(c)};return i=n.then(l,l),t.set(a,i),i.finally(()=>{t.get(a)===i&&t.delete(a)}).catch(()=>{}),i}const Uj=[500,1e3,2e3,4e3,8e3,14e3];function Vj(t){return t.map(a=>{const s=a.fields??{},r=O=>{const E=s[O];return E&&typeof E=="object"&&"value"in E?E.value:E},n=(...O)=>{for(const E of O){const R=r(E);if(R!=null&&String(R).trim())return String(R)}return""},i=(a.photos??[]).map(O=>O.ImageFileLocationIdentifier).filter(O=>typeof O=="string"&&O.trim()!==""),l={...MN(s),...a.fields?.DataSources?{...(()=>{const O=GL(a.fields.DataSources,{allowIncomplete:!0});return{dataSource:{value:HL(O),source:O[0]?.source==="mls"?"MLS":O[0]?.source==="public_records"?"PublicRecord":"User",dataSources:O}}})()}:{},...r("EnergyFeatures")?{EnergyFeatures:{value:r("EnergyFeatures"),source:"User"}}:{},...r("PropertyAmenities")?{PropertyAmenities:{value:r("PropertyAmenities"),source:s.PropertyAmenities&&typeof s.PropertyAmenities=="object"&&"source"in s.PropertyAmenities&&typeof s.PropertyAmenities.source=="string"?s.PropertyAmenities.source:"User"}}:{}},c=[["AssociationDuesAmount","AssociationChargeAmount"],["AmenityTypes","ProjectCommonAmenityType"],["SpecialAssessmentCharges","AssociationSpecialAssessmentStatusType"],["PropertyInProjectIndicator","PropertyInProjectIndicator"],["SameProjectAsSubjectIndicator","SameProjectAsSubjectIndicator"],["ProjectName","ProjectName"]];for(const[O,E]of c){const R=l[O];R!==void 0&&!(E in l)&&Object.assign(l,{[E]:R})}const d=n("AddressLineText"),p=n("CityName"),u=n("StateCode"),m=n("PostalCode"),h=EI(a.transferHistory),f=uI(a.transferHistory);Object.assign(l,f);const v=h.record?h.amount??0:Number(r("SalePrice")),S=s.VehicleStorageItems,N=r("VehicleStorageItems"),x=a.customRows,y=Object.fromEntries(Object.entries(x??{}).map(([O,E])=>[O,String(E&&typeof E=="object"&&"value"in E?E.value??"":E??"")])),b=Object.fromEntries((a.transferHistory??[]).flatMap((O,E)=>Object.entries(O).map(([R,G])=>{const U=G&&typeof G=="object"&&"value"in G?G:{value:G,source:"mls"},C=U.source==="user"?"User":U.source==="public_record"||U.source==="public_records"?"PublicRecord":U.source==="ai"||U.source==="ai_derived"?"AI":"MLS";return[`saleHistory${E}_${R}`,{value:U.value??null,source:C}]}))),j=r("SaleHistoryDataSource"),T=a.transferHistory;return{id:a.id,snapshotId:a.compSnapshotId??void 0,mlsNumber:a.mlsNumber??void 0,mlsData:a.mlsNumber?{mlsNumber:a.mlsNumber}
53:void 0,address:d,fullAddress:[d,p,u,m].filter(Boolean).join(", "),city:p,state:u,zip:m,price:Number.isFinite(v)?v:0,saleDate:n("SaleDate")||void 0,status:"CLSD",photoUrl:i[0],photos:i,transferHistory:Array.isArray(T)?T:[],vehicleStorageItems:Array.isArray(N)?N.slice(0,12):[],vehicleStorageSource:S&&typeof S=="object"&&"source"in S&&typeof S.source=="string"?S.source:void 0,vehicleStorageUserEdited:!!S&&typeof S=="object"&&"userEdited"in S&&S.userEdited===!0,vehicleStorageCustomRows:y,selectionState:"selected",gridFieldOverrides:{...l,...f,...b,...j!==void 0?{saleHistoryDataSource:{value:j,source:"MLS"}}:{}}}})}function mJ(t){const a=t.match(/^Comp(\d+)SaleHistory(\d+)_([A-Za-z0-9]+)$/);if(!a)return null;const s=Number(a[1]),r=Number(a[2]);return!Number.isInteger(s)||s<1||!Number.isInteger(r)||r<0||r>Vm||!mg.includes(a[3])?null:{slot:s,historyIndex:r,fieldName:a[3]}}function hC(t,a){const s=mJ(a);if(!s)return null;const r=t[s.slot-1];return r?{comparable:r,historyIndex:s.historyIndex,fieldName:s.fieldName}:null}function hJ(t,a){const s=hC(t,a);if(!s)return;const r=s.comparable.transferHistory?.[s.historyIndex]?.[s.fieldName];return r&&typeof r=="object"&&"value"in r?r.value:r}function fJ(t,a,s){const r=hC(t,a);if(!r)return null;const n=(r.comparable.transferHistory??[]).map(i=>({...i}));for(;n.length<=r.historyIndex;)n.push({});return n[r.historyIndex]={...n[r.historyIndex],[r.fieldName]:s},{itemId:r.comparable.id,transferHistory:n}}const Hf=new Set(["ACTV","NEW","PCHG","BOMK","RACT","PEND","CTG","HOLD","CSOON","AUC"]);function Eo(t){if(t==null)return null;const a=typeof t=="number"?t:Number(t);return!isNaN(a)&&a>0?a:null}function qS(t,a,s){console.warn(`[PropertyLab] Legacy market lock restore (${t}/${a}) produced no usable cards — ${s?.resultIds?.length??0} resultIds, ${s?.salesData?.length??0} salesData rows. Clearing lockedMarketPropertyCards so the user can re-lock.`)}function YS(t){let a=t.address||"";!a&&t.fullAddress&&(a=t.fullAddress.split(",")[0]||"");const s=a.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),r=(t.city||"").toLowerCase().replace(/[^a-z0-9]/g,""),n=(t.state||"").toLowerCase().replace(/[^a-z]/g,""),i=(t.zip||"").replace(/[^0-9]/g,"").slice(0,5);return s&&(r||i)?`${s}-${r||i}-${n}`:s&&n?`${s}-${n}`:""}function gJ({propertyData:t,subjectAddress:a,subjectCoordinates:s,assignmentId:r,effectiveDate:n,subjectState:i,subjectZipCode:l,subjectPropertyType:c,subjectProviderData:d,subjectProviderReplacementVersion:p=0,subjectHistoryCandidates:u=[],inspectionImport:m,onBack:h,onNext:f,onProceedToCleanup:v,onCleanedCompsChange:S,initialCleanupMode:N=!1,onCleanupModeChange:x,onNeighborhoodInfoChange:y,onNeighborhoodAiGenerated:b,initialNeighborhoodInfo:j,compIntentState:T,boostItems:O,onApplyBoostItems:E,onSaveBoostDefault:R,onResetBoostItems:G,enableStr:U=!1,enableUad36:C=!1,evalGridProfile:F=!1,evalCompGridRows:A=[],evalSubjectVehicleStorageItems:M=[],evalSubjectVehicleStorageExplicitNone:B=!1,evalSubjectVehicleStorageLegacyLabel:oe="",evalSubjectVehicleStorageHasLegacyOverride:ae=!1,onEvalSubjectVehicleStorageEvidenceChange:D,evalCustomComparisonFactors:_=[],onEvalCustomComparisonFactorsChange:$,subjectPhotos:z=[],initialSelectedComps:V,initialAvmResults:le,onAvmResultsChange:W,initialSelectedAvmComps:me,onSelectedAvmCompsChange:Z,initialVerifiedSubject:pe,onVerifiedSubjectChange:se,initialMarketLocked:fe,onMarketLockedChange:ue,initialSubMarketLocked:be,onSubMarketLockedChange:H,initialLocksRow:ye,onLockDataChanged:de,initialSubMarketPropertyIds:ge,onSubMarketPropertyIdsChange:Be,enableDualScenario:He=!1,initialCompScenarioTags:Ie,onCompScenarioTagsChange:ce,initialAfterRepairedOverrides:Pe,onOpenSubjectDrawer:We,onGridAdjustmentChange:Re,persistedGridAdjustments:ne,onGridCompFieldEdit:Me,saleHistoryGetValue:lt,saleHistoryGetSource:Tt,saleHistorySetValue:je,onCsvSubjectImport:Le,onSubjectGridFieldEdit:ut,initialCachedLabState:st,onLabStateChange:Xt,lateElsCache:ua,lateCompAiCache:Oa,lateAllCachedSales:Xa,cachesPending:qa=!1,onRequestImmediateSave:os,strRentalComps:ya,onMapSnapshotChange:At,onReg
53isterActions:Fe,onAvmLoadingChange:Oe,onLockedTimeAdjRateChange:rt,onMarketPropertiesUpdate:$t,onSubmarketPropertiesUpdate:na,headerSearchQuery:zt="",wizardPreloadStatus:Ua,wizardIsPreloading:Ce,wizardPreloadComplete:St,maxSalesComps:vt=24}){const{toast:Ve}=hc(),{profile:sa}=ly(),{preferences:tt}=_I(),{isLoading:it}=a$(null),Je=d?.propertyDetails,ht=d?.listingDetails,Kt=Ua??{status:"idle"},Sa=Ce??!1,Qt=St??!1,[ea,tr]=o.useState(!1),[ir,zs]=o.useState(!1),[pr,$e]=o.useState([]),Ot=o.useCallback(()=>{$e((O||[]).map(g=>({...g}))),zs(!0)},[O]),_e=(()=>{switch(Kt.currentStage){case"queued":return"Preparing…";case"searching":return"Searching MLS for nearby comps…";case"caching":return"Caching property records…";case"scoring_els":return"Scoring nearby locations…";case"analyzing_photos":return"Analyzing listing photos…";case"normalizing":return"Normalizing comparable details…";case"almost_ready":return"Almost ready…";case"ready":return"Finishing background work…";case"completed":return null;default:return null}})();o.useRef(null);const ma=!!st,pt=g=>{const I=new Set;return g.filter(k=>{const L=k.mlsNumber||k.mlsData?.mlsNumber||k.mlsData?.MlsListingNumber||k.mlsData?.ListingId,Y=[k.snapshotId,k.id,L].filter(Boolean);return Y.some(K=>I.has(K))?!1:(Y.forEach(K=>I.add(K)),!0)})},[re,qe]=o.useState(()=>{if(st){const g=st.labState;if(V&&V.length>0){const Y=g._cachedGridOverrides?.length?g._cachedGridOverrides:g.selectedComps??[],K=pt(V).map(te=>{const q=te.mlsNumber||te.mlsData?.mlsNumber||te.mlsData?.MlsListingNumber,ie=Y.find(ee=>ee.id===te.id||ee.snapshotId&&ee.snapshotId===te.snapshotId||q&&(ee.mlsNumber===q||ee.mlsData?.mlsNumber===q||ee.mlsData?.MlsListingNumber===q));return!ie?.gridFieldOverrides||Object.keys(ie.gridFieldOverrides).length===0?te:{...te,gridFieldOverrides:fO(te.gridFieldOverrides,ie.gridFieldOverrides)}});return{...g,selectedComps:K}}const k=(g.selectedComps??[]).filter(L=>!!(L?.mlsData||L?.address||L?.status));return{...g,selectedComps:pt(k)}}return V&&V.length>0?{...fw,selectedComps:pt(V)}:fw}),Ze=o.useRef(!1);o.useEffect(()=>{Ze.current||!U||(Ze.current=!0,qe(g=>g.filters.propertyTypes?.includes("STR")&&g.filters.strOnly?g:{...g,filters:{...g.filters,propertyTypes:["STR"],strOnly:!0}}))},[U]);const[It,Ne]=o.useState(""),[Ue,ct]=o.useState(!1),[xt,Na]=o.useState(!1),[qt,la]=o.useState(null),[fs,ps]=o.useState(!1),[Te,at]=o.useState(0),[yt,nt]=o.useState(0),[Wt,ts]=o.useState(!1),[gs,Va]=o.useState(!1),[Mr,xs]=o.useState(null),Sn=o.useRef(null),ds=o.useRef(null),Zt=o.useRef(null),Rs=o.useCallback(()=>{if(Zt.current){try{Zt.current.dismiss()}catch{}Zt.current=null}},[]),[Os,qs]=o.useState(!1),[Ks,Tn]=o.useState(st?.mapCenter??null),[Bn,Ka]=o.useState(st?.mapZoom),Ee=o.useRef(ma),dt=o.useRef(null),[ot,xa]=o.useState(!1),[rs,Gs]=o.useState(st?.viewMode??"cards"),[bs,ba]=o.useState(()=>{if(st?.labViewMode)return st.labViewMode;const g=st?.viewMode??"cards",I=st?.showMapPanel!==!1;return g==="list"?I?"list-map":"list":I?"cards-map":"cards"}),[ln,zn]=o.useState(null),fd=o.useRef(null);fd.current=ln;const[go,Zd]=o.useState(!1),[Mu,hp]=o.useState(!0),[qn,gd]=o.useState(st?.comparisonDataSource??"ai"),[Bi,xd]=o.useState(st?.columnSort),[Jp,hf]=o.useState(55),_c=o.useRef(null),bd=o.useRef("cards"),In=o.useRef(bs),Yn=F$(r),{data:Qa,isFetched:Xi}=DG(r),Ri=o.useRef(0),yd=p>0&&Ri.current!==p,Zo=o.useRef(z||[]),Tg=Xi?Qa||[]:z||[],Xp=!yd&&Tg.length===0?Zo.current:Tg,ni=QP(d?.propertyDetails,d?.listingDetails,Xp,yd?p:0);Zo.current=ni;const ki=(bs==="map"||bs==="cards-map"||bs==="list-map")&&!Yn.isPopoutOpen,fp=o.useRef(!1);ki&&(fp.current=!0);const Ol=ki||fp.current&&!Yn.isPopoutOpen,$m=o.useRef(0);o.useEffect(()=>{$m.current=Date.now(),Gs(bs==="list"||bs==="list-map"?"list":"cards")},[bs]);const[Jd,Ig]=o.useState(st?.visibleColumns??vk),Cg=o.useCallback(()=>{sa?.id&&fetch(`/api/profile/${sa.id}/defaults`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({labColumnOrder:Jd})}).then(g=>{g.ok&&Ve({title:"Column layout saved",description:"Your column preferences have been saved as default."})}).catch(()=>{})},[sa?.id,Jd,Ve]),[Sd,ml]=o.useState(null),[Rg,hl]=o.useState("comps"),[ff,vd]=o.use
53State(void 0),[gf,Gn]=o.useState(!1),[zi,em]=o.useState(!1),[Bm,xb]=o.useState(null),[gc,zm]=o.useState(!1),[Nd,Fu]=o.useState("avm"),[Uc,Xd]=o.useState(null),[eu,qm]=o.useState(!1),[Eg,Ym]=o.useState(null),[gy,Vc]=o.useState(null),tm=o.useCallback((g,I)=>{Ym(g),Vc(I&&I.length>0?I:null)},[]),[tu,ii]=o.useState("comps"),[Gm,eo]=o.useState([]),[Wr,$c]=o.useState(null),Bc=o.useRef(null);o.useEffect(()=>{Bc.current=Wr},[Wr]);const _u=o.useRef((()=>{const g={};if(st){const I=st.labState;(I._cachedGridOverrides?.length?I._cachedGridOverrides:st.labState.selectedComps??[]).forEach(L=>{if(!L.gridFieldOverrides||Object.keys(L.gridFieldOverrides).length===0)return;const Y=L.gridFieldOverrides,K=L.snapshotId,te=L.id,q=L.mlsNumber||L.mlsData?.mlsNumber||L.mlsData?.MlsListingNumber;K&&(g[K]=Y),te&&te!==K&&(g[te]=Y),q&&(g[q]=Y)})}return g})());o.useEffect(()=>{re.selectedComps.forEach(g=>{if(!g.gridFieldOverrides||Object.keys(g.gridFieldOverrides).length===0)return;const I=g.gridFieldOverrides,k=g.snapshotId,L=g.id,Y=g.mlsNumber||g.mlsData?.mlsNumber||g.mlsData?.MlsListingNumber;k&&(_u.current[k]=I),L&&L!==k&&(_u.current[L]=I),Y&&(_u.current[Y]=I)})},[re.selectedComps]);const xf={neighborhoodName:{section:"subjectProperty",field:"NeighborhoodName"},SiteInfluenceType:{section:"site",field:"SiteInfluenceType"},ProjectName:{section:"projectInformation",field:"ProjectName"},AssociationChargeAmount:{section:"projectInformation",field:"AssociationChargeAmount"},ProjectCommonAmenityType:{section:"projectInformation",field:"ProjectCommonAmenityType"},AssociationSpecialAssessmentStatusType:{section:"projectInformation",field:"AssociationSpecialAssessmentStatusType"},PropertyInProjectIndicator:{section:"subjectProperty",field:"PropertyInProjectIndicator"},SameProjectAsSubjectIndicator:{section:"projectInformation",field:"SameProjectAsSubjectIndicator"},quality:{section:"improvements",field:"OverallQualityRatingCode"},condition:{section:"improvements",field:"OverallConditionRatingCode"}},No=o.useRef([]),gp=o.useRef(null),xp=o.useRef(Promise.resolve()),wg=o.useRef(0),Pg=o.useRef(new Map),qi=ku(),Jo=o.useCallback(g=>{r&&(gp.current&&clearTimeout(gp.current),gp.current=setTimeout(async()=>{const I=No.current.splice(0);if(I.length===0)return;const k=++wg.current;for(const K of I)Pg.current.set(`${K.section}:${K.field}`,k);const L=xp.current;let Y=()=>{};xp.current=new Promise(K=>{Y=K}),await L;try{await Go(r,fetch(`/api/uad36/section-merge/${r}`,{method:"POST",headers:{"Content-Type":"application/json",...ho(r)},body:JSON.stringify({patches:I})}).then(q=>{if(!q.ok)throw new Error(`Section merge failed (${q.status})`);return q}));const K={};let te=null;for(const q of I)q.section==="improvements"&&q.field==="buildings"&&Array.isArray(q.value)&&oV(r,q.value),q.section==="vehicleStorage"&&q.field==="items"&&typeof q.value=="object"&&q.value!==null&&Array.isArray(q.value.value)&&lV(r,q.value.value),q.section==="energyFeatures"&&typeof q.value=="object"&&q.value!==null&&"value"in q.value&&(K[q.field]=q.value),q.section==="salesComparisonGrid"&&q.field==="visibleRows"&&typeof q.value=="object"&&q.value!==null&&Array.isArray(q.value.value)&&(te=q.value.value);if(Object.keys(K).length>0&&dJ(r,K),te){const q=te;qi.setQueriesData({queryKey:["/api/uad36/prefill",r]},ie=>ie&&{...ie,sections:{...ie.sections,salesComparisonGrid:{...ie.sections?.salesComparisonGrid,visibleRows:{value:q,confidence:"manual",source:"user",userEdited:!0}}}}),pJ(r,q),await qi.invalidateQueries({queryKey:["/api/uad36/prefill",r]})}}catch{const te=I.filter(q=>Pg.current.get(`${q.section}:${q.field}`)===k);No.current.unshift(...te)}finally{Y()}},g))},[r,qi]),[Ll,oi]=o.useState(N),[zc,am]=o.useState("select"),[xo,Yi]=o.useState(st?.hasDrawnShapes??!1),[Og,Xo]=o.useState(fe??!1),[Lg,au]=o.useState(be??!1),Tr=ue?fe??!1:Og,Fr=H?be??!1:Lg,Zl=o.useCallback(g=>{ue?ue(g):Xo(g)},[ue]),qc=o.useCallback(g=>{H?H(g):au(g)},[H]),[bf,sm]=o.useState(null),[rm,nm]=o.useState(null),[Dg,yf]=o.useState({}),[el,Jn]=o.useState(()=>({boundaries:j?.boundaries||"",description:j?.description||"",marketConditions:j?.marketConditions||""}
53)),[Yc,vn]=o.useState(!1),[su,Ei]=o.useState(()=>!!(j?.aiGenerated||j?.boundaries&&j?.description)),[Gc,$r]=o.useState(null),[Mi,tl]=o.useState(null),[to,Ao]=o.useState(null),[Gi,li]=o.useState(ge&&ge.length>0?ge:null),[fl,im]=o.useState([]),[Ad,gl]=o.useState([]),[Nn,_o]=o.useState([]),[mr,Jl]=o.useState([]),[bp,Uu]=o.useState(null),[ru,yp]=o.useState(null),[jd,Uo]=o.useState(null),[xl,om]=o.useState(null),[Br,nu]=o.useState(null),[lm,xc]=o.useState(null),[cm,Hc]=o.useState(null),[Hi,Sp]=o.useState(null),[iu,vp]=o.useState(null),[Np,ao]=o.useState(null),[Zs,al]=o.useState(null),Fi=o.useRef(null),[Td,Vu]=o.useState(!1),[Ap,Hm]=o.useState(.3),[js,bo]=o.useState(st?.appliedBoundaries??[]),Wm=o.useRef(st?.appliedBoundaries?.length??0),ou=o.useRef(!1),Xl=o.useRef(!1),Id=o.useRef(ma),$u=o.useRef(!1),[Km,Qm]=o.useState([]),Sf=o.useRef(new Set),[Zm,kg]=o.useState(!1),[dm,Vo]=o.useState([]),[xr,Ir]=o.useState([]),[Mg,lu]=o.useState(null),[ec,Jm]=o.useState(null),[Ma,Xn]=o.useState(st?.currentShapes??{polygons:[],circles:[]}),Bu=st?.currentShapes&&(st.currentShapes.circles.length>0||st.currentShapes.polygons.length>0),[Ea,so]=o.useState(Bu?st?.shapesInitialized??!1:!1),[Xm,zu]=o.useState(st?.noBoundaryPresetApplied??!1),jo=o.useRef(!1),$a=o.useRef(st?.defaultPresetApplied??!1),ci=o.useRef(!!(st&&(st.appliedBoundaries&&st.appliedBoundaries.length>0||st.currentShapes&&((st.currentShapes.circles?.length??0)>0||(st.currentShapes.polygons?.length??0)>0)))),[um,Wc]=o.useState(null),yo=o.useRef(null),[Kr,cu]=o.useState(st?.allCachedSales??[]),[bb,bc]=o.useState(!1),{loadSavedMapping:Cd,saveMapping:Fg}=xQ(),[_g,eh]=o.useState(!(st?.allCachedSales&&st.allCachedSales.length>0)),jp=EZ({initialCachedLabState:st,lateAllCachedSales:Xa,searchInFlight:re.isLoading||Wt}),ei=o.useRef(!1),Ug=o.useRef(Tr);Ug.current=Tr;const Vg=o.useRef(Fr);Vg.current=Fr;const tc=o.useRef(fe);tc.current=fe;const du=o.useRef(ye);du.current=ye;const uu=o.useRef(de);uu.current=de;const yc=o.useRef(Zs);yc.current=Zs;const wi=o.useRef([]),Rd=o.useRef([]),$g=o.useRef([]),[qu,bl]=o.useState(0),[Yu,pm]=o.useState(0),[Us,Kc]=o.useState("sale"),[yb,Pi]=o.useState([]),Lr=o.useRef([]),Qc=o.useRef([]),Dl=o.useRef([]);Dl.current=[...Nn,...mr],Lr.current=yb;const $o=o.useRef(0),Sc=o.useRef(0),Wi=o.useRef(0),ti=o.useRef(new Set),sl=o.useRef(r);sl.current=r;const Ed=o.useRef(!1),[Tp,Ip]=o.useState(!1),Cp=o.useRef(!1),ro=o.useMemo(()=>{const g=new Set;return re.selectedComps.forEach(I=>{I.snapshotId&&g.add(I.snapshotId),I.id&&g.add(I.id);const k=I.mlsNumber||I.mlsData?.mlsNumber||I.mlsData?.MlsListingNumber||I.mlsData?.ListingId;k&&g.add(String(k))}),g},[re.selectedComps]),vf=o.useRef(ro);vf.current=ro;const pu=o.useCallback(g=>g?C&&Us!=="rental"?nJ(re.selectedComps,{id:g.id??"",snapshotId:g.snapshotId,mlsNumber:g.mlsNumber}):g.snapshotId&&ro.has(g.snapshotId)||g.id&&ro.has(g.id)||g.mlsNumber&&ro.has(g.mlsNumber)?!0:re.selectedComps.some(I=>T0(I,g)):!1,[Us,C,ro,re.selectedComps]),mu=o.useRef(re.selectedComps);mu.current=re.selectedComps;const[hu,th]=o.useState(!1),[as,mm]=o.useState(pe??null),[fu,hm]=o.useState({}),[Fn,Zc]=o.useState(le??null),[fm,gm]=o.useState(!1),[wn,no]=o.useState(new Set(me??[])),Pn=o.useRef(!0),ca=o.useRef(new Set),pn=o.useCallback(g=>(ca.current.add(g),g.finally(()=>ca.current.delete(g)),g),[]),io=o.useRef({openAdjustModal:()=>Gn(!0),openDerivationPanel:()=>em(!0),runAVM:()=>{},applyLibrarySearch:void 0,applyOrderState:void 0,getLibrarySearches:()=>[],getOrderMarketStates:()=>[],removeLibrarySearchFromState:void 0});o.useEffect(()=>{io.current.openAdjustModal=()=>Gn(!0),io.current.openDerivationPanel=()=>em(!0),io.current.applyLibrarySearch=PC,io.current.applyOrderState=wC,io.current.getLibrarySearches=()=>xr,io.current.getOrderMarketStates=()=>dm,io.current.removeLibrarySearchFromState=g=>{Ir(I=>I.filter(k=>k.id!==g))}}),o.useEffect(()=>(Fe?.({openAdjustModal:()=>io.current.openAdjustModal(),openDerivationPanel:()=>io.current.openDerivationPanel(),runAVM:()=>io.current.runAVM(),applyLibrarySearch:g=>io.current.applyLibrarySearch?.(g),applyOrderState:g=>io.current.applyOrderState?.(g),getLibrarySearches:()=>io.current.getLibrarySearches?.()||[],getOrderMarketStates:()=>io.current.getOrderMarketStates?.()||[],removeLibrarySearchFromState:g=>io.current.removeLibrarySearchFromState?.(g),flushPendingLocks:async()=>{const g=Array.from(ca.current);g.length!==0&&await Promise.allSettled(g)}}),()=>Fe?.(null)),[Fe]),o.useEffect(()=>{Oe?.(fm)},[fm,Oe]),o.useEffect(()=>{rt?.(ec)}
53,[ec,rt]);const Rp=o.useMemo(()=>{const g=Zs==="market"&&Nn.length>0,I=Zs==="submarket"&&mr.length>0;return!g&&(I||Fr&&mr.length>0)?ru:bp},[Zs,Nn.length,mr.length,Fr,ru,bp]),ah=o.useRef(!!st),[ac,sc]=o.useState(null),[Bg,Sb]=o.useState(null);o.useEffect(()=>{if(!sa?.id||ah.current)return;ah.current=!0;const g=!!st;fetch(`/api/profile/${sa.id}/defaults`).then(I=>I.ok?I.json():null).then(I=>{if(I?.defaults){if(I.defaults.quickPicks&&sc(I.defaults.quickPicks),!g){const k=I.defaults.defaultRadiusPreset;(k===1||k===2)&&Sb(k)}if(!g&&Array.isArray(I.defaults.labColumnOrder)){const k=new Set(fg.map(Y=>Y.key)),L=I.defaults.labColumnOrder.filter(Y=>k.has(Y));L.length>0&&Ig(L)}if(!g&&I.defaults.defaultFilters&&(!V||V.length===0)){const k=I.defaults.defaultFilters,L={"match-subject":void 0,all:void 0,SFR:"House",Condo:"Condo",Townhouse:"Townhouse","Multi-Family":"Multi-Family"};qe(Y=>{const K=as?.gla,te=k.glaPercent,q=te!=null&&te>0&&typeof K=="number"&&K>0,ie=q?Math.round(K*(1-te/100)):Y.filters.minSqft,ee=q?Math.round(K*(1+te/100)):Y.filters.maxSqft,we=k.status&&k.status.length>0?k.status:["CLSD"];return{...Y,filters:{...Y.filters,status:we,statusSelection:we,...k.dateMonths!=null?{monthsBack:k.dateMonths}:{},propertyType:L[k.propertyType??"match-subject"],minSqft:ie,maxSqft:ee}}})}}}).catch(()=>{})},[sa?.id,V,st,as?.gla]);const[yl,zg]=o.useState("as-is"),[Gu,sh]=o.useState(()=>Ie||{}),gu=o.useCallback(g=>{sh(I=>{const k=typeof g=="function"?g(I):g;return ce?.(k),k})},[ce]),[rl,Hu]=o.useState(null),Nf=o.useRef("");o.useEffect(()=>{if(!He)return;if(!Pe||Object.keys(Pe).length===0){rl&&Hu(null),Nf.current="";return}const g=JSON.stringify(Pe);if(g===Nf.current)return;Nf.current=g;const I={condition:"condition",quality:"quality",gla:"gla",bedrooms:"bedrooms",bathrooms:"bathrooms",basementFinishedSqft:"basementFinishedSqft",basementSqft:"basementSqft",garageSpaces:"garageSpaces",heatingCooling:"heatingCooling",energyEfficient:"energyEfficient",functionalUtility:"functionalUtility",porchPatioDeck:"porchPatioDeck",pool:"pool",design:"design",stories:"stories",view:"view"},L={...rl?.fields||{}};for(const[Y,K]of Object.entries(I))Pe[Y]!=null&&Pe[Y]!==""&&(L[K]={value:Pe[Y],source:"User",hasConflict:!1,isVerified:!0});Object.keys(L).length>0&&Hu(Y=>({id:Y?.id||"after-repaired-subject",address:Y?.address||a+" (After-Repaired)",city:Y?.city||"",state:Y?.state||"",photoUrl:Y?.photoUrl||null,status:Y?.status||"Unknown",isSubject:!0,fields:L}))},[Pe,He,a]);const[_i,Af]=o.useState(null),[oo,Wu]=o.useState(null),[Qr,hr]=o.useState([]),Hn=o.useRef(!1),rh=o.useRef(!1),xm=o.useRef(!1),nh=o.useRef(null),jf=o.useRef(null),Tf=o.useRef(null);o.useEffect(()=>{if(!le)return;const g=JSON.stringify(le);g!==nh.current&&(nh.current=g,console.log("[PropertyLab] Syncing avmResults from prop (WizardPage database load completed)"),Hn.current=!0,Zc(le))},[le]),o.useEffect(()=>{if(!pe)return;const g=JSON.stringify(pe);if(g===jf.current)return;jf.current=g,console.log("[PropertyLab] Syncing verifiedSubject from prop (WizardPage database load completed)"),rh.current=!0;const I={...pe},k=t;I.condition||(I.condition=Fn?.verifiedSubject?.condition||k?.condition?.value||"C3"),I.quality||(I.quality=Fn?.verifiedSubject?.quality||k?.quality?.value||"Q4"),mm(I)},[pe]),o.useEffect(()=>{if(!me||me.length===0)return;const g=me.slice().sort().join(",");g!==Tf.current&&(Tf.current=g,console.log("[PropertyLab] Syncing selectedAvmComps from prop:",me.length),xm.current=!0,no(new Set(me)))},[me]),o.useEffect(()=>{if(Pn.current){Pn.current=!1;return}if(Hn.current){Hn.current=!1;return}W&&W(Fn)},[Fn,W]);const Jc=o.useRef(!0);o.useEffect(()=>{if(Jc.current){Jc.current=!1;return}if(xm.current){xm.current=!1;return}Z&&Z(Array.from(wn))},[wn,Z]);const J=o.useRef(!0);o.useEffect(()=>{if(J.current){J.current=!1;return}if(rh.current){rh.current=!1;return}se&&se(as)},[as,se]);const he=o.useMemo(()=>_D(ht,Je,m),[ht,Je,m]),Ae=o.useRef(null);o.useEffect(()=>{if(!Wr)return;const g=JSON.stringify(he);g!==Ae.current&&(Ae.current=g,$c(I=>I&&Mb(I,he)))},[he,Wr]);const Ke=o.useRef(null);o.useEffect(()=>{if(as&&Wr){const g=JSON.stringify(as);if(g===Ke.current)return;Ke.current=g,$c(I=>I&&Mb(Kb(I,as),he))}},[as]),o.useEffect(()=>{if(!as)return;const g=Object.entries(fu);g.length!==0&&(hm({}),mm(I=>{if(!I)return I;let k={...I};const L={...I.gridSubjectOverrides};for(const[Y,K]of g){const{vsPatch:te}=XT(Y,K.value);k={...k,...te},L[Y]=K}return{...k,gridSubjectOverrides:L}}))},[as,fu]);
53const ft=t?.estateType,mt=ft?`${ft.value??""}|${ft.source??""}|${ft.isEdited?1:0}`:"";o.useEffect(()=>{if(!Wr)return;const g=Qb(t).leaseholdFeeSimple;$c(I=>{if(!I)return I;const k=I.fields?.leaseholdFeeSimple;return k&&k.value===g.value&&k.source===g.source?I:{...I,fields:{...I.fields,leaseholdFeeSimple:g}}})},[mt,Wr!=null]);const Xe=o.useMemo(()=>JSON.stringify({propertyDetails:Je??null,listingDetails:ht??null,propertyData:t,verifiedSubject:as??null,subjectAddress:a,subjectState:i,subjectZipCode:l,subjectCoordinates:s,canonicalSubjectPhotos:ni,subjectProviderReplacementVersion:p}),[Je,ht,t,as,a,i,l,s,ni,p]),_t=o.useRef(null);o.useEffect(()=>{if(!Wr||Xe===_t.current)return;_t.current=Xe;const g=t,I=Je,k=ht,L=!!I&&Object.keys(I).length>0,Y=!!k&&Object.keys(k).length>0,K=L&&!Y?"PublicRecord":"MLS",te=Object.fromEntries(Object.entries(g).filter(([,ee])=>!ee||typeof ee!="object"?!1:ee.source==="User"||ee.isEdited===!0||ee.isConfirmed===!0)),q=QP(I,k,ni,yd?p:0),ie={salePrice:{value:k?.soldPrice||I?.lastSalePrice||null,source:K,hasConflict:!1,isVerified:!0},dateOfSale:{value:(()=>{const ee=k?.soldDate||I?.lastSaleDate||null,we=k?.contractDate||null;return ee?Mm(ee,we):null})(),source:K,hasConflict:!1,isVerified:!0},gla:{value:I?.squareFeet||I?.gla||k?.squareFeet||k?.gla||null,source:K,hasConflict:!1,isVerified:!0},yearBuilt:{value:(()=>{const ee=I?.yearBuilt||k?.yearBuilt;return ee?Number(ee):null})(),source:K,hasConflict:!1,isVerified:!0},aboveGrade:{value:(()=>{const ee=I?.bedrooms||I?.bedroomsTotal||k?.bedrooms||k?.bedroomsTotal,we=I?.bathrooms||I?.bathroomsTotal||k?.bathrooms||k?.bathroomsTotal,ve=I?.fullBathrooms??I?.fullBaths??k?.fullBathrooms??k?.fullBaths,Se=I?.halfBathrooms??I?.halfBaths??k?.halfBathrooms??k?.halfBaths,Qe=Uh(ve!=null?Number(ve):null,Se!=null?Number(Se):null,we!=null?Number(we):null),Nt=we!=null?Number(we):ve!=null?Number(ve)+(Se!=null?Number(Se)*.5:0):0;return ee!=null?`${Number(ee)+Math.ceil(Nt)+2}|${ee}|${Qe}`:null})(),source:K,hasConflict:!1,isVerified:!0},...DS(k,I,{},K),...Qb(te),site:{value:I?.lotSize||I?.lotSizeSquareFeet||I?.lotSizeAcres||k?.lotSize||k?.lotSizeSquareFeet||k?.lotSizeAcres||null,source:K,hasConflict:!1,isVerified:!0},view:{value:I?.view||k?.view||null,source:K,hasConflict:!1,isVerified:!1},design:{value:I?.style||k?.style||null,source:K,hasConflict:!1,isVerified:!0}};$c(ee=>{if(!ee)return ee;const we={...sW(ee.fields,yd?p:0)};for(const[Qe,Nt]of Object.entries(ie))we[Qe]=Nt;let ve=Kb({...ee,fields:we},as,K);const Se=Object.entries(ee.fields).filter(([,Qe])=>Qe?.source==="User");return Se.length>0&&(ve={...ve,fields:{...ve.fields,...Object.fromEntries(Se)}}),{...ve,photoUrl:q[0]||null,photos:q,status:OS(v0(k))}}),yd&&(Ri.current=p)},[Wr!=null,Xe,t,Je,ht,ni,yd,p,as]);const oa=o.useRef(!1),[ls,Ps]=o.useState(!1);o.useEffect(()=>{ge&&ge.length>0&&li(g=>{const I=g?g.slice().sort().join(","):"",k=ge.slice().sort().join(",");return I!==k?(console.log("[PropertyLab] Syncing submarket property IDs from prop:",ge.length),tl(ge.length),oa.current=!0,ge):g})},[ge]);const Er=o.useMemo(()=>AZ(Hi,Np,iu,s??null),[Hi,Np,iu,s]),mn=o.useRef(null);o.useEffect(()=>{if(!$t)return;let g=[];if(Tr&&Nn&&Nn.length>0)g=Nn.map(k=>({id:k.snapshotId||k.id,address:`${k.address||""}${k.city?`, ${k.city}`:""}`,status:k.status||"CLSD",listPrice:k.listPrice??null,salePrice:k.price??null,dom:k.dom??null,gla:k.sqft??null,beds:k.beds??null,baths:k.baths??null,yearBuilt:k.yearBuilt??null,ppsf:k.pricePerSqft??(k.price&&k.sqft?Math.round(k.price/k.sqft):null),closeDate:k.saleDate??null,listDate:k.listDate??null,latitude:k.coordinates?.lat??null,longitude:k.coordinates?.lng??null}));else if(Tr)return;const I=JSON.stringify(g);mn.current!==I&&(mn.current=I,$t(g))},[Tr,Nn,$t]);const vr=o.useRef(null);o.useEffect(()=>{if(!na)return;let g=[];Fr&&mr&&mr.length>0&&(g=dO(mr,ro,Er).map(L=>({id:L.snapshotId||L.id,address:`${L.address||""}${L.city?`, ${L.city}`:""}`,status:L.status||"CLSD",listPrice:L.listPrice??null,salePrice:L.price??null,dom:L.dom??null,gla:L.sqft??null,beds:L.beds??null,baths:L.baths??null,yearBuilt:L.yearBuilt??null,ppsf:L.pricePerSqft??(L.price&&L.sqft?Math.round(L.price/L.sqft):null),closeDate:L.saleDate??null,listDate:L.listDate??null,latitude:L.coordinates?.lat??null,longitude:L.coordinates?.lng??null})));const I=JSON.stringify(g);vr.current!==I&&(vr.current=I,na(g))},[Fr,mr,na,Er,ro]);const tn=o.useRef(!0);o.useEffect(()=>{if(tn.current){tn.current=!1;return}if(oa.current){oa.current=!1;return}Be&&Be(Gi||[])},[Gi,Be]),o.useEffect(()=>{const g=js.length,I=Wm.current;if(Id.current){Wm.current=g;return}if(g>I&&g>0){const k=js[js.length-1];console.log("[PropertyLab] Boundary added - triggering search. Boundary:",k?.name,"hasPolygon:",!!k?.polygon,"Boundaries:",js.map(L=>L.name),"loadingSavedSearch:",Xl.current),Xl.current?console.log("[PropertyLab] Skipping boundary-added search trigger — saved search/order state load will handle it"):ou.current=!0}g===0&&I>0&&(console.log("[PropertyLab] All boundaries removed - resetting loading state"),Tc.current&&Tc.current.abort(),Qn.current=!1,qe(k=>({...k,isLoading:!1}))),Wm.current=g},[js]);
53const[An,lo]=o.useState(()=>st?.elsCache?new Map(st.elsCache):new Map),Si=o.useRef(An);Si.current=An;const[Bo,nl]=o.useState(0),Ki=o.useCallback(g=>{lo(I=>{const k=typeof g=="function"?g(I):g;return k!==I&&queueMicrotask(()=>nl(L=>L+1)),k})},[]),[rc,Ku]=o.useState(0),wd=o.useCallback(()=>Ku(g=>g+1),[]),[vc,nc]=o.useState(),[_n,To]=o.useState(),So=o.useRef(!1);o.useEffect(()=>{!s||So.current||(So.current=!0,dn("/api/els/batch",{properties:[{propertyId:"__subject__",lat:s.lat,lng:s.lng}]},{throwOnSuccessFalse:!1}).then(g=>{g.success&&g.results?.[0]?.success&&(nc(g.results[0].factors),typeof g.results[0].score=="number"&&To(g.results[0].score))}).catch(()=>{}))},[s]);const wa=o.useMemo(()=>{const g=Je?.photos?.length?Je.photos:ht?.photos?.length?ht.photos:ni,I=_n!=null?_n>=90?"Premium":_n>=75?"Beneficial":_n>=60?"Above Average":_n>=45?"Average":_n>=30?"Below Average":"Adverse":void 0,k=t.fullBaths?.value!=null?Number(t.fullBaths.value):null,L=t.halfBaths?.value!=null?Number(t.halfBaths.value):null;let Y=k,K=L;const te=es=>{if(es==null||es==="")return;const Js=(typeof es=="string"?es:String(es)).trim();return Js||void 0},q=te(as?.design)??te(ht?.style)??te(Je?.style)??te(t.designStyle?.value),ie=te(ht?.basement);if(as){if(Y===null&&K===null&&as.bathrooms!=null){Y=Math.floor(as.bathrooms);const er=as.bathrooms-Y;K=er>=.1?Math.round(er*2):0}const es=as.address||a;return{address:jm(es||"")?.street||es,city:as.city,photoUrl:g[0]||void 0,price:as.lastSalePrice,beds:as.bedrooms,baths:as.bathrooms,fullBathrooms:Y,halfBathrooms:K,gla:as.gla,lotSqft:as.lotSizeAcres?Math.round(as.lotSizeAcres*43560):void 0,yearBuilt:as.yearBuilt,condition:as.condition||Fn?.verifiedSubject?.condition||t?.condition?.value||"C3",quality:as.quality||Fn?.verifiedSubject?.quality||t?.quality?.value||"Q4",locationScore:_n,locationTier:I,garage:as.garageSpaces,style:q,basement:ie}}const ee=Je?.bedrooms?Number(Je.bedrooms):ht?.bedrooms?Number(ht.bedrooms):t.bedrooms?.value?parseInt(String(t.bedrooms.value)):void 0,we=Je?.bathrooms?Number(Je.bathrooms):ht?.bathrooms?Number(ht.bathrooms):t.bathrooms?.value?parseFloat(String(t.bathrooms.value)):void 0,ve=Je?.squareFeet?Number(Je.squareFeet):ht?.squareFeet?Number(ht.squareFeet):t.gla?.value?parseInt(String(t.gla.value)):t.squareFeet?.value?parseInt(String(t.squareFeet.value)):void 0,Se=Je?.yearBuilt?Number(Je.yearBuilt):ht?.yearBuilt?Number(ht.yearBuilt):t.yearBuilt?.value?parseInt(String(t.yearBuilt.value)):void 0;if(!a&&!ee&&!we&&!ve)return null;if(Y===null&&K===null&&we!=null){Y=Math.floor(we);const es=we-Y;K=es>=.1?Math.round(es*2):0}const Qe=t.lotSize?.value?String(t.lotSize.value):void 0;let Nt;if(Je?.lotSize)Nt=typeof Je.lotSize=="number"?Je.lotSize:parseFloat(String(Je.lotSize).replace(/[^0-9.]/g,""))||void 0;else if(Je?.lotSizeAcres)Nt=Math.round(Number(Je.lotSizeAcres)*43560);else if(ht?.lotSize)Nt=typeof ht.lotSize=="number"?ht.lotSize:void 0;else if(ht?.lotSizeAcres)Nt=Math.round(Number(ht.lotSizeAcres)*43560);else if(Qe){const es=parseFloat(Qe.replace(/[^0-9.]/g,""));!isNaN(es)&&es>0&&(Nt=/acre/i.test(Qe)?Math.round(es*43560):Math.round(es))}const Ct=jm(a||""),va=Ct?.street||a||"Unknown Address",Ht=Ct?.city||"",Cs=ht?.soldPrice??Je?.lastSalePrice??void 0,aa=Cs!=null?typeof Cs=="number"?Cs:parseFloat(String(Cs).replace(/[^0-9.]/g,""))||void 0:void 0,Ft=Je?.garage?parseInt(String(Je.garage))||void 0:t.garageCars?.value?parseInt(String(t.garageCars.value)):void 0,ss=Fn?.verifiedSubject?.condition||(t.condition?.value?String(t.condition.value):void 0)||"C3",da=Fn?.verifiedSubject?.quality||(t.quality?.value?String(t.quality.value):void 0)||"Q4";return{address:va,city:Ht,photoUrl:g[0]||void 0,price:aa,beds:ee,baths:we,fullBathrooms:Y,halfBathrooms:K,gla:ve,lotSqft:Nt,yearBuilt:Se,condition:ss,quality:da,locationScore:_n,locationTier:I,garage:Ft,style:q,basement:ie}},[as,Je,ht,ni,_n,a,Fn,t]),di=o.useMemo(()=>{const g=ht;return g?{bedrooms:g.bedrooms,bathrooms:g.bathrooms,squareFeet:g.squareFeet,buildingAreaTotal:g.buildingAreaTotal??g.BuildingAreaTotal,BuildingAreaTotal:g.buildingAreaTotal??g.BuildingAreaTotal,numberOfUnitsTotal:g.
53numberOfUnitsTotal??g.NumberOfUnitsTotal,NumberOfUnitsTotal:g.numberOfUnitsTotal??g.NumberOfUnitsTotal,unitBreakdown:g.unitBreakdown,unitMix:g.unitMix,lotSize:g.lotSize,yearBuilt:g.yearBuilt,style:g.style,stories:void 0,garageSpaces:g.garageSpaces,basement:g.basement,construction:g.construction,exteriorFeatures:g.exteriorFeatures,roof:g.roofType,roofType:g.roofType,foundation:g.foundation,heating:g.heating,cooling:g.cooling,pool:g.pool,poolFeatures:g.pool,fireplaceFeatures:g.fireplaceFeatures,fireplaceCount:g.fireplace,fireplacesTotal:g.fireplace,parking:g.parkingType,parkingFeatures:g.parkingFeatures,parkingSpaces:g.parkingSpaces,taxes:g.taxes,taxYear:g.taxYear,taxAssessedValue:g.taxAssessedValue,county:g.county,zoning:g.zoning,neighborhood:g.neighborhood,subdivision:g.subdivision,township:g.township,apn:g.apn,description:g.description,features:g.features,interiorFeatures:g.interiorFeatures,appliances:g.appliances,equipment:g.equipment,laundryFeatures:g.laundryFeatures,bathFeatures:g.bathFeatures,attic:g.attic,elementarySchool:g.elementarySchool,middleSchool:g.middleSchool,highSchool:g.highSchool,schoolDistrict:g.schoolDistrict,greenFeatures:g.greenFeatures,hersIndex:g.hersIndex,electricity:g.electricity,sewer:g.sewer,water:g.water,waterfront:g.waterfront,concessions:g.concessions,saleTerms:g.saleTerms,possession:g.possession,originalListPrice:g.originalListPrice,spLpRatio:g.spLpRatio,taxExemptions:g.taxExemptions,specialAssessments:g.specialAssessments}:{}},[ht]),us=o.useMemo(()=>{const g=Je;return g?{bedrooms:g.bedrooms,bathrooms:g.bathrooms,squareFeet:g.squareFeet,livingArea:g.squareFeet,buildingAreaTotal:g.buildingAreaTotal??g.BuildingAreaTotal??g.areaSemanticProvenance?.buildingAreaTotal,BuildingAreaTotal:g.buildingAreaTotal??g.BuildingAreaTotal??g.areaSemanticProvenance?.buildingAreaTotal,numberOfUnitsTotal:g.numberOfUnitsTotal??g.NumberOfUnitsTotal,NumberOfUnitsTotal:g.numberOfUnitsTotal??g.NumberOfUnitsTotal,lotSize:g.lotSize,lotAcres:g.lotSizeAcres,yearBuilt:g.yearBuilt,style:g.style,construction:g.construction,roof:g.roofType,RoofType:g.roofType,foundation:g.foundation,FoundationType:g.foundation,heating:g.heating,cooling:g.cooling,garage:g.garage,garageSpaces:g.garage&&parseInt(String(g.garage))||void 0,fireplace:g.fireplace,fireplaceCount:g.fireplace,taxes:g.taxes,taxYear:g.taxYear,taxAssessedValue:g.taxAssessedValue,county:g.county,zoning:g.zoningCode,zoningDescription:g.zoningDescription,neighborhood:g.neighborhood,subdivision:g.subdivision,township:g.township,apn:g.apn,owner:g.owner,legalDescription:g.legalDescription,ExteriorWalls:g.construction}:{}},[Je]),ks=o.useMemo(()=>iM({garageSpaces:as?.garageSpaces,garageType:as?.garageType},di,us),[di,us,as?.garageSpaces]);o.useEffect(()=>{F&&D?.(ks)},[F,ks,D]);const On=o.useCallback(g=>!F||!ae?g:{...g,vehicleStorageLegacyLabel:oe,fields:{...g.fields,garageParking:{...g.fields.garageParking??{alternatives:[]},value:oe,source:"User"}}},[F,ae,oe]),ui=o.useRef(new Map),Xc=4,[Nc,Pd]=o.useState(()=>st?.compAiCache?new Map(st.compAiCache):new Map),Dr=o.useRef(Nc);Dr.current=Nc;const[co,Od]=o.useState(0),kl=o.useCallback(g=>{Pd(I=>{const k=typeof g=="function"?g(I):g;return k!==I&&queueMicrotask(()=>Od(L=>L+1)),k})},[]);o.useEffect(()=>{Array.isArray(Xa)&&Xa.length===0&&eh(!1),!(!ua?.length&&!Oa?.length&&!Xa?.length)&&(ua?.length&&(Ki(g=>{const I=new Map(g);let k=!1;for(const[L,Y]of ua)I.has(L)||(I.set(L,Y),k=!0);return k?I:g}),ua.forEach(([g])=>sn.current.add(g))),Oa?.length&&(kl(g=>{const I=new Map(g);let k=!1;for(const[L,Y]of Oa)I.has(L)||(I.set(L,Y),k=!0);return k?I:g}),Oa.forEach(([g])=>rn.current.add(g))),Xa?.length&&(cu(g=>g.length>
530?g:Xa),eh(!1)))},[ua,Oa,Xa]);const{enableAutoAdjustments:ih}=uL(),[bm,qg]=o.useState(null),[If,ym]=o.useState(!1),Yg=o.useCallback(g=>{qg(g),ym(!1)},[]),xu=o.useMemo(()=>{const g=Wr?.fields?.site,I=(()=>{if(!g||g.source!=="User")return null;const q=cC(g.value);return{active:!0,cleared:q.cleared,acres:q.cleared?null:q.acres}})(),k=(()=>{const q=as?.lotSizeAcres;if(typeof q=="number"&&q>0)return q;const ie=as?.lotSize;return typeof ie=="number"&&ie>0?ie/43560:null})(),L=Fn?.adjustmentRates?.lotSizePerAcre??null,Y=s?.lat,K=s?.lng;return(C&&Us!=="rental"?yb:re.selectedComps).map(q=>{const ie=q.snapshotId||q.id,ee=Dr.current.get(ie),we=ee?.btDesignStyle&&!q.btDesignStyle?{...q,btDesignStyle:ee.btDesignStyle}:q,ve=q.adjustments,Se=aW(we,!1,ve,qn,tt,k,L,I,F,C),Qe=KP(Y,K,Se.lat,Se.lng,Se.distance);if(Se.distance=Qe??void 0,Y!=null&&K!=null&&Se.lat!=null&&Se.lng!=null&&Se.lat!==0&&Se.lng!==0){const va=Se.distance??lb(Y,K,Se.lat,Se.lng),Ht=eW(Y,K,Se.lat,Se.lng),Cs=oM(va,Ht);Se.fields={...Se.fields,proximity:{...Se.fields.proximity??{},value:Cs,aiValue:Cs,source:"AI",hasConflict:!1,isVerified:!0}}}const Nt=q.gridFieldOverrides;let Ct=Se;if(Nt&&Object.keys(Nt).length>0){const va={...Se.fields},Ht={};for(const[aa,Ft]of Object.entries(Nt))C&&["neighborhoodName","location","site","view"].includes(aa)||(va[aa]=KZ(va[aa],Ft),aa==="city"&&(Ht.city=String(Ft.value)),aa==="state"&&(Ht.state=String(Ft.value)),aa==="zipCode"&&(Ht.zipCode=String(Ft.value)));const Cs=["ProximityToSubjectDistanceLinearMeasure","LinearUnitOfMeasureType","ComparableToSubjectDirectionType"];Cs.some(aa=>aa in Nt)&&(va.proximity={...ZZ(Object.fromEntries(Cs.map(aa=>[aa,va[aa]])),va.proximity),hasConflict:!1,isVerified:!!qT(Object.fromEntries(Cs.map(aa=>[aa,va[aa]])))}),Ct={...Se,...Ht,fields:va}}return F?tq(Ct,{compId:q.id,snapshotId:q.snapshotId,mlsNumber:q.mlsNumber,address:q.address},A):Ct})},[re.selectedComps,yb,C,Us,qn,tt,co,Wr,as,Fn,s,F,A]),vi=o.useMemo(()=>He?xu.filter(g=>{const I=Gu[g.id];return I?I==="both"||I===yl:yl==="as-is"}):xu,[xu,He,yl,Gu]),Gg=o.useMemo(()=>!He||yl==="as-is"?Wr:rl||Wr,[He,yl,Wr,rl]);o.useEffect(()=>{!He||!Wr||Hu(g=>{if(!g)return JSON.parse(JSON.stringify(Wr));const I={...Wr,fields:{...Wr.fields}};for(const[k,L]of Object.entries(g.fields))L&&L.source==="User"&&(I.fields[k]=L);return I})},[He,Wr]);const Ld=o.useMemo(()=>({address:a,coordinates:s||void 0,propertyType:void 0,beds:void 0,baths:void 0,gla:void 0,yearBuilt:t.yearBuilt?.value?parseInt(String(t.yearBuilt.value)):void 0,lotSize:void 0}),[a,s,t]),w=Ks||s||{lat:41.8781,lng:-87.6298};o.useEffect(()=>{Id.current&&(Id.current=!1,console.log("[PropertyLab] Cache restoration complete — effects unlocked"))},[]);const wt=o.useRef(!1);o.useEffect(()=>{if(wt.current||!st?.subjectCoordinates||!s)return;wt.current=!0;const g=st.subjectCoordinates;Math.sqrt(Math.pow(g.lat-s.lat,2)+Math.pow(g.lng-s.lng,2))>.001&&(console.log("[PropertyLab] Subject coordinates changed since last visit:",g,"->",s),Ve({title:"Subject location changed",description:"The subject property location was updated. Your previous search results have been restored, but you may want to re-search with the new location.",duration:8e3}))},[s]);const Pt=o.useRef(Xt);Pt.current=Xt;const Ba=o.useRef(null);o.useEffect(()=>{const g={labState:re,appliedBoundaries:js,currentShapes:Ma,mapCenter:Ks,mapZoom:Bn,viewMode:rs,labViewMode:bs,showMapPanel:ki,comparisonDataSource:qn,columnSort:Bi,visibleColumns:Jd,hasDrawnShapes:xo,shapesInitialized:Ea,allCachedSales:Kr,noBoundaryPresetApplied:Xm,defaultPresetApplied:$a.current,subjectCoordinates:s??null};Si.current.size>0&&(g.elsCache=Array.from(Si.current.entries())),Dr.current.size>0&&(g.compAiCache=Array.from(Dr.current.entries())),Ba.current=g,Pt.current&&Pt.current(g)},[re,js,Ma,Ks,Bn,rs,bs,qn,Bi,Jd,xo,Ea,Kr,Xm,s]),o.useEffect(()=>()=>{Ba.current&&Pt.current&&(Si.current.size>0&&(Ba.current.elsCache=Array.from(Si.current.entries())),Dr.current.size>0&&(Ba.current.compAiCache=Array.from(Dr.current.entries())),Pt.current(Ba.current))},[]);const Ts=o.useRef(!0),ia=o.useRef(!!(j?.boundaries||j?.description)),Ca=o.useRef(N),Ls=o.useRef(!1);o.useEffect(()=>{Ca.current!==N&&(Ca.current=N,Ll!==N&&(Ls.current=!0,oi(N)))},[N,Ll]);const Qs=o.useRef(x);Qs.current=x,o.useEffect(()=>{if(Ts.current){Ts.current=!1;return}if(Ls.current){Ls.current=!1;return}Qs.current?.(Ll)},[Ll]);const Lt=o.useRef(y);Lt.current=y;const La=o.useRef(null);o.useEffect(()=>{if(ia.current){ia.current=!1,La.current=JSON.stringify(el);return}const g=JSON.stringify(el);La.current!==g&&(La.current=g,Lt.current?.(el))},[el]);const lr=o.useRef(v);lr.current=v,o.useEffect(()=>{if(!V?.length||!Ll||Wr)return;console.log("[PropertyLab] Hydrating grid state from initialSelectedComps:",V.length);const g=Je,I=ht,k=t,L=jm(a||""),Y=L?.city||"",K=L?.state||i||"",te=g?.photos?.length?g.ph
53otos:I?.photos?.length?I.photos:ni,q=v0(I),ie={id:"subject",address:a||"Unknown Address",city:Y,state:K,zipCode:l||L?.zip||"",lat:s?.lat,lng:s?.lng,photoUrl:te[0]||null,photos:te,status:OS(q),isSubject:!0,elsScore:typeof _n=="number"?_n:null,elsTier:typeof _n=="number"?_n>=67?"Beneficial":_n>=34?"Neutral":"Adverse":null,fields:{salePrice:{value:I?.soldPrice||g?.lastSalePrice||k?.salePrice?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},dateOfSale:{value:(()=>{const ee=I?.soldDate||g?.lastSaleDate||k?.saleDate?.value||null,we=I?.contractDate||k?.contractDate?.value||null;return ee?Mm(ee,we):null})(),source:"MLS",hasConflict:!1,isVerified:!0},gla:{value:g?.squareFeet||I?.squareFeet||k?.gla?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},yearBuilt:{value:(()=>{const ee=g?.yearBuilt||I?.yearBuilt||k?.yearBuilt?.value;return ee?Number(ee):null})(),source:"MLS",hasConflict:!1,isVerified:!0},aboveGrade:{value:(()=>{const ee=g?.bedrooms||I?.bedrooms||k?.beds?.value,we=g?.bathrooms||I?.bathrooms||k?.baths?.value,ve=g?.fullBathrooms??I?.fullBathrooms??k?.fullBaths?.value,Se=g?.halfBathrooms??I?.halfBathrooms??k?.halfBaths?.value,Qe=Uh(ve!=null?Number(ve):null,Se!=null?Number(Se):null,we!=null?Number(we):null),Nt=we!=null?Number(we):ve!=null?Number(ve)+(Se!=null?Number(Se)*.5:0):0;return ee!=null?`${Number(ee)+Math.ceil(Nt)+2}|${ee}|${Qe}`:null})(),source:"MLS",hasConflict:!1,isVerified:!0},...DS(I,g,k),...Qb(k),site:{value:g?.lotSize||I?.lotSize||k?.lotSize?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},view:{value:k?.view?.value||null,source:"MLS",hasConflict:!1,isVerified:!1},design:{value:g?.style||I?.style||k?.style?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},strBedrooms:{value:g?.bedrooms||I?.bedrooms||k?.beds?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},strBathrooms:{value:g?.bathrooms||I?.bathrooms||k?.baths?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},strGLA:{value:(()=>{const ee=g?.squareFeet||I?.squareFeet||k?.gla?.value;return ee?`${ee} sf`:null})(),source:"MLS",hasConflict:!1,isVerified:!0},strParking:{value:g?.garage||I?.garage||k?.garage?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},strLocation:{value:"N;Res",source:"AI",hasConflict:!1,isVerified:!1},strNightlyRate:{value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},strOccupancy:{value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},strAnnualNights:{value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},strGrossIncome:{value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},strDataSource:{value:"MLS / Public Record",source:"MLS",hasConflict:!1,isVerified:!0}}};$c(Mb(Kb(ie,as),he))},[V,Ll,Wr,Je,ht,t,a,i,ni,Fn,as,s]),o.useEffect(()=>{Ts.current||!re.selectedComps.length||lr.current?.(re.selectedComps)},[re.selectedComps]);const Ys=o.useRef(S);Ys.current=S;const Ms=o.useRef(""),Zr=o.useRef(new Map),[cn,Jr]=o.useState(!1),[Wn,Dt]=o.useState(!1),[Da,Ia]=o.useState(U?"rentals":"sales"),[ar,Xs]=o.useState(null),[Fa,is]=o.useState(0),Cr=o.useRef(new Map),[Io,Qi]=o.useState({}),ic=o.useRef(null),dr=o.useCallback((g,I)=>{const k=zS(g),L=Vj(k);if(!I&&!BZ(Lr.current.length,L.length))return;const Y=n0(L,[...Qc.current,...Dl.current]);Qi(qZ(k)),Lr.current=Y,Pi(Y),Xs({gridCount:k.length,selectedCount:typeof g?.selectedCount=="number"?g.selectedCount:k.filter(K=>K.compSnapshotId).length,available:typeof g?.capacity?.available=="number"?g.capacity.available:Math.max(0,24-k.length)})},[]),_r=o.useCallback(g=>{if(!(!C||Us==="rental"))return hJ(Lr.current,g)},[Us,C]),Ni=o.useCallback(g=>{if(!C||Us==="rental")return;const I=hC(Lr.current,g);if(!I)return;const k=I.comparable.transferHistory?.[I.historyIndex]?.[I.fieldName];return k&&typeof k=="object"&&"source"in k&&typeof k.source=="string"?k.source:void 0},[Us,C]),P=o.useCallback((g,I)=>{if(!C||Us==="rental"||!r)return;const k=fJ(Lr.current,g,I);if(!k)return;const{itemId:L,transferHistory:Y}=k,K=Lr.current.map(q=>q.id!==L?q:{...q,transferHistory:Y});Lr.current=K,Pi(K);const te=r;Im(Cr.current,te,()=>ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(L)}`,{patch:{transferHistory:Y}},{headers:ho(r)}),q=>dr(q,!0)).catch(q=>{console.error("[PropertyLab] Failed to persist comparable sale history:",q),is(ie=>ie+1)})}
53,[dr,r,Us,C]),X=o.useCallback((g,I,k)=>{!C||!r||g.length===0||Im(Cr.current,r,()=>Go(r,dn(`/api/uad36/comparables/${encodeURIComponent(r)}/contract-date-copy`,{targetItemIds:g,date:I,unknown:k},{headers:ho(r)})),L=>dr(L,!0)).catch(L=>{console.error("[PropertyLab] Failed to copy Contract Date:",L),is(Y=>Y+1)})},[dr,r,C,Go]);o.useEffect(()=>{if(!C||!r||Us==="rental"){ic.current=null,Qc.current=[],Xs(null),Qi({});return}ic.current!==r&&(ic.current=r,Pi([]));let g=!1;const I=Sc.current;return Ho(`/api/uad36/comparables/${encodeURIComponent(r)}`,{cache:"no-store"}).then(k=>{g||!hO(I,Sc.current)||dr(k,!0)}).catch(()=>{g||Xs(null)}),()=>{g=!0}},[dr,r,Us,C,Fa]),o.useEffect(()=>{if(!C||!r||Us==="rental")return;let g=!1;const I=Sc.current;return Ho(`/api/uad36/comparables/${encodeURIComponent(r)}/memberships`,{cache:"no-store"}).then(k=>{if(g||!hO(I,Sc.current))return;const L=(k.cards??[]).map(K=>aJ(K));Qc.current=L;const Y=n0(Lr.current,[...L,...Dl.current]);Lr.current=Y,Pi(Y),qe(K=>({...K,selectedComps:L}))}).catch(()=>{g||qe(k=>({...k,selectedComps:[]}))}),()=>{g=!0}},[r,Us,C,Fa]),o.useEffect(()=>{if(!C||Us==="rental")return;const g=n0(Lr.current,[...Qc.current,...Dl.current]);g.some((k,L)=>k.rawMlsStatus!==Lr.current[L]?.rawMlsStatus)&&(Lr.current=g,Pi(g))},[Us,C,Nn,mr]);const{isLoading:xe,useIncomeApproach:Ye,useRentalApproach:ke,useSalesComparison:jt,subjectBuildings:Et,uad36Sections:ka}=AN(r,C),{formData:Yt,hydrated:ha,updateField:Rt,saveNow:Bt}=YL(r),Jt=o.useCallback((g,I,k,L)=>{if(!r)return;const Y=L??{value:k,confidence:"manual",source:"user",userEdited:!0};Rt(g,I,L??k),qi.setQueriesData({queryKey:["/api/uad36/prefill",r]},K=>K&&{...K,sections:{...K.sections,[g]:{...K.sections?.[g],[I]:Y}}}),!(g==="salesComparison"&&I==="orderedComparables")&&(No.current=No.current.filter(K=>!(K.section===g&&K.field===I)),No.current.push({section:g,field:I,value:Y}),Jo(50))},[r,qi,Jo,Rt]),gt=o.useRef(Et),Ra=o.useRef(!1);o.useEffect(()=>{Ra.current||(gt.current=Et)},[Et]);const fa=g=>{if(g==null)return null;if(typeof g=="object"&&g!==null&&"value"in g){const I=g.value;return I!=null?String(I):null}return typeof g=="string"?g:String(g)},Is=g=>{const I=typeof g=="object"&&g!==null&&"value"in g?g:null,k=lM(I?.source),L=I?.sourceCandidates&&typeof I.sourceCandidates=="object"?I.sourceCandidates:{};return{value:fa(g),source:k,hasConflict:!1,isVerified:I?.userEdited===!0||k==="User",sourceCandidates:I?.sourceCandidates&&typeof I.sourceCandidates=="object"?I.sourceCandidates:void 0,mlsValue:L.mls,prValue:L.public_records,aiValue:L.ai_derived,userValue:L.user}},cs=ha?Yt:ka,br=yO(cs?.salesContract?.SalesContractExistsIndicator),zr=yO(cs?.salesContract?.SalesContractReviewedIndicator),_s=NE({site:cs?.site}),et=g=>{const I=cs?.site?.[g];if(!I||typeof I!="object"||Array.isArray(I)||!("source"in I))return;const k=I.source;if(k==="mls"||k==="MLS")return"mls";if(k==="public_records"||k==="PublicRecord")return"public_records";if(k==="ai_derived"||k==="AI")return"ai_derived";if(k==="user"||k==="User")return"user"},pa=cs?.subjectProperty?.AttachmentType,Gt=HZ(pa);Gt?.value!=null&&String(Gt.value);const hs=cs?.subjectListing,qr=(()=>{const g=hs?.listings,I=g&&typeof g=="object"&&"value"in g?g.value:g;return Array.isArray(I)?I:[]})(),ys=o.useRef(qr);ys.current=qr;const yr=hs?.listings&&typeof hs.listings=="object"&&"source"in hs.listings?hs.listings.source:void 0,Yr=AE(qr);EU(qr);const Ge=(()=>{const g=cs?.site;if(!g)return null;const I=NE({site:g});return wU(I.parcels)})(),bt=X8(cs),Za=cs?.vehicleStorage?.items,ra=typeof Za?.source=="string"?Za.source:void 0,ta=Za?.userEdited===!0,Mt=o.useMemo(()=>{const g=cs?.salesComparisonGrid?.visibleRows?.value;return Array.isArray(g)?g.filter(I=>!!(I&&typeof I=="object")&&I.kind==="custom"&&I.group==="Vehicle Storage"&&typeof I.customId=="string"):[]},[cs]),ms=o.useMemo(()=>{const g=cs?.salesComparison??{};return Object.fromEntries(Mt.map(I=>{const k=g[`SubjectCustom_${I.customId}`],L=k&&typeof k=="object"&&"value"in k?k.value:k;return[I.customId,String(L??"")]}))},[cs,Mt]),cr=cs?.energyFeatures??{},Cn=o.useMemo(()=>{const g=cs?.salesComparisonGrid?.visibleRows;return Array.isArray(g?.value)?g.value.filter(I=>!!(I&&typeof I=="object")&&["RenewableEnergyComponentType","GreenCertificationName","EfficiencyRatingName"].includes(I.rowId)):[]},[cs]),Ai=o.useMemo(()=>{const g=cs?.salesComparisonGrid?.visibleRows,I=new Set(["LandOwnedInCommonIndicator","NeighborhoodName","SiteZoningComplianceType","HazardZoneType"]);return Array.isArray(g?.value)?g.value.filter(k=>
53!!(k&&typeof k=="object")&&I.has(k.rowId)):[]},[cs]),Rn=o.useMemo(()=>{const g=cs?.salesComparisonGrid?.visibleRows,I=new Set(cd.map(k=>zx(k)));return Array.isArray(g?.value)?g.value.filter(k=>!!(k&&typeof k=="object")&&I.has(k.rowId)):[]},[cs]),hn=cs?.propertyAmenities?.amenities,Ml=Array.isArray(hn?.value)?hn.value:[],bu=typeof hn?.source=="string"?hn.source:void 0,Kn=cV(cs??{}),oh=ha?Yt.improvements?.OverallQualityRatingCode:ka?.improvements?.OverallQualityRatingCode,xy=ha?Yt.improvements?.OverallConditionRatingCode:ka?.improvements?.OverallConditionRatingCode,Hg=(g,I)=>{const k=Yr?.__gridSourceState?.fields?.[g];return JZ(I??null,k,k?.source,yr)},lh={ContractPrice:Is(cs?.subjectProperty?.SalesContractAmount),ContractDate:Is(cs?.salesContract?.SalesContractDate),ListedWithinPreviousYearIndicator:Is(hs?.ListedWithinPreviousYearIndicator),listingStatus:Hg("ListingStatusType",Yr?.ListingStatusType),listPrice:Hg("FinalListPriceAmount",Yr?.FinalListPriceAmount),daysOnMarket:Hg("DaysOnMarketCount",Yr?.DaysOnMarketCount),OverallQualityRatingCode:Is(oh),OverallConditionRatingCode:Is(xy)},by=Et.length>0?Et.map(g=>`${g.improvementType??""}:${g.id??""}:${g.exteriorQualityRatingCode??""}:${g.exteriorConditionRatingCode??""}:${g.outbuildingType??""}:${g.outbuildingTypeOtherDescription??""}:${g.outbuildingRealPropertyIndicator??""}`).join("|"):"",Vt=o.useRef(!1);o.useEffect(()=>{if(!Wr)return;const g=Et;if(g.length===0)return;const I=yH(g.map(q=>({id:q.id,improvementType:q.improvementType,attachmentType:q.attachmentType??null,structuralDesignType:q.structuralDesignType??null,constructionMethods:Array.isArray(q.constructionMethods)?q.constructionMethods:[],manufacturedHomeWidthType:q.manufacturedHomeWidthType??null,outbuildingType:q.outbuildingType??null,outbuildingTypeOtherDescription:q.outbuildingTypeOtherDescription??null,outbuildingRealPropertyIndicator:q.outbuildingRealPropertyIndicator??null,units:(q.units??[]).map(ie=>({id:ie.id??"",isAdu:ie.isAdu??!1,kitchenCount:null}))}))),k=g.filter(q=>q.improvementType==="Dwelling"),L=g.flatMap(q=>(q.units??[]).filter(ie=>!ie.isAdu)),Y=g.flatMap(q=>(q.units??[]).filter(ie=>ie.isAdu)),K={};k.forEach((q,ie)=>{const ee=ie===0?"exteriorQuality":`Dwelling${ie+1}_ExteriorQualityRatingCode`,we=ie===0?"exteriorCondition":`Dwelling${ie+1}_ExteriorConditionRatingCode`;q.exteriorQualityRatingCode&&(K[ee]={value:q.exteriorQualityRatingCode,source:"User",hasConflict:!1,isVerified:!0}),q.exteriorConditionRatingCode&&(K[we]={value:q.exteriorConditionRatingCode,source:"User",hasConflict:!1,isVerified:!0})}),L.forEach((q,ie)=>{const ee=ie===0?"interiorQuality":`Unit${ie+1}_InteriorQualityRatingCode`,we=ie===0?"interiorCondition":`Unit${ie+1}_InteriorConditionRatingCode`;q.interiorQualityRatingCode&&(K[ee]={value:q.interiorQualityRatingCode,source:"User",hasConflict:!1,isVerified:!0}),q.interiorConditionRatingCode&&(K[we]={value:q.interiorConditionRatingCode,source:"User",hasConflict:!1,isVerified:!0})}),Y.forEach((q,ie)=>{const ee=ie+1;q.interiorQualityRatingCode&&(K[`Adu${ee}_InteriorQualityRatingCode`]={value:q.interiorQualityRatingCode,source:"User",hasConflict:!1,isVerified:!0}),q.interiorConditionRatingCode&&(K[`Adu${ee}_InteriorConditionRatingCode`]={value:q.interiorConditionRatingCode,source:"User",hasConflict:!1,isVerified:!0})});let te=-1;if(!Vt.current){Vt.current=!0,Ra.current=!0;const q=g.filter(ie=>ie.improvementType==="Outbuilding"&&ie.outbuildingRealPropertyIndicator===!0&&!!ie.outbuildingType&&ie.outbuildingType!=="StandaloneADU"&&!(ie.outbuildingType==="Other"&&ie.outbuildingTypeOtherDescription==="ADUGarage"));te=q.length,q.forEach((ie,ee)=>{const we=ee+1,ve=`Outbuilding${we}_OutbuildingType`,Se=`Outbuilding${we}_OutbuildingTypeOtherDescription`;K[ve]={value:ie.outbuildingType??"",source:"User",hasConflict:!1,isVerified:!0},K[Se]={value:ie.outbuildingTypeOtherDescription??"",source:"User",hasConflict:!1,isVerified:!0}});try{const ie={SubjectStructures:I};q.forEach((ee,we)=>{const ve=we+1;ie[`Outbuilding${ve}_OutbuildingType`]=K[`Outbuilding${ve}_OutbuildingType`]?.value||null,ie[`Outbuilding${ve}_OutbuildingTypeOtherDescription`]=K[`Outbuilding${ve}_OutbuildingTypeOtherDescription`]?.value||null}),sessionStorage.setItem(`uad36_ob_types_${r}`,JSON.stringify(ie))}catch{}}$c(q=>{if(!q)return q;const ie={};if(te>=0)for(const ee of Object.keys(q.fields??{})){const we=ee.match(/^Outbuilding(\d+)_OutbuildingType(OtherDescription)?$/);we&&parseInt(we[1])>te&&!(ee in K)&&(ie[ee]={value:"",source:"User",hasConflict:!1,isVerified:!0})}return q.fields?.SubjectStructures?.value===I&&Object.keys(K).every(ee=>q.fields?.[ee]?.value===K[ee].value)&&Object.keys(ie).length===0?q:{...q,fields:{...q.fields,...ie,SubjectStructures:{value:I,source:"User",hasConflict:!1,isVerified:!0}
53,...K}}}),te>=0&&mm(q=>{if(!q?.gridSubjectOverrides)return q;const ie=Object.keys(q.gridSubjectOverrides).filter(we=>{const ve=we.match(/^Outbuilding(\d+)_OutbuildingType(OtherDescription)?$/);return ve&&parseInt(ve[1])>te});if(ie.length===0)return q;const ee={...q.gridSubjectOverrides};for(const we of ie)delete ee[we];return{...q,gridSubjectOverrides:ee}})},[by,Wr!=null]),o.useEffect(()=>{!C||!r||$c(g=>{if(!g)return g;try{const I=sessionStorage.getItem(`uad36_ob_types_${r}`);if(!I)return g;const k=JSON.parse(I),L={};for(const[Y,K]of Object.entries(k))Y==="SubjectStructures"&&(L[Y]={value:K??"",source:"User",hasConflict:!1,isVerified:!0});return Object.keys(L).length===0?g:{...g,fields:{...g.fields,...L}}}catch{return g}})},[Wr!=null,C,r]);const Ut=C&&(Ye||ke),_a=!C||jt!==!1;o.useEffect(()=>{Us==="rental"&&!Ut?Kc("sale"):Us==="sale"&&!_a&&Ut&&Kc("rental")},[Us,Ut,_a]);const[Ss,fr]=o.useState([]),an=o.useRef(Ss);an.current=Ss;const Sl=o.useRef(new Set),Dd=o.useCallback((g,I,k,L)=>{console.log(`[OnDemandAI] Updating cache for propId=${g} (MLS ${I}): C=${k}, Q=${L}`),kl(Y=>{const K=new Map(Y),te=Y.get(g);return te?.condition&&te?.quality?Y:(K.set(g,{condition:k,quality:L}),K)}),I&&(rn.current.add(I),Sl.current.delete(I))},[]),Un=o.useRef(new Map),Ui=o.useCallback(g=>{const I=g.filter(Boolean);if(I.length<2)return;const k=new Set;for(const L of I){k.add(L);const Y=Un.current.get(L);Y&&Y.forEach(K=>k.add(K))}for(const L of k)Un.current.set(L,k)},[]),uo=o.useCallback((g,I)=>{const k=g.get(I);if(k!==void 0)return k;const L=Un.current.get(I);if(L)for(const Y of L){const K=g.get(Y);if(K!==void 0)return K}},[]),sn=o.useRef(st?.elsCache?new Set(st.elsCache.map(([g])=>g)):new Set),rn=o.useRef(st?.compAiCache?new Set(st.compAiCache.map(([g])=>g)):new Set),Co=o.useRef(new Set),ji=o.useRef(new Set),po=o.useCallback(g=>CQ(g),[]),[Ac,Qu]=o.useState([]),[yu,Wg]=o.useState(!1),[vb,Oi]=o.useState(null),pi=o.useMemo(()=>Ac.map(g=>Vb(g,!1)),[Ac]),il=o.useRef(!1),ed=as?.bedrooms??(Je?.bedrooms?Number(Je.bedrooms):void 0),Sm=c||Je?.propertyType,AC=o.useRef(!1);o.useEffect(()=>{if(AC.current||U||!Sm)return;const I=["Townhouse","Condo","Duplex","Multi-Family","Land","Single Family","Other"].find(k=>kV(Sm,k));I&&(AC.current=!0,qe(k=>k.filters.propertyTypes&&k.filters.propertyTypes.length>0?k:{...k,filters:{...k.filters,propertyTypes:[I]}}))},[U,Sm]),o.useEffect(()=>{if(!U||!a)return;const g=new AbortController;return G1(g,{subjectAddress:a,subjectState:i,subjectZipCode:l,subjectCoordinates:s,subjectBedrooms:ed,subjectPropertyType:Sm},{parseAddress:jm,normalizeStrToCompResult:po,setStrAggregatorLoading:Wg,setStrAggregatorProviders:Oi,setStrCompResults:Qu,resetStrDbMerged:()=>{il.current=!1},log:console.log,errorLog:console.error}),()=>{g.abort()}},[U,a,i,l,s?.lat,s?.lng,po,ed,Sm]);const rF=o.useMemo(()=>Ma.polygons.length===0?"":Ma.polygons[0].path.map(g=>`${g.lat.toFixed(6)},${g.lng.toFixed(6)}`).join("|"),[Ma.polygons]),jC=o.useRef(null),UN=o.useRef(!1),TC=o.useRef(null);o.useEffect(()=>{if(!U||Da!=="rentals"&&Da!=="all")return;const g=Ma.circles.length>0,I=Ma.polygons.length>0;if(!(g||I)&&!UN.current)return;const L=RQ(Ma);L&&(UN.current=!0);const Y=L?`geo:${L.lat.toFixed(6)},${L.lng.toFixed(6)},${L.radiusMiles.toFixed(6)}`:"subject";if(TC.current===Y)return;jC.current?.abort();const K=new AbortController;jC.current=K;const te=setTimeout(()=>{K.signal.aborted||(L||(UN.current=!1),TC.current=Y,console.log(`[PropertyLab] STR geometry re-query: ${L?`center=(${L.lat.toFixed(4)}, ${L.lng.toFixed(4)}), radius=${L.radiusMiles.toFixed(2)}mi`:"subject-centered (geometry cleared)"}`),G1(K,{subjectAddress:a,subjectState:i,subjectZipCode:l,subjectCoordinates:s,subjectBedrooms:ed,subjectPropertyType:Sm,geometryOverride:L},{parseAddress:jm,normalizeStrToCompResult:po,setStrAggregatorLoading:Wg,setStrAggregatorProviders:Oi,setStrCompResults:Qu,resetStrDbMerged:()=>{il.current=!1},log:console.log,errorLog:console.error}))},600);return()=>{clearTimeout(te),K.abort()}},[U,Da,Ma.circles.length,Ma.polygons.length,Ma.circles[0]?.center.lat,Ma.circles[0]?.center.lng,Ma.circles[0]?.radiu
53sMeters,rF,a,i,l,s?.lat,s?.lng,po,ed,Sm]),o.useEffect(()=>{!U||yu||!ya||ya.length===0||il.current||(il.current=!0,Qu(g=>{const I=new Set,k=new Set;g.forEach(K=>{I.add(K.id),K.snapshotId&&I.add(K.snapshotId),K.strProviderId&&I.add(K.strProviderId);const te=(K.address||K.fullAddress||"").toLowerCase().replace(/[^a-z0-9]/g,"");te&&k.add(te)});const L=ya.filter(K=>{if(I.has(K.id))return!1;const te=(K.address||"").toLowerCase().replace(/[^a-z0-9]/g,"");return!(te&&k.has(te))});if(L.length===0)return g;const Y=L.map(K=>{const te=K.nightlyRate||0,q=K.occupancyRate||0,ie=K.photoUrl;return{id:K.id,snapshotId:K.id,address:K.address||"Unknown Address",city:"",state:"",zip:"",fullAddress:K.address||"",coordinates:K.lat!=null&&K.lng!=null&&Number.isFinite(K.lat)&&Number.isFinite(K.lng)&&(K.lat!==0||K.lng!==0)?{lat:K.lat,lng:K.lng}:null,distance:0,status:"CLSD",saleDate:void 0,price:te,pricePerSqft:void 0,gla:K.gla??void 0,beds:K.bedrooms??0,baths:K.bathrooms??0,yearBuilt:0,lotSize:void 0,garageSpaces:void 0,dom:0,propertyType:"Residential",photoUrl:ie,photos:ie?[ie]:K.photos||[],selectionState:"none",isStrProperty:!0,strSource:K.platform||"",strProviderId:K.id,strListingName:K.listingName||"",strRentalType:K.rentalType||"",strAverageDailyRate:te,strOccupancyRate:q,strGrossRevenue12mo:K.annualRevenue,strRating:K.rating,strReviewCount:K.reviewCount,strGuestCapacity:void 0,strMaxGuests:void 0,strProvider:K.platform||"",strAmenities:void 0}});return console.log("[PropertyLab] Merging",Y.length,"additional STR comps from database (total aggregator:",g.length,")"),[...g,...Y]}))},[U,yu,ya]);const IC=o.useRef(null);o.useEffect(()=>{if(!U||Ac.length===0)return;const g=new Map,I=new Map;Ac.forEach(k=>{g.set(k.id,k),g.set(k.snapshotId||k.id,k),k.strProviderId&&g.set(k.strProviderId,k);const L=(k.address||k.fullAddress||"").toLowerCase().replace(/[^a-z0-9]/g,"");L&&I.set(L,k)}),qe(k=>{const L=k.selectedComps;if(L.length===0)return k;const Y=L.filter(ie=>{if(ie.isStrProperty&&(!ie.strAverageDailyRate||ie.strAverageDailyRate===0))return!0;if(!ie.isStrProperty){const ee=(ie.address||ie.fullAddress||"").toLowerCase().replace(/[^a-z0-9]/g,"");if(ee&&I.has(ee))return!0}return!1});if(Y.length===0)return k;const K=Y.map(ie=>ie.snapshotId||ie.id).join(",");if(IC.current===K)return k;IC.current=K;const te=L.map(ie=>{if(ie.isStrProperty&&ie.strAverageDailyRate&&ie.strAverageDailyRate>0)return ie;let ee=g.get(ie.snapshotId||ie.id)||g.get(ie.id)||(ie.strProviderId?g.get(ie.strProviderId):void 0);if(!ee){const we=(ie.address||ie.fullAddress||"").toLowerCase().replace(/[^a-z0-9]/g,"");we&&(ee=I.get(we))}return ee?{...ie,isStrProperty:!0,strAverageDailyRate:ee.strAverageDailyRate||ie.strAverageDailyRate,strOccupancyRate:ee.strOccupancyRate||ie.strOccupancyRate,strGrossRevenue12mo:ee.strGrossRevenue12mo||ie.strGrossRevenue12mo,strRating:ee.strRating||ie.strRating,strReviewCount:ee.strReviewCount||ie.strReviewCount,strGuestCapacity:ee.strGuestCapacity||ie.strGuestCapacity,strMaxGuests:ee.strMaxGuests||ie.strMaxGuests,strProvider:ee.strProvider||ie.strProvider,strListingName:ee.strListingName||ie.strListingName,strRentalType:ee.strRentalType||ie.strRentalType,strSource:ee.strSource||ie.strSource,strAmenities:ee.strAmenities||ie.strAmenities,strProviderId:ee.strProviderId||ie.strProviderId}:ie});return te.some((ie,ee)=>ie!==L[ee])?(console.log("[PropertyLab] Merged STR rental data into",Y.length,"selected comps (including address-matched)"),{...k,selectedComps:te}):k})},[U,Ac]),o.useEffect(()=>{const g=JSON.stringify(re.selectedComps.map(te=>({id:te.snapshotId||te.id,gla:te.gla,beds:te.beds,baths:te.baths,yearBuilt:te.yearBuilt,fullBathrooms:F?te.fullBathrooms:void 0,halfBathrooms:F?te.halfBathrooms:void 0,lotSize:te.lotSize,basement:te.basement,garageSpaces:te.garageSpaces,price:te.price,mlsData:te.mlsData,publicRecordData:te.publicRecordData,aboveGradeOverride:F?te.gridFieldOverrides?.aboveGrade:void 0,attachmentOverrides:F?{attachmentType:te.gridFieldOverrides?.attachmentType,AttachmentType:te.gridFieldOverrides?.AttachmentType,attachedDetached:te.gridFieldOverrides?.attachedDetached,AttachedDetached:te.gridFieldOverrides?.AttachedDetached}:void 0,strComparability:te.strComparability,strAverageDailyRate:te.strAverageDailyRate,strOccupancyRate:te.strOccupancyRate,strGrossMonthlyIncome:te.strGrossMonthlyIncome}))),I=Array.from(Dr.current.entries()).map(([te,q])=>`${te}:${q.condition}:${q.quality}`).join(","),k=`${g}|${I}`;if(k===Ms.current)return;
53if(Ms.current=k,re.selectedComps.length===0){Zr.current.clear(),Ys.current?.([]);return}const L=re.selectedComps.map(te=>{const q=te.snapshotId||te.id,ie=Zr.current.get(q),ee=uo(Dr.current,q),we=CT(te),ve=Fl=>{if(Fl===null)return null;if(Fl===void 0||Fl==="")return;const ad=Number(String(Fl).replace(/[$,\s]/g,""));return Number.isFinite(ad)&&ad>=0?ad:void 0},Se=Fl=>{if(Fl===null||Fl==="")return{full:null,half:null};if(typeof Fl!="string")return null;const ad=Fl.split("|");if(ad.length!==3)return null;const Df=ad[2].trim().split(".");if(Df.length>2||Df[0]==="")return null;const zy=ve(Df[0]),qy=Df.length===2?ve(Df[1]):0;return zy!=null&&qy!=null?{full:zy,half:qy}:null},Qe=te,Nt=Qe.mlsData||{},Ct=Qe.publicRecordData||{},va=F?ve(Qe.fullBathrooms??Qe.fullBaths)??ve(Nt.BathroomsFull??Nt.fullBaths)??ve(Ct.BathroomsFull??Ct.fullBaths):void 0,Ht=F?ve(Qe.halfBathrooms??Qe.halfBaths)??ve(Nt.BathroomsHalf??Nt.halfBaths)??ve(Ct.BathroomsHalf??Ct.halfBaths):void 0,Cs=F?Qe.gridFieldOverrides?.aboveGrade:void 0,aa=Cs&&Object.prototype.hasOwnProperty.call(Cs,"value")?Se(Cs.value):null,Ft=aa?aa.full:va,ss=aa?aa.half:Ht,da=Cs?.source==="PublicRecord"?"publicRecord":Cs?.source==="MLS"?"mls":Cs?.source==="User"?"manual":va!==void 0||Ht!==void 0?Nt.BathroomsFull!=null||Nt.BathroomsHalf!=null?"mls":"publicRecord":"mls",es={...ve(Qe.fullBathrooms??Qe.fullBaths)!=null?{mls:ve(Qe.fullBathrooms??Qe.fullBaths)}:{},...ve(Nt.BathroomsFull??Nt.fullBaths)!=null?{mls:ve(Nt.BathroomsFull??Nt.fullBaths)}:{},...ve(Ct.BathroomsFull??Ct.fullBaths)!=null?{publicRecord:ve(Ct.BathroomsFull??Ct.fullBaths)}:{}},Js={...ve(Qe.halfBathrooms??Qe.halfBaths)!=null?{mls:ve(Qe.halfBathrooms??Qe.halfBaths)}:{},...ve(Nt.BathroomsHalf??Nt.halfBaths)!=null?{mls:ve(Nt.BathroomsHalf??Nt.halfBaths)}:{},...ve(Ct.BathroomsHalf??Ct.halfBaths)!=null?{publicRecord:ve(Ct.BathroomsHalf??Ct.halfBaths)}:{}},er=[...Ft!==void 0||aa?[{fieldKey:"fullBathrooms",fieldLabel:"Full Bathrooms",category:"basics",finalValue:Ft??null,source:da,confidence:.9,options:es,hasConflict:es.mls!=null&&es.publicRecord!=null&&es.mls!==es.publicRecord,isRequired:!1,...Cs?{comment:"Property Lab selected source"}:{}}]:[],...ss!==void 0||aa?[{fieldKey:"halfBathrooms",fieldLabel:"Half Bathrooms",category:"basics",finalValue:ss??null,source:da,confidence:.9,options:Js,hasConflict:Js.mls!=null&&Js.publicRecord!=null&&Js.mls!==Js.publicRecord,isRequired:!1,...Cs?{comment:"Property Lab selected source"}:{}}]:[]];let ga=we.condition,As=we.conditionConfidence,Ya=we.conditionSource,Aa=we.quality,ns=we.qualityConfidence,Sr=we.qualitySource;if(ie){const Fl=ie.conditionSource==="vault"||ie.conditionSource==="manual",ad=ie.qualitySource==="vault"||ie.qualitySource==="manual";Fl&&(ga=ie.condition,As=ie.conditionConfidence,Ya=ie.conditionSource),ad&&(Aa=ie.quality,ns=ie.qualityConfidence,Sr=ie.qualitySource)}ee&&((!Ya||Ya!=="vault"&&Ya!=="manual")&&(ga=ee.condition||ga,As=ee.confidence,Ya="ai"),(!Sr||Sr!=="vault"&&Sr!=="manual")&&(Aa=ee.quality||Aa,ns=ee.confidence,Sr="ai"));const Or=te.coordinates?.lat??te.lat??(parseFloat(te.latitude||"")||void 0),Li=te.coordinates?.lng??te.lng??(parseFloat(te.longitude||"")||void 0),Ti=s?.lat,Ic=s?.lng;let oc=we.distanceMiles,Lf=we.latitude,Xg=we.longitude;if(Or&&Li&&Ti&&Ic){const Fl=KP(Ti,Ic,Or,Li,0);Fl!=null&&Fl>0&&(oc=Fl),Lf||(Lf=Or),Xg||(Xg=Li)}const wb={...we,...typeof Ft=="number"?{fullBathrooms:Ft}:{},...typeof ss=="number"?{halfBathrooms:ss}:{},...er.length>0?{cleanedFields:[...we.cleanedFields,...er]}:{},condition:ga,conditionConfidence:As,conditionSource:Ya,quality:Aa,qualityConfidence:ns,qualitySource:Sr,...ee?.btDesignStyle?{btDesignStyle:ee.btDesignStyle}:{},distanceMiles:oc,latitude:Lf,longitude:Xg},Pp=F&&!C?uk(wb,te):wb;return Zr.current.set(q,Pp),Pp}),Y=new Set(re.selectedComps.map(te=>te.snapshotId||te.id)),K=Array.from(Zr.current.keys());for(const te of K)Y.has(te)||Zr.current.delete(te);console.log("[PropertyLab] Syncing cleanedComps:",L.length,"with AI ratings:",Dr.current.size),Ys.current?.(L)},[re.selectedComps,co,s?.lat,s?.lng,F]),o.useEffect(()=>{const I=setTimeout(async()=>{const k=new Set(re.selectedComps.map(te=>te.snapshotId||te.id)),L=Array.from(ji.current);for(const te of L)k.has(te)||ji.current.delete(te);const Y=re.selectedComps.filter(te=>{const q=te.snapshotId||te.id,ie=te.photos&&te.photos.length>0||te.photoUrl,ee=!ji.current.has(q);return ie&&ee});if(Y.length===0)return;const K=Y.map(te=>te.snapshotId||te.id);
53K.forEach(te=>ji.current.add(te)),console.log("[PropertyLab] Triggering AI photo analysis for",Y.length,"comps"),Jr(!0);try{const te=Y.map(ie=>({compId:ie.snapshotId||ie.id,mlsNumber:iJ({mlsNumber:ie.mlsNumber,mlsData:ie.mlsData}),photoUrls:ie.photos?.slice(0,4)||(ie.photoUrl?[ie.photoUrl]:[]),address:ie.address,propertyType:ie.propertyType})),q=await fetch("/api/ai/analyze-comp-photos",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({comps:te,assignmentId:r})});if(q.ok){const ie=await q.json();if(ie.success&&ie.results){const ee=new Set(Object.keys(ie.results));kl(we=>{const ve=new Map(we);for(const[Se,Qe]of Object.entries(ie.results))ve.set(Se,{condition:Qe.condition?.rating,quality:Qe.quality?.rating,confidence:Math.min(Qe.condition?.confidence||.7,Qe.quality?.confidence||.7),btDesignStyle:Qe.btDesignStyle||void 0});return ve}),K.forEach(we=>{ee.has(we)||ji.current.delete(we)}),console.log("[PropertyLab] AI photo analysis complete for",Object.keys(ie.results).length,"comps")}else K.forEach(ee=>ji.current.delete(ee))}else K.forEach(ie=>ji.current.delete(ie))}catch(te){console.warn("[PropertyLab] Failed to analyze comp photos:",te),K.forEach(q=>ji.current.delete(q))}finally{Jr(!1)}},500);return()=>clearTimeout(I)},[re.selectedComps]),o.useEffect(()=>{const g=st?.allCachedSales&&st.allCachedSales.length>0,I=async(k=0)=>{try{g||eh(!0);const L=await Ho("/api/sales/map",{throwOnSuccessFalse:!1});if(L.success&&L.sales)console.log(`[PropertyLab] Loaded ${L.sales.length} cached sales for map (global library)`),cu(L.sales);else if(k===0){console.warn("[PropertyLab] /api/sales/map returned non-success, retrying in 2s..."),setTimeout(()=>I(1),2e3);return}}catch(L){if(console.warn("[PropertyLab] Failed to load all sales (attempt",k+1,"):",L),k===0){setTimeout(()=>I(1),2e3);return}}finally{eh(!1)}};I()},[]),o.useEffect(()=>{const g=wi.current.length;wi.current=Nn,g===0&&Nn.length>0&&bl(I=>I+1)},[Nn]),o.useEffect(()=>{Rd.current=mr},[mr]),o.useEffect(()=>{const g=async()=>{const Y=wi.current,K=Tr&&Y.length>0?[...Y.map(ee=>({...ee,snapshotId:ee.snapshotId||ee.id,coordinates:ee.coordinates}))]:re.properties;for(const ee of K){const we=ee.snapshotId||ee.id,ve=Pc(ee);ve&&we!==ve?Ui([we,ve,ee.id]):ee.snapshotId&&ee.id&&ee.snapshotId!==ee.id&&Ui([ee.snapshotId,ee.id])}const te=K.filter(ee=>{const we=ee.snapshotId||ee.id;if(!ee.coordinates||ee.echoLocationScore&&ee.echoLocationScore.score>=0||sn.current.has(we))return!1;const ve=Un.current.get(we);if(ve){for(const Se of ve)if(sn.current.has(Se))return!1}return!0});if(te.length===0)return;console.log("[PropertyLab] Fetching ELS for",te.length,"properties");const q=50,ie=[];for(let ee=0;ee<te.length;ee+=q)ie.push(te.slice(ee,ee+q));for(const ee of ie){const we=ee.map(ve=>ve.snapshotId||ve.id);we.forEach(ve=>sn.current.add(ve));try{const ve=ee.map(Qe=>({propertyId:Qe.snapshotId||Qe.id,lat:Qe.coordinates.lat,lng:Qe.coordinates.lng})),Se=await dn("/api/els/batch",{properties:ve},{throwOnSuccessFalse:!1});if(Se.success&&Se.results){const Qe=new Set(Se.results.filter(Ct=>Ct.success).map(Ct=>Ct.propertyId));Ki(Ct=>{const va=new Map(Ct);for(const Ht of Se.results)Ht.success&&va.set(Ht.propertyId,{score:Ht.score,tier:Ht.tier,factors:Ht.factors,isOverridden:Ht.isOverridden,isPartial:Ht.isPartial||!1});return va});const Nt=we.filter(Ct=>!Qe.has(Ct));for(const Ct of Nt){const va=ui.current.get(Ct)||0;va>=Xc?Ki(Ht=>{const Cs=new Map(Ht);return Cs.set(Ct,{score:-1,tier:"Neutral",factors:[],isOverridden:!1}),Cs}):(ui.current.set(Ct,va+1),sn.current.delete(Ct))}}else for(const Qe of we){const Nt=ui.current.get(Qe)||0;Nt>=Xc?Ki(Ct=>{const va=new Map(Ct);return va.set(Qe,{score:-1,tier:"Neutral",factors:[],isOverridden:!1}),va}):(ui.current.set(Qe,Nt+1),sn.current.delete(Qe))}}catch(ve){console.warn("[PropertyLab] ELS batch fetch failed:",ve);for(const Se of we){const Qe=ui.current.get(Se)||0;Qe>=Xc?Ki(Nt=>{const Ct=new Map(Nt);return Ct.set(Se,{score:-1,tier:"Neutral",factors:[],isOverridden:!1}),Ct}):(ui.current.set(Se,Qe+1),sn.current.delete(Se))}}}}
53,I=Math.max(0,...Array.from(ui.current.values())),k=I>0?Math.min(500+Math.pow(2,I)*1e3,8e3):500,L=setTimeout(g,k);return()=>clearTimeout(L)},[re.properties,Tr,qu]),o.useEffect(()=>{const g=wi.current,I=Tr&&g.length>0;if(re.isLoading&&!I)return;const L=setTimeout(async()=>{const Y=wi.current,te=(Tr&&Y.length>0?Y:re.properties).filter(ee=>{const we=Pc(ee);return we&&!Co.current.has(we)&&!rn.current.has(we)});if(te.length===0)return;const q=[],ie=new Map;for(const ee of te){const we=ee.snapshotId||ee.id,ve=Pc(ee);ve&&(q.push(we),ie.set(we,ve))}if(q.length!==0){console.log("[PropertyLab] Fetching cached AI ratings for",q.length,"properties");try{const ee=await fetch("/api/ai/get-cached-ratings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({snapshotIds:q})});if(ee.ok){const we=await ee.json();we.success&&we.results&&(q.forEach(ve=>{const Se=ie.get(ve);Se&&Co.current.add(Se)}),kl(ve=>{const Se=new Map(ve);let Qe=!1;for(const[Nt,Ct]of Object.entries(we.results)){const va=ie.get(Nt);if(Nt&&(Ct.conditionRating||Ct.qualityRating)){const Ht=ve.get(Nt);if(Ht?.condition&&Ht?.quality)continue;Se.set(Nt,{condition:Ct.conditionRating,quality:Ct.qualityRating,confidence:Math.min(Ct.conditionConfidence||.7,Ct.qualityConfidence||.7)}),Qe=!0,va&&rn.current.add(va)}}return Qe?Se:ve}),console.log("[PropertyLab] Loaded cached AI ratings for",we.foundCount,"of",q.length,"properties"))}}catch(ee){console.warn("[PropertyLab] Failed to fetch cached AI ratings:",ee)}}},300);return()=>clearTimeout(L)},[re.properties,Tr,qu,re.isLoading]);const CC=o.useRef(new Set);o.useEffect(()=>{if(r){if(!MZ(C))return;const g=V&&V.length>0,I=re.selectedComps.length>0,k=He&&Object.keys(Gu).length===0,L=/^\s*(none|n\/?a|unknown|null|-|–|—)\s*$/i,Y=ie=>!(ie==null||ie===""||typeof ie=="string"&&L.test(ie)),K=(ie,ee)=>{if(!ee)return ie||void 0;if(!ie)return ee;const we={...ee};for(const[ve,Se]of Object.entries(ie))Y(Se)&&(we[ve]=Se);return we},te=ie=>{const ee=ie.mlsData;if(!ee)return!0;const we=Y(ee.lotSize)||Y(ee.LotSizeSquareFeet)||Y(ee.LotSizeAcres),ve=Y(ee.basementSqft)||Y(ee.BasementArea)||Y(ee.basement)||Y(ee.Basement)||Y(ee.basementType),Se=Y(ee.garageSpaces)||Y(ee.GarageSpaces)||Y(ee.garageType)||Y(ee.GarageType)||Y(ee.GarageYN),Qe=Y(ee.PatioAndPorchFeatures)||Y(ee.patioFeatures)||Y(ee.PorchFeatures)||Y(ee.OutdoorFeatures),Nt=String(ie.status??"").toLowerCase(),Ct=["clsd","sold","closed","cls"].includes(Nt),va=ie.contractDate!=null||ee.contractDate!=null;return!!(!we||!ve||!Se||!Qe||Ct&&!va)},q=g&&V.some(te)||I&&re.selectedComps.some(te);if(g&&!k&&!q){console.log("[PropertyLab] Using initialSelectedComps from wizard - skipping DB load to preserve edits");const ie=re.selectedComps.length>0?re.selectedComps:V,ee=ie.some(ve=>ve.snapshotId&&(!ve.contractDate||!ve.saleDate)),we=ie.some(ve=>ve.snapshotId&&!ve.mlsData);(ee||we)&&Ho(`/api/comps/selected/${r}`,{throwOnSuccessFalse:!1}).then(ve=>{if(ve.success&&ve.comps?.length>0){const Se=new Map;ve.comps.forEach(Qe=>{Qe.id&&Se.set(Qe.id,{saleDate:Qe.saleDate,contractDate:Qe.contractDate,mlsData:Qe.mlsData,publicRecordData:Qe.publicRecordData})}),qe(Qe=>({...Qe,selectedComps:Qe.selectedComps.map(Nt=>{const Ct=Nt.snapshotId||Nt.id,va=Se.get(Ct);return va?{...Nt,saleDate:Nt.saleDate||va.saleDate,contractDate:Nt.contractDate||va.contractDate,mlsData:K(Nt.mlsData,va.mlsData),publicRecordData:Nt.publicRecordData||va.publicRecordData}:Nt})})),console.log("[PropertyLab] Enriched",Se.size,"comps with dates/mlsData from DB")}}).catch(()=>{});return}if(I&&!k&&!q){re.selectedComps.some(ee=>ee.snapshotId&&!ee.mlsData)&&Ho(`/api/comps/selected/${r}`,{throwOnSuccessFalse:!1}).then(ee=>{if(ee.success&&ee.comps?.length>0){const we=new Map;ee.comps.forEach(ve=>{ve.id&&we.set(ve.id,{saleDate:ve.saleDate,contractDate:ve.contractDate,mlsData:ve.mlsData,publicRecordData:ve.publicRecordData})}),qe(ve=>({...ve,selectedComps:ve.selectedComps.map(Se=>{const Qe=Se.snapshotId||Se.id,Nt=we.get(Qe);return Nt?{...Se,saleDate:Se.saleDate||Nt.saleDate,contractDate:Se.contractDate||Nt.contractDate,mlsData:K(Se.mlsData,Nt.mlsData),publicRecordData:Se.publicRecordData||Nt.publicRecordData}:Se})})),console.log("[PropertyLab] Enriched existing comps with mlsData from DB")}
53}).catch(()=>{}),console.log("[PropertyLab] Already have selectedComps - skipping full DB load");return}Ho(`/api/comps/selected/${r}`,{throwOnSuccessFalse:!1}).then(ie=>{if(ie.success&&ie.comps?.length>0){if(q&&(g||I)){const we=new Map(ie.comps.map(Nt=>[Nt.id,Nt])),Se=(g?V:re.selectedComps).map(Nt=>{const Ct=we.get(Nt.id)||we.get(Nt.snapshotId);return Ct?{...Nt,lotSize:Nt.lotSize??(Ct.lotSize?Number(Ct.lotSize):void 0),saleDate:Nt.saleDate||Ct.saleDate||void 0,contractDate:Nt.contractDate||Ct.contractDate||void 0,mlsData:K(Nt.mlsData,Ct.mlsData),publicRecordData:Nt.publicRecordData||Ct.publicRecordData||void 0,prLotSize:Nt.prLotSize??Ct.prLotSize,lotSizeAcres:Nt.lotSizeAcres??Ct.lotSizeAcres}:Nt});console.log("[PropertyLab] Enriched",Se.length,"comps with fresh DB data (deep-merged mlsData)"),qe(Nt=>({...Nt,selectedComps:pt(Se.map(Ct=>{const Ht=[Ct.snapshotId,Ct.id,Ct.mlsNumber,Ct.mlsData?.mlsNumber,Ct.mlsData?.MlsListingNumber].filter(ss=>!!ss).reduce((ss,da)=>ss??_u.current[da],void 0),aa=Nt.selectedComps.find(ss=>{const da=ss.mlsNumber||ss.mlsData?.mlsNumber,es=Ct.mlsNumber||Ct.mlsData?.mlsNumber;return ss.id===Ct.id||ss.snapshotId&&ss.snapshotId===(Ct.snapshotId??Ct.id)||da&&es&&da===es})?.gridFieldOverrides,Ft=fO(Ct.gridFieldOverrides,aa,Ht);return Object.keys(Ft).length===0?Ct:{...Ct,gridFieldOverrides:Ft}}))}));const Qe=Se.filter(Nt=>te(Nt)&&Nt.mlsNumber&&!we.has(Nt.id)&&!we.has(Nt.snapshotId));Qe.length>0&&(console.log("[PropertyLab] Looking up",Qe.length,"orphan comps by MLS number"),Promise.all(Qe.map(Nt=>Ho(`/api/comps/mls/${encodeURIComponent(Nt.mlsNumber)}`,{throwOnSuccessFalse:!1}).then(Ct=>({comp:Nt,dbComp:Ct?.success?Ct.comp:null})).catch(()=>({comp:Nt,dbComp:null})))).then(Nt=>{const Ct=new Map;Nt.forEach(({comp:va,dbComp:Ht})=>{Ht&&va.mlsNumber&&Ct.set(va.mlsNumber,Ht)}),Ct.size!==0&&(qe(va=>({...va,selectedComps:va.selectedComps.map(Ht=>{const Cs=Ht.mlsNumber?Ct.get(Ht.mlsNumber):null;return Cs?{...Ht,lotSize:Ht.lotSize??(Cs.lotSize?Number(Cs.lotSize):void 0),saleDate:Ht.saleDate||Cs.saleDate||void 0,contractDate:Ht.contractDate||Cs.contractDate||void 0,mlsData:K(Ht.mlsData,Cs.mlsData),publicRecordData:Ht.publicRecordData||Cs.publicRecordData||void 0}:Ht})})),console.log("[PropertyLab] Enriched",Ct.size,"orphan comps by MLS lookup"))}))}else if(!g&&!I){const we=ie.comps.map(ve=>{const Se=ve.latitude!=null&&ve.longitude!=null,Qe=ve.isStrProperty===!0||ve.is_str_property===!0,Nt=ve.strAverageDailyRate?parseFloat(String(ve.strAverageDailyRate)):void 0,Ct=ve.strOccupancyRate?parseFloat(String(ve.strOccupancyRate)):void 0,va=ve.strGrossRevenue12mo?parseFloat(String(ve.strGrossRevenue12mo)):void 0,Ht=ve.strRating?parseFloat(String(ve.strRating)):void 0;return{id:ve.id,snapshotId:ve.id,address:ve.address,city:ve.city,state:ve.state,zip:ve.zipCode||"",fullAddress:`${ve.address}, ${ve.city}, ${ve.state}`,coordinates:Se?{lat:parseFloat(ve.latitude),lng:parseFloat(ve.longitude)}:void 0,distance:ve.distance||0,status:ve.mlsStatus||ve.status||"CLSD",saleDate:ve.saleDate||void 0,contractDate:ve.contractDate||void 0,listDate:ve.listDate||void 0,price:Number(ve.salePrice)||0,gla:Number(ve.sqft)||Number(ve.gla)||0,beds:ve.bedrooms||ve.beds||0,baths:Number(ve.bathrooms)||Number(ve.baths)||0,yearBuilt:ve.yearBuilt||0,lotSize:ve.lotSize?Number(ve.lotSize):void 0,propertyType:ve.propertyType,photoUrl:ve.photos?.[0]?.originalUrl||ve.photos?.[0]?.url||ve.primaryPhotoUrl,photos:ve.photos?.map(Cs=>typeof Cs=="string"?Cs:Cs.originalUrl||Cs.url)||(ve.primaryPhotoUrl?[ve.primaryPhotoUrl]:[]),selectionState:"selected",publicRecordData:ve.publicRecordData||void 0,mlsData:ve.mlsData||void 0,isStrProperty:Qe,strSource:Qe?ve.strSource:void 0,strProviderId:Qe?ve.strProviderId:void 0,strListingName:Qe?ve.strListingName:void 0,strRentalType:Qe?ve.strRentalType:void 0,strAverageDailyRate:Qe?Nt:void 0,strOccupancyRate:Qe?Ct:void 0,strGrossRevenue12mo:Qe?va:void 0,strRating:Qe?Ht:void 0,strReviewCount:Qe?ve.strReviewCount:void 0,strGuestCapacity:Qe?ve.strGuestCapacity:void 0,strMaxGuests:Qe?ve.strGuestCapacity:void 0,strProvider:Qe?ve.strSource:void 0,strAmenities:Qe?ve.strAmenities:void 0,pool:ve.hasPool||!1,hasPool:ve.hasPool||!1,sqftPR:Eo(ve.prLivingArea)??Eo(ve.publicRecordData?.squareFeet)??Eo(ve.publicRecordData?.livingArea),lotSqftPR:Eo(ve.publicRecordData?.lotSize),yearBuiltPR:Eo(ve.publicRecordData?.yearBuilt),prLivingArea:Eo(ve.prLivingArea),basement:ve.basement??void 0,basementSqft:Eo(ve.basementSqft)??void 0,basementFinishedSqft:Eo(ve.basementFinishedSqft)??Eo(ve.basementFinished)??void 0,basementFullBaths:Eo(ve.basementFullBaths)??void 0,basementHalfBaths:Eo(ve.basementHalfBaths)??void 0,garageSpaces:Eo(ve.garageSpaces)??void 0,garageType:ve.garageType??ve.carStorageType??void 0,carStorageType:ve.carStorageType??void 0,parkingDescription:ve.parkingDescription??void 0,patioFeatures:ve.patioFeatures??void 0,exteriorFeatures:ve.exteriorFeatures??void 0,mlsNumber:ve.mlsNumber||ve.mlsData?.mlsNumber||ve.mlsData?.MlsListingNumber||ve.mlsData?.ListingId||void 0}});console.log("[PropertyLab] Loaded",we.length,"selected comps for assignment",r),qe(ve=>({...ve,selectedComps:pt(we)}))}const ee={};ie.comps.forEach(we=>{we.scenarioTag&&["as-is","after-repaired","both"].includes(we.scenarioTag)&&(ee[we.id]=we.scenarioTag)}),Object.keys(ee).length>0&&(console.log("[PropertyLab] Restored scenario tags for",Object.keys(ee).length,"comps"),gu(ee))}}).catch(ie=>{ie instanceof qo&&ie.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to load selections:",ie)})}},[r,C,Ve]);const RC=o.useRef(new Set),EC=o.useRef(new Set);o.useEffect(()=>{if(!re.selectedComps||re.selectedComps.length===0)return;let g=!1;const I=re.selectedComps.filter(L=>L.mlsNumber&&uO(L)&&!RC.current.has(L.mlsNumber));I.length>
530&&(I.forEach(L=>RC.current.add(L.mlsNumber)),console.log("[PropertyLab] Orphan effect: looking up",I.length,"comps by MLS number"),Promise.all(I.map(L=>Ho(`/api/comps/mls/${encodeURIComponent(L.mlsNumber)}`,{throwOnSuccessFalse:!1}).then(Y=>({mls:L.mlsNumber,dbComp:Y?.success?Y.comp:null})).catch(()=>({mls:L.mlsNumber,dbComp:null})))).then(L=>{if(g)return;const Y=new Map;L.forEach(({mls:K,dbComp:te})=>{te&&Y.set(K,te)}),Y.size!==0&&(qe(K=>({...K,selectedComps:K.selectedComps.map(te=>{const q=te.mlsNumber?Y.get(te.mlsNumber):null;return q?TZ(te,q):te})})),console.log("[PropertyLab] Orphan effect: enriched",Y.size,"comps"))}));const k=re.selectedComps.filter(L=>{if(L.mlsNumber)return!1;const Y=L.snapshotId||L.id;return!!Y&&uO(L)&&!EC.current.has(Y)});if(k.length>0){const L=k.map(Y=>String(Y.snapshotId||Y.id));L.forEach(Y=>EC.current.add(Y)),console.log("[PropertyLab] Orphan effect: looking up",k.length,"comps by snapshot id"),dn("/api/comps/by-ids",{ids:L},{throwOnSuccessFalse:!1}).then(Y=>{if(g)return;const K=Y?.success&&Array.isArray(Y.comps)?Y.comps:[];if(K.length===0)return;const te=new Map;K.forEach(q=>{q?.id&&te.set(String(q.id),q)}),te.size!==0&&(qe(q=>({...q,selectedComps:q.selectedComps.map(ie=>{const ee=String(ie.snapshotId||ie.id||""),we=ee?te.get(ee):null;return we?IZ(ie,we):ie})})),console.log("[PropertyLab] Orphan effect: enriched",te.size,"comps by snapshot id"))}).catch(Y=>{console.error("[PropertyLab] Orphan effect: id-based lookup failed",Y)})}return()=>{g=!0}},[re.selectedComps]);const yy=o.useCallback(async g=>{if(!g||g.length===0)return[];try{console.log("[PropertyLab] Hydrating",g.length,"property cards from database");const I=await dn("/api/market-session/hydrate-cards",{propertyIds:g},{throwOnSuccessFalse:!1});return I.success&&I.cards?.length>0?(console.log("[PropertyLab] Hydrated",I.cards.length,"of",g.length,"cards from database"),I.cards):(console.log("[PropertyLab] Hydration returned no cards"),[])}catch(I){return console.error("[PropertyLab] Hydration failed:",I),[]}},[]);o.useEffect(()=>{if(!r){Ps(!0);return}Ps(!1);const g=k=>{console.warn(`[PropertyLab] Lock reconcile → unlocked (${k}); running fallback search`),ei.current=!1,Zl(!1),setTimeout(()=>{Nr.current&&!Qn.current?Nr.current():En.current=!0},100)};(async()=>{try{const k=du.current;let L;if(k&&vZ(k)?(console.log("[PropertyLab] Hydrating locks from slim payload (pre-enriched) — skipping /api/market-session/locks GET"),L=NZ(k)):L=await Ho(`/api/market-session/locks/${r}`,{throwOnSuccessFalse:!1}),!L.success)Zl(!1),qc(!1),lO({classification:"missing",restoredCardCount:0,clientBelievedLocked:tc.current===!0})&&g("no lock state on server");else{if(L.marketLock?.locked?(console.log("[PropertyLab] Restoring market lock with",L.marketLock.salesData?.length||0,"sales"),Zl(!0),sm(L.marketLock.stats||null),$r(L.marketLock.propertyCount||null),Ao(L.marketLock.resultIds||null),im(L.marketLock.salesData||[]),om(L.marketLock.boundaries||[]),nu(L.marketLock.radiusMiles||null),xc(h1(L.marketLock.shapes)),L.marketLock.filters&&Uo(L.marketLock.filters),L.marketLock.utilityBands&&Uu(L.marketLock.utilityBands)):(Zl(!1),lO({classification:xZ(L.marketLock),restoredCardCount:0,clientBelievedLocked:tc.current===!0})&&g("market lock row missing")),L.submarketLock?.locked){if(console.log("[PropertyLab] Restoring sub-market lock with",L.submarketLock.salesData?.length||0,"sales"),qc(!0),nm(L.submarketLock.stats||null),tl(L.submarketLock.propertyCount||null),li(L.submarketLock.resultIds||null),gl(L.submarketLock.salesData||[]),L.submarketLock.propertyCards&&L.submarketLock.propertyCards.length>0){console.log("[PropertyLab] Restoring",L.submarketLock.propertyCards.length,"submarket property cards from lock"),ei.current=!0,En.current=!1;const te=L.submarketLock.propertyCards.map(q=>({id:q.id,snapshotId:r0(q),mlsNumber:q.mlsNumber||null,mlsBoard:i0({mlsBoard:q.mlsBoard,mlsData:q.mlsData})||null,address:q.address||"",city:q.city||"",state:q.state||"",zip:q.zip||"",price:q.price||0,listPrice:q.listPrice,beds:q.beds,baths:q.baths,fullBathrooms:q.fullBathrooms??null,halfBathrooms:q.halfBathrooms??null,sqft:q.sqft,sqftPR:q.sqftPR||q.prLivingArea||null,lotSqft:q.lotSqft,lotSqftPR:q.lotSqftPR||null,yearBuilt:q.yearBuilt,yearBuiltPR:q.yearBuiltPR||null,status:q.status||"CLSD",saleDate:q.saleDate,listDate:q.listDate,dom:q.dom||0,distance:q.distance,style:q.style,stories:q.stories,garageSpaces:q.garageSpaces,coordinates:q.coordinates,photos:q.photos||[],photoUrl:q.photoUrl,photoCount:q.photoCount||0,propertyType:q.propertyType||"SFR",similarityScore:q.similarityScore,matchScore:q.matchScore,pricePerSqft:q.pricePerSqft,mlsData:q.mlsData,echoLocationScore:q.echoLocationScore,conditionRating:q.conditionRating,conditionSource:q.conditionSource,qualityRating:q.qualityRating,qualitySource:q.qualitySource,btNormalizedGla:q.btNormalizedGla??null,btGlaSource:q.btGlaSource??null,btGlaConfidence:q.btGlaConfidence??null,btGlaNormNote:q.btGlaNormNote??null,btDesignStyle:q.btDesignStyle??null,btStyleConfidence:q.btStyleConfidence??null,mlsAboveGradeArea:q.mlsAboveGradeArea??null,mlsTotalLivingArea:q.mlsTotalLivingArea??null,prLivingArea:q.prLivingArea??null,roomMathGla:q.roomMathGla??null,roomMathFactor:q.roomMathFactor??null,roomCount:q.roomCount??null,roomMathAgreement:q.roomMathAgreement??null,glaSanityFlag:q.glaSanityFlag??null,distressedYN:q.distressedYN??null,distressType:q.distressType??null,specialListingConditions:q.specialListingConditions??null}));Jl(te)}L.submarketLock.filters&&Hc(L.submarketLock.filters),Sp(L.submarketLock.boundaries||[]),vp(L.submarketLock.radiusMiles||null),ao(h1(L.submarketLock.shapes)),L.submarketLock.utilityBands&&yp(L.submarketLock.utilityBands)}else qc(!1);const Y=L.marketLock?.propertyCards&&L.marketLock.propertyCards.length>0,K=L.marketLock?.resultIds&&L.marketLock.resultIds.length>0;
53if(Y&&(En.current=!1),Y){console.log("[PropertyLab] Restoring",L.marketLock.propertyCards.length,"full property cards from lock"),ei.current=!0;const te=L.marketLock.propertyCards.map(q=>({id:q.id,snapshotId:r0(q),mlsNumber:q.mlsNumber||null,mlsBoard:i0({mlsBoard:q.mlsBoard,mlsData:q.mlsData})||null,address:q.address||"",city:q.city||"",state:q.state||"",zip:q.zip||"",price:q.price||0,listPrice:q.listPrice,beds:q.beds,baths:q.baths,fullBathrooms:q.fullBathrooms??null,halfBathrooms:q.halfBathrooms??null,sqft:q.sqft,sqftPR:q.sqftPR||q.prLivingArea||null,lotSqft:q.lotSqft,lotSqftPR:q.lotSqftPR||null,yearBuilt:q.yearBuilt,yearBuiltPR:q.yearBuiltPR||null,status:q.status||"CLSD",saleDate:q.saleDate,listDate:q.listDate,dom:q.dom||0,distance:q.distance,style:q.style,stories:q.stories,garageSpaces:q.garageSpaces,coordinates:q.coordinates,photos:q.photos||[],photoUrl:q.photoUrl||q.photos?.[0]||null,photoCount:q.photoCount||q.photos?.length||0,photosStatus:q.photosStatus,propertyType:q.propertyType||"SFR",similarityScore:q.similarityScore,matchScore:q.matchScore,matchBreakdown:q.matchBreakdown,avmScore:q.avmScore,avmAdjustedPrice:q.avmAdjustedPrice,isSelected:q.isSelected,pricePerSqft:q.pricePerSqft,propMixCachedAt:q.propMixCachedAt,mlsData:q.mlsData,echoLocationScore:q.echoLocationScore,conditionRating:q.conditionRating,conditionSource:q.conditionSource,qualityRating:q.qualityRating,qualitySource:q.qualitySource,isStrProperty:q.isStrProperty,strListingName:q.strListingName,strNightlyRate:q.strNightlyRate,strAverageDailyRate:q.strAverageDailyRate,strOccupancyRate:q.strOccupancyRate,strGrossRevenue12mo:q.strGrossRevenue12mo,strRating:q.strRating,strReviewCount:q.strReviewCount,strMaxGuests:q.strMaxGuests,strProvider:q.strProvider,strListingUrl:q.strListingUrl,btNormalizedGla:q.btNormalizedGla??null,btGlaSource:q.btGlaSource??null,btGlaConfidence:q.btGlaConfidence??null,btGlaNormNote:q.btGlaNormNote??null,btDesignStyle:q.btDesignStyle??null,btStyleConfidence:q.btStyleConfidence??null,mlsAboveGradeArea:q.mlsAboveGradeArea??null,mlsTotalLivingArea:q.mlsTotalLivingArea??null,prLivingArea:q.prLivingArea??null,roomMathGla:q.roomMathGla??null,roomMathFactor:q.roomMathFactor??null,roomCount:q.roomCount??null,roomMathAgreement:q.roomMathAgreement??null,glaSanityFlag:q.glaSanityFlag??null,distressedYN:q.distressedYN??null,distressType:q.distressType??null,specialListingConditions:q.specialListingConditions??null}));_o(te),console.log("[PropertyLab] Restored",te.length,"full property cards")}else if(!K)console.log("[PropertyLab] Market lock has no resultIds or propertyCards - falling back to normal search"),setTimeout(()=>{Nr.current&&!Qn.current?Nr.current():En.current=!0},100);else if(K){console.log("[PropertyLab] Restoring locked market - silently fetching",L.marketLock.resultIds.length,"properties from cache (legacy mode)");let te=s;if(!te&&L.marketLock.boundaries?.length>0){const q=L.marketLock.boundaries[0];if(q.polygon?.length>0){const ie=q.polygon.map(we=>we.lat),ee=q.polygon.map(we=>we.lng);te={lat:ie.reduce((we,ve)=>we+ve,0)/ie.length,lng:ee.reduce((we,ve)=>we+ve,0)/ee.length}}}if(te&&r)try{const q={assignmentId:r,lat:te.lat,lng:te.lng},ie=await dn("/api/comps/cached-search/thin",q,{throwOnSuccessFalse:!1});if(ie.cached&&ie.comps?.length>0){const ee=new Set(L.marketLock.resultIds),we=ie.comps.filter(Se=>ee.has(Se.mlsNumber)||ee.has(Se.snapshotId)||ee.has(Se.id));if(console.log("[PropertyLab] Silent cache fetch: got",ie.comps.length,"cached, filtered to",we.length,"locked properties"),we.length===0){console.log("[PropertyLab] No cac
53hed comps match locked resultIds - hydrating from database"),ei.current=!0;const Se=L.marketLock.resultIds?.length>0?await yy(L.marketLock.resultIds):[],Qe=US(Se,L.marketLock.resultIds,L.marketLock.salesData);Qe.cards.length>0?(_o(Qe.cards),console.log("[PropertyLab] Hydrated",Qe.cards.length,"cards from database (cache ID mismatch)")):(_o([]),qS("cache-mismatch",Qe.reason,L.marketLock),g("legacy lock hydration empty (cache-mismatch)"));return}const ve=we.map(Se=>({id:Se.id,snapshotId:Se.snapshotId||Se.id,address:Se.address||"",city:Se.city||"",state:Se.state||"",zip:Se.zipCode||Se.zip||"",price:Se.salePrice||Se.listPrice||0,beds:Se.beds||0,baths:Se.baths||0,fullBathrooms:Se.fullBathrooms??Se.mlsData?.BathroomsFull??null,halfBathrooms:Se.halfBathrooms??Se.mlsData?.BathroomsHalf??null,sqft:Se.gla||Se.sqft||0,sqftPR:Eo(Se.prLivingArea)??Eo(Se.publicRecordData?.squareFeet)??Eo(Se.publicRecordData?.livingArea)??Eo(Se.glaPR)??Eo(Se.sqftPR),lotSqft:Se.lotSize||Se.lotSqft||0,lotSqftPR:Eo(Se.publicRecordData?.lotSize)??Eo(Se.lotSqftPR),yearBuilt:Se.yearBuilt||0,yearBuiltPR:Eo(Se.publicRecordData?.yearBuilt)??Eo(Se.yearBuiltPR),status:Se.status||"CLSD",saleDate:Se.saleDate||Se.closeDate||null,listDate:Se.listDate||null,contractDate:Se.contractDate||null,dom:Se.dom||0,distance:Se.distance||0,style:Se.style||"",coordinates:Se.coordinates,mlsId:Se.mlsId||Se.mlsNumber||"",photos:Se.photos||[],photoUrl:Se.photoUrl||Se.primaryPhotoUrl||Se.photos?.[0]||null,primaryPhotoUrl:Se.photoUrl||Se.primaryPhotoUrl||Se.photos?.[0]||null,photoCount:Se.photoCount||Se.photos?.length||0,mlsData:Se.mlsData,publicRecordData:Se.publicRecordData,source:Se.source||"cache",dq:Se.dq||null,btNormalizedGla:Se.btNormalizedGla??null,btDesignStyle:Se.btDesignStyle??null,btStyleConfidence:Se.btStyleConfidence??null,btGlaSource:Se.btGlaSource??null,btGlaConfidence:Se.btGlaConfidence??null,btGlaNormNote:Se.btGlaNormNote??null,mlsAboveGradeArea:Se.mlsAboveGradeArea??null,mlsTotalLivingArea:Se.mlsTotalLivingArea??null,prLivingArea:Se.prLivingArea??null,roomMathGla:Se.roomMathGla??null,roomMathFactor:Se.roomMathFactor??null,roomCount:Se.roomCount??null,roomMathAgreement:Se.roomMathAgreement??null,glaSanityFlag:Se.glaSanityFlag??null}));_o(ve),ei.current=!0,console.log("[PropertyLab] Locked property cards restored from cache:",ve.length,"- marking lockedDataRestoredRef=true")}else{console.log("[PropertyLab] Silent cache miss or empty - hydrating from database"),ei.current=!0;const ee=L.marketLock.resultIds?.length>0?await yy(L.marketLock.resultIds):[],we=US(ee,L.marketLock.resultIds,L.marketLock.salesData);we.cards.length>0?(_o(we.cards),console.log("[PropertyLab] Hydrated",we.cards.length,"cards from database (cache miss)")):(_o([]),qS("cache-miss",we.reason,L.marketLock),g("legacy lock hydration empty (cache-miss)"))}}catch(q){console.error("[PropertyLab] Silent cache fetch failed:",q),ei.current=!0;const ie=L.marketLock.resultIds?.length>0?await yy(L.marketLock.resultIds):[],ee=US(ie,L.marketLock.resultIds,L.marketLock.salesData);ee.cards.length>0?(_o(ee.cards),console.log("[PropertyLab] Hydrated",ee.cards.length,"cards from database (cache error fallback)")):(_o([]),qS("cache-error",ee.reason,L.marketLock),g("legacy lock hydration empty (cache-error)"))}
53else{console.log("[PropertyLab] No cache coords - hydrating from database directly"),ei.current=!0;const q=L.marketLock.resultIds?.length>0?await yy(L.marketLock.resultIds):[],ie=US(q,L.marketLock.resultIds,L.marketLock.salesData);ie.cards.length>0?(_o(ie.cards),console.log("[PropertyLab] Hydrated",ie.cards.length,"cards from database (no coords)")):(_o([]),qS("no-coords",ie.reason,L.marketLock),g("legacy lock hydration empty (no-coords)"))}}}}catch(k){k instanceof qo&&k.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):(console.error("[PropertyLab] Failed to load locked state:",k),tc.current===!0&&g("locks GET failed"))}finally{Ps(!0)}try{const k=await fetch(`/api/time-adj/sessions?assignmentId=${encodeURIComponent(r)}`,{credentials:"include"});if(k.ok){const L=await k.json();if(L&&L.decisionSavedAt){const Y=L.selectedOption==="zero"||L.finalMethod==="zero",K=L.linearRatePctPerMonth,te=Y?0:typeof K=="string"?parseFloat(K):K;if(te!=null&&Number.isFinite(te)){const q=L.selectedOption==="submarket"?"submarket":"market";lu(q),Jm(te),console.log("[PropertyLab] Hydrated time-adj lock from TimeVault session:",`${te>=0?"+":""}${te.toFixed(2)}%/mo (${q})`)}}}}catch(k){console.warn("[PropertyLab] Time-adj session hydration failed (non-blocking):",k)}})()},[r,Ve]),o.useEffect(()=>{const g=s?.lat,I=s?.lng,k=`${g??"none"}:${I??"none"}`;if(Sf.current.has(k))return;Sf.current.add(k),(async()=>{try{const Y=new URLSearchParams;s&&(Y.set("lat",String(s.lat)),Y.set("lng",String(s.lng)));const K=await Ho(`/api/saved-searches?${Y}`,{throwOnSuccessFalse:!1});K.success&&K.searches&&Qm(K.searches)}catch(Y){Y instanceof qo&&Y.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to load saved searches:",Y)}})()},[s?.lat,s?.lng]),o.useEffect(()=>{if(!r)return;(async()=>{try{const k=(await Ho(`/api/v2/orders/${r}`,{throwOnSuccessFalse:!1}))?.marketStates;Array.isArray(k)&&Vo(k)}catch(I){console.error("[PropertyLab] Failed to load order market states:",I)}})()},[r]),o.useEffect(()=>{(async()=>{try{const I=await Ho("/api/market-library",{throwOnSuccessFalse:!1});Array.isArray(I)&&Ir(I)}catch(I){console.error("[PropertyLab] Failed to load library searches:",I)}})()},[]);const nF=o.useCallback(async g=>{kg(!0);try{const I=Ks||s,k=await dn("/api/saved-searches",{name:g,filters:re.filters,marketArea:{radiusMiles:re.marketDefinition?.radiusMiles,boundaries:js},centerLat:I?.lat,centerLng:I?.lng},{throwOnSuccessFalse:!1});k.success&&k.search&&(Qm(L=>[k.search,...L]),Ve({title:"Search Saved",description:`"${g}" saved for quick reuse`}))}catch(I){I instanceof qo&&I.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):(console.error("[PropertyLab] Failed to save search:",I),Ve({title:"Save Failed",description:"Could not save search",variant:"destructive"}))}finally{kg(!1)}},[Ks,s,re.filters,re.marketDefinition,js,Ve]),iF=o.useCallback(g=>{g.filters&&qe(k=>({...k,filters:{...k.filters,...g.filters}})),g.marketArea?.radiusMiles&&qe(k=>({...k,marketDefinition:{...k.marketDefinition,radiusMiles:g.marketArea.radiusMiles,totalProperties:k.marketDefinition?.totalProperties||0}}));const I=g.marketArea?.boundaries??[];console.log("[PropertyLab] handleLoadSearch: loading boundaries:",I.length,I.map(k=>({name:k.name,hasPolygon:!!k.polygon}))),Xl.current=!0,bo(I),Ve({title:"Search Loaded",description:`Applied "${g.name}"`}),setTimeout(()=>{Xl.current=!1,!Qn.current&&Nr.current?Nr.current():Nr.current&&(console.log("[PropertyLab] Load search deferred, queuing pending search"),En.current=!0)},150)},[Ve]),oF=o.useCallback(async g=>{try{await Wy(`/api/saved-searches/${g}`),Qm(I=>I.filter(k=>k.id!==g)),Ve({title:"Search Deleted"})}catch(I){I instanceof qo&&I.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to delete search:",I)}},[Ve]),wC=o.useCallback(g=>{g.filters&&qe(I=>({...I,filters:{...I.filters,...g.filters}}
53)),g.radiusMiles&&qe(I=>({...I,marketDefinition:{...I.marketDefinition,radiusMiles:parseFloat(g.radiusMiles),totalProperties:I.marketDefinition?.totalProperties||0}})),g.boundaries&&(console.log("[PropertyLab] handleApplyOrderState: loading boundaries:",g.boundaries.length,g.boundaries.map(I=>({name:I.name,hasPolygon:!!I.polygon,hasCoords:!!I.polygon?.coordinates}))),Xl.current=!0,bo(g.boundaries)),Ve({title:"State Applied",description:`Applied "${g.name}"`}),setTimeout(()=>{Xl.current=!1,!Qn.current&&Nr.current?Nr.current():Nr.current&&(En.current=!0)},150)},[Ve]),PC=o.useCallback(async g=>{g.filters&&qe(I=>({...I,filters:{...I.filters,...g.filters}})),g.radiusMiles&&qe(I=>({...I,marketDefinition:{...I.marketDefinition,radiusMiles:parseFloat(g.radiusMiles),totalProperties:I.marketDefinition?.totalProperties||0}})),g.boundaries&&bo(g.boundaries),Ve({title:"Library Search Applied",description:`Applied "${g.name}"`});try{await dn(`/api/market-library/${g.id}/use`,{},{throwOnSuccessFalse:!1}),Ir(I=>I.map(k=>k.id===g.id?{...k,useCount:(k.useCount||0)+1}:k))}catch(I){console.error("[PropertyLab] Failed to increment use count:",I)}setTimeout(()=>{!Qn.current&&Nr.current?Nr.current():Nr.current&&(En.current=!0)},100)},[Ve]),lF=o.useCallback(async(g,I)=>{try{const k=await dn("/api/market-library",{name:I,filters:g.filters,boundaries:g.boundaries,polygon:g.polygon,center:g.center,radiusMiles:g.radiusMiles,salesCount:g.salesCount},{throwOnSuccessFalse:!1});k?.id&&(Ir(L=>[k,...L]),Ve({title:"Added to Library",description:`"${I}" saved to your library`}))}catch(k){k instanceof qo&&k.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):(console.error("[PropertyLab] Failed to add to library:",k),Ve({title:"Save Failed",description:"Could not add to library",variant:"destructive"}))}},[Ve]),cF=o.useCallback(async g=>{try{await Wy(`/api/market-library/${g}`),Ir(I=>I.filter(k=>k.id!==g)),Ve({title:"Library Search Deleted"})}catch(I){I instanceof qo&&I.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to delete library search:",I)}},[Ve]);o.useCallback(g=>{Tn(g.coordinates),g.bounds?Ka(void 0):g.types.includes("postal_code")?Ka(13):g.types.includes("locality")?Ka(12):Ka(15),la(null),Ve({title:"Location updated",description:`Searching near ${g.address}`})},[Ve]);const[WX,KX]=o.useState(!1),[VN,dF]=o.useState(!1);o.useEffect(()=>{const g=requestAnimationFrame(()=>dF(!0));return()=>cancelAnimationFrame(g)},[]);const uF=C&&Us!=="rental"?re.selectedComps.map(g=>g.snapshotId??"").join("|"):"",jc=o.useMemo(()=>{if(!VN)return[];const g=new Map,I=new Set,k=Ft=>{let ss=Ft.address||"";!ss&&Ft.fullAddress&&(ss=Ft.fullAddress.split(",")[0]||"");const da=ss.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim(),es=(Ft.city||"").toLowerCase().replace(/[^a-z0-9]/g,""),Js=(Ft.state||"").toLowerCase().replace(/[^a-z]/g,""),er=(Ft.zip||"").replace(/[^0-9]/g,"").slice(0,5);return da&&(es||er)?`${da}-${es||er}-${Js}`:da&&Js?`${da}-${Js}`:""},L=Ft=>!!(Ft.photos&&Ft.photos.length>0||Ft.photoUrl),Y=(Ft,ss)=>{if(g.has(ss)){const es=g.get(ss);return!L(es)&&L(Ft)&&g.set(ss,Ft),!1}const da=k(Ft);if(da&&I.has(da)){if(L(Ft)){for(const[es,Js]of g)if(k(Js)===da&&!L(Js)){g.set(es,{...Js,photos:Ft.photos,photoUrl:Ft.photoUrl});break}}return!1}return g.set(ss,Ft),da&&I.add(da),!0},K=()=>re.properties.forEach(Ft=>{Y(Ft,Ft.snapshotId||Ft.id)}),te=()=>mu.current.forEach(Ft=>{Y(Ft,Ft.snapshotId||Ft.id)});C&&Us!=="rental"?(te(),K()):(K(),te()),qt&&qt.length>0&&Kr.forEach(Ft=>{const ss=Ft.snapshotId||Ft.id;qt.includes(ss)&&Y(Ft,ss)});const q=xo||js.length>0;Kr.length>0&&q?(console.log("[PropertyLab] Including cached sales:",Kr.length,"boundaries:",js.length,"hasDrawnShapes:",xo),Kr.forEach(Ft=>{Y(Ft,Ft.snapshotId||Ft.id)})):Kr.length>0&&console.log("[PropertyLab] Skipping cached sales (no active geometry):",Kr.length);const ie=new Map,ee=new Map;Fn?.rankedComps&&Fn.rankedComps.forEach(Ft=>{const ss={score:Ft.reconciliationScore,adjustedPrice:Ft.adjustedPrice};ie.set(Ft.id,ss);const da=Ft.address?.toLowerCase().replace(/[^a-z0-9]/g,"")||"";da&&ee.set(da,ss)});const we=Array.from(g.values()),ve=lb,Se=s?.lat,Qe=s?.lng,Nt=re.marketDefinition?.radiusMiles,Ct=NQ(js),va=!Ct;let Ht=we;if(Nt&&Se&&Qe&&Ct){const Ft=new Set(mu.current.map(da=>da.snapshotId||da.id)),ss=new Set(qt||[]);Ht=we.filter(da=>{const es=da.snapshotId||da.id;return Ft.has(es)||ss.has(es)?!0:da.coordinates?ve(Se,Qe,da.coordinates.lat,da.coordinates.lng)<=Nt:!1})}console.log("[PropertyLab] propertyCards memo: search:",re.properties.length,"selected:",mu.current.length,"combined:",we.length,"afterRadiusFilter:",Ht.length,"radiu
53s:",Nt,"polygonBoundary:",va,"avmScores:",ie.size);const Cs=jm(a||""),aa=nO({address:as?.address||Cs?.street||a,city:as?.city||Cs?.city,state:as?.state||Cs?.state,zip:as?.zip||Cs?.zip});return Ht.map(Ft=>{Se&&Qe&&Ft.coordinates&&(Ft={...Ft,distance:Math.round(ve(Se,Qe,Ft.coordinates.lat,Ft.coordinates.lng)*100)/100});const ss=Vb(Ft,!1);if(aa&&!ss.isSubject){const er=nO({address:ss.address||(Ft.fullAddress?Ft.fullAddress.split(",")[0]:""),city:ss.city,state:ss.state,zip:ss.zipCode});er&&er===aa&&(ss.isSameAsSubject=!0)}const da=Ft.snapshotId||Ft.id,es=Pc(Ft);es&&da!==es?Ui([da,es,Ft.id]):Ft.snapshotId&&Ft.id&&Ft.snapshotId!==Ft.id&&Ui([Ft.snapshotId,Ft.id]);let Js=ie.get(da)||ie.get(Ft.id);if(!Js&&Ft.snapshotId&&(Js=ie.get(Ft.snapshotId)),!Js&&(Ft.address||Ft.fullAddress)){const er=(Ft.address||Ft.fullAddress||"").toLowerCase().replace(/[^a-z0-9]/g,"");Js=ee.get(er)}return Js&&(ss.avmScore=Js.score,ss.avmAdjustedPrice=Js.adjustedPrice),ss})},[VN,re.properties,qt,Kr,Fn,js,xo,re.marketDefinition?.radiusMiles,a,as?.address,as?.city,as?.state,as?.zip,C,Us,uF]);$g.current=jc;const pF=o.useMemo(()=>{let g=0,I=0,k=0;for(const L of jc){const Y=jN(L.status);Y==="active"?g+=1:Y==="underContract"?I+=1:Y==="contingent"&&(k+=1)}return{active:g,underContract:I,contingent:k}},[jc]);o.useEffect(()=>{if(jc.length===0)return;const g=new Map;for(const I of jc)if(I.conditionRating||I.qualityRating){const k=I.snapshotId||I.id;if(!Dr.current.has(k)){g.set(k,{condition:I.conditionRating??void 0,quality:I.qualityRating??void 0,confidence:.8});const L=Pc(I);L&&rn.current.add(L)}}g.size>0&&(console.log("[PropertyLab] Pre-seeding compAiCache from API data:",g.size,"comps"),kl(I=>{const k=new Map(I);let L=!1;return g.forEach((Y,K)=>{I.has(K)||(k.set(K,Y),L=!0)}),L?k:I}))},[jc]);const Cf=o.useMemo(()=>{const g=Ma.circles.length>0,I=Ma.polygons.length>0,k=js.length>0;return g||I||k},[Ma.circles.length,Ma.polygons.length,js.length]),ch=o.useMemo(()=>{const g=[];for(const I of js)if(I.polygon)try{let k;I.polygon.type==="MultiPolygon"?k=vI(I.polygon.coordinates):k=NI(I.polygon.coordinates);const L=rL(k,{reverse:!1});g.push({id:I.id,turfPoly:L})}catch(k){console.error("[PropertyLab] Error pre-computing boundary polygon:",I.id,k)}return g},[js]),[Sy,Kg]=o.useState(null),[mF,Qg]=o.useState(!1),Nb=o.useRef(0),OC=o.useRef(!1);o.useEffect(()=>{const g=typeof re.filters.remarksSearch=="string"?re.filters.remarksSearch.trim():"";if(!g||OC.current){Nb.current++,Kg(null),Qg(!1);return}const I=++Nb.current,k=setTimeout(async()=>{try{const L=[...mr,...Nn,...jc],Y=g.toLowerCase(),K=new Set,te=[];for(const ee of L){if(ee.isStrProperty)continue;const we=ee.snapshotId||ee.id;if(!we||K.has(we))continue;K.add(we);const ve=ee.mlsData?.publicRemarks||ee.description||"";if(!(!ve||typeof ve!="string"||!ve.trim())&&!MV(ee,Y)&&(te.push({id:we,remarks:ve}),te.length>=500))break}if(te.length===0){I===Nb.current&&(Kg(new Set),Qg(!1));return}const q=await fetch("/api/comps/semantic-remarks",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({query:g,candidates:te})}),ie=await q.json().catch(()=>null);if(I!==Nb.current)return;q.ok&&ie?.success?(Kg(new Set((ie.matches??[]).map(ee=>ee.id))),Qg(!1)):ie?.unavailable?(OC.current=!0,Kg(null),Qg(!1)):(Kg(null),Qg(!0))}catch(L){console.warn("[PropertyLab] Semantic remarks lookup failed, exact-only:",L),I===Nb.current&&(Kg(null),Qg(!0))}},450);return()=>clearTimeout(k)},[re.filters.remarksSearch,jc,Nn,mr]);const Xr=o.useMemo(()=>{const g=Zs==="market"&&Nn.length>0,I=Zs==="submarket"&&mr.length>0,k=!g&&(I||Fr&&mr.length>0),L=!k&&(g||Tr&&Nn.length>0);let Y=k?mr:L?Nn:jc;const K=k||L,te=k?mr:L?Nn:null;if(te&&te.length>0){const ga=new Map,As=new Map;Fn?.rankedComps?.length&&Fn.rankedComps.forEach(Ya=>{const Aa={score:Ya.reconciliationScore,adjustedPrice:Ya.adjustedPrice};ga.set(Ya.id,Aa);const ns=Ya.address?.toLowerCase().replace(/[^a-z0-9]/g,"")||"";ns&&As.set(ns,Aa)}),Y=te.map(Ya=>{const Aa=Ya.snapshotId||Ya.id;let ns={...Ya},Sr=ga.get(Aa)||ga.get(Ya.id);if(!Sr&&Ya.address){const Or=Ya.address.toLowerCase().replace(/[^a-z0-9]/g,"");Sr=As.get(Or)}return Sr&&!ns.avmScore&&(ns.avmScore=Sr.score,ns.avmAdjustedPrice=Sr.adjustedPrice),ns})}if(K&&jc.length>0){const ga=re.filters.statusSelection,{merged:As,freshMatches:Ya}=gZ(Y,jc,ga);Ya.length>0&&(console.log("[PropertyLab] Merging",Ya.length,"fresh search results (statuses:",Array.from(new Set(Ya.map(Aa=>Aa.status))).join(","),") into locked",k?"submarket":"market","data"),Y=As)}if(k&&Er){const ga=Y.length;Y=dO(Y,ro,Er),Y.length!==ga&&console.log("[PropertyLab] Dropped",ga-Y.length,"cards outside the locked submarket geometry")}const q=Si.current,ie=Dr.current;Y=Y.map(ga=>{const As=ga.snapshotId||ga.id,Ya=uo(q,As),Aa=uo(ie,As);if(!Ya&&!Aa)return ga;const ns={...ga};return Ya&&!ns.echoLocationScore&&(ns.echoLocationScore=Ya),Aa&&(Aa.condition&&!ns.conditionRating&&(ns.conditionRating=Aa.condition,ns.conditionSource="ai"),Aa.quality&&!ns.qualityRating&&(ns.qualityRating=Aa.quality,ns.qualitySource="ai"),Aa.btDesignStyle&&!ns.btDesignStyle&&(ns.btDesignStyle=Aa.btDesignStyle)),ns});const ee=ro,we=k?ru:L?bp:null,ve=(()=>
53{if(!we)return null;const ga=we.glaBySource;if(ga){if(qn==="mls"&&ga.mls)return ga.mls;if(qn==="public-record"&&ga.pr)return ga.pr;if(qn==="ai"&&ga.ai)return ga.ai}return we.gla})();ve&&(Y=Y.map(ga=>{const As=qn==="mls"?ga.sqft??ga.btNormalizedGla:qn==="public-record"?ga.sqftPR??ga.sqft:ga.btNormalizedGla??ga.sqft;if(As&&As>0){const Ya=Yx(As,ve);if(Ya!==ga.glaBandTier)return{...ga,glaBandTier:Ya}}return ga}));let Se=[];if(Da==="sales"?Se=Y:Da==="rentals"?Se=pi:Se=[...Y,...pi],!Cf){if(Da==="sales")return console.log("[PropertyLab] No geometry active (sales mode), showing only selected comps:",ee.size),Se.filter(As=>ee.has(As.snapshotId||As.id)).sort((As,Ya)=>(As.dom??0)-(Ya.dom??0));if(U)return console.log("[PropertyLab] No geometry active (STR mode), showing only selected comps:",ee.size),EQ(Se,ee);console.log("[PropertyLab] No geometry active (rentals/all mode), showing STR props + selected comps")}let Qe=[...Se];const Nt=!Cf&&Da!=="sales",Ct=Ma.circles.length>0||Ma.polygons.length>0;if(!Nt&&Ct){const ga=Ma.circles,As=Ma.polygons;console.log("[PropertyLab] Filtering",Qe.length,"properties against",ga.length,"circles,",As.length,"polygons"),Qe=Qe.filter(Ya=>{const Aa=Ya.snapshotId||Ya.id;return ee.has(Aa)?!0:Ya.coordinates?FE(Ya.coordinates,ga)||_E(Ya.coordinates,As):qt?qt.includes(Aa):!1}),console.log("[PropertyLab] After drawn shapes filter:",Qe.length)}const va=Fr&&mr.length>0;if(!Nt&&ch.length>0&&!va){console.log("[PropertyLab] Filtering by",ch.length,"boundaries (UNION semantics)"),ch.forEach((Ya,Aa)=>{const ns=Ya.turfPoly.geometry?.coordinates;if(ns&&ns[0]){const Sr=ns[0],Or=Sr.map(Ti=>Ti[1]),Li=Sr.map(Ti=>Ti[0]);console.log(`[PropertyLab] Boundary ${Aa} (${Ya.id}): lat range [${Math.min(...Or).toFixed(4)}, ${Math.max(...Or).toFixed(4)}], lng range [${Math.min(...Li).toFixed(4)}, ${Math.max(...Li).toFixed(4)}], ${Sr.length} points`)}});const ga=Qe.length;let As=0;Qe=Qe.filter(Ya=>{const Aa=Ya.snapshotId||Ya.id;if(ee.has(Aa))return!0;if(!Ya.coordinates)return!1;const ns=bv([Ya.coordinates.lng,Ya.coordinates.lat]),Sr=ch.some(Or
53=>{try{return aT(ns,Or.turfPoly)}catch{return!1}});return!Sr&&As<5&&(console.log(`[PropertyLab] Property OUTSIDE boundary: lat=${Ya.coordinates.lat.toFixed(5)}, lng=${Ya.coordinates.lng.toFixed(5)} - ${Ya.address||"unknown"}`),As++),Sr&&console.log(`[PropertyLab] Property INSIDE boundary: lat=${Ya.coordinates.lat.toFixed(5)}, lng=${Ya.coordinates.lng.toFixed(5)} - ${Ya.address||"unknown"}`),Sr}),console.log("[PropertyLab] After boundary filter:",Qe.length,"of",ga)}if(!Nt&&ee.size>0){const ga=k&&!!Er,As=Ct||ch.length>0;if(ga||As){const Ya=Aa=>{if(ga)return LM(Aa,Er);if(Ct&&!(FE(Aa,Ma.circles)||_E(Aa,Ma.polygons)))return!1;if(ch.length>0){const ns=bv([Aa.lng,Aa.lat]);if(!ch.some(Or=>{try{return aT(ns,Or.turfPoly)}catch{return!1}}))return!1}return!0};Qe=Qe.map(Aa=>{if(!ee.has(Aa.snapshotId||Aa.id))return Aa;const ns=!!Aa.coordinates&&!Ya(Aa.coordinates);return ns===!!Aa.keptOutsideBoundary?Aa:{...Aa,keptOutsideBoundary:ns}})}}const Ht=Qe.length,Cs=Qe.filter(ga=>ee.has(ga.snapshotId||ga.id)),aa=Qe.filter(ga=>!ee.has(ga.snapshotId||ga.id)),Ft=(()=>{const ga=re.filters.statusSelection;if(!ga?.length)return Cs;const As=new Set(ga),Ya=new Set(ga.map(Aa=>FV[Aa]).filter(Boolean));return Cs.filter(Aa=>{const ns=Aa.status;return ns?As.has(ns)||Ya.has(ns):!0})})(),ss=_V(aa,re.filters,qn,Sy?{semanticRemarkIds:Sy}:void 0);Qe=[...Ft,...ss],Qe.length!==Ht&&console.log("[PropertyLab] After attribute filters:",Qe.length,"of",Ht);const es=(ga=>{const As=T?.priorities&&T.priorities.length>0?{...T,baselineSource:T.baselineSource||"mls"}:{priorities:[],baselineWeights:{proximity:30,gla:25,els:25,bedsBaths:20}};console.log("[PropertyLab] Match scoring - compIntentState:",T?.priorities,"using:",As.priorities);const Ya=mO({verifiedSubject:as,propertyData:t,subjectCoordinates:s,subjectElsScore:_n,mlsData:di,publicRecordData:us}).subject;return console.log("[PropertyLab] Subject for scoring:",{gla:Ya.gla,beds:Ya.beds,baths:Ya.baths,lat:Ya.latitude}),ga.map(Aa=>{const ns=sJ(Aa,qn),{score:Sr,breakdown:Or}=g$(Ya,ns,As,we,qn);return{...Aa,matchScore:Sr,matchBreakdown:Or}})})(Qe),Js=ga=>{const As=typeof ga.sqft=="number"&&ga.sqft>0,Ya=typeof ga.sqftPR=="number"&&ga.sqftPR>0,Aa=typeof ga.btNormalizedGla=="number"&&ga.btNormalizedGla>0;return qn==="ai"?Aa?ga.btNormalizedGla:As?ga.sqft:Ya?ga.sqftPR:0:qn==="public-record"?Ya?ga.sqftPR:0:As?ga.sqft:0},er=[...es];if(Bi){const{column:ga,direction:As}=Bi,Ya=As==="desc"?-1:1;return er.sort((Aa,ns)=>{let Sr,Or;switch(ga){case"price":Sr=Aa.price,Or=ns.price;break;case"sqft":Sr=Js(Aa),Or=Js(ns);break;case"beds":Sr=Aa.beds??0,Or=ns.beds??0;break;case"baths":Sr=Aa.baths??0,Or=ns.baths??0;break;case"distance":Sr=Aa.distance??999,Or=ns.distance??999;break;case"dom":Sr=Aa.dom??0,Or=ns.dom??0;break;case"listDate":Sr=Aa.listDate?new Date(Aa.listDate).getTime():0,Or=ns.listDate?new Date(ns.listDate).getTime():0;break;case"closeDate":Sr=Aa.saleDate?new Date(Aa.saleDate).getTime():0,Or=ns.saleDate?new Date(ns.saleDate).getTime():0;break;case"yearBuilt":Sr=Aa.yearBuilt??0,Or=ns.yearBuilt??0;break;case"condition":Sr=Aa.conditionRating?parseInt(Aa.conditionRating.replace(/\D/g,""))||0:99,Or=ns.conditionRating?parseInt(ns.conditionRating.replace(/\D/g,""))||0:99;break;case"quality":Sr=Aa.qualityRating?parseInt(Aa.qualityRating.replace(/\D/g,""))||0:99,Or=ns.qualityRating?parseInt(ns.qualityRating.replace(/\D/g,""))||0:99;break;case"locationScore":Sr=Aa.echoLocationScore?.score??0,Or=ns.echoLocationScore?.score??0;break;case"matchScore":Sr=Aa.matchScore??0,Or=ns.matchScore??0;break;case"avmScore":Sr=Aa.avmScore??0,Or=ns.avmScore??0;break;case"utility":{const Li={green:0,yellow:1,red:2};Sr=Aa.glaBandTier?Li[Aa.glaBandTier]??3:3,Or=ns.glaBandTier?Li[ns.glaBandTier]??3:3;break}case"basement":case"style":{const Li=ga==="basement"?Aa.basement:Aa.style,Ti=ga==="basement"?ns.basement:ns.style,Ic=(typeof Li=="string"?Li:"").trim(),oc=(typeof Ti=="string"?Ti:"").trim();return!Ic&&!oc?0:Ic?oc?Ic.localeCompare(oc,void 0,{sensitivity:"base"})*Ya:-1:1}case"nightlyRate":{const Li=typeof Aa.strAverageDailyRate=="number"&&Aa.strAverageDailyRate>0?Aa.strAverageDailyRate:null,Ti=typeof ns.strAverageDailyRate=="number"&&ns.strAverageDailyRate>0?ns.strAverageDailyRate:null;return Li===null&&Ti===null?0:Li===null?1:Ti===null?-1:(Li-Ti)*Ya}case"occupancy":{const Li=oc=>typeof oc!="number"||!(oc>0)?null:oc<=1?oc*100:oc,Ti=Li(Aa.strOccupancyRate),Ic=Li(ns.strOccupancyRate);return Ti===null&&Ic===null?0:Ti===null?1:Ic===null?-1:(Ti-Ic)*Ya}case"rating":Sr=Aa.strRating??0,Or=ns.strRating??0;break;case"revenue":Sr=Aa.strGrossRevenue12mo??0,Or=ns.strGrossRevenue12mo??0;break;default:return 0}return(Sr-Or)*Ya})}switch(re.filters.sortBy){case"price-asc":return er.sort((ga,As)=>(ga.price??0)-(As.price??0));case"price-desc":return er.sort((ga,As)=>(As.price??0)-(ga.price??0));case"sqft-asc":return er.sort((ga,As)=>{const Ya=Js(ga),Aa=Js(As);return!Ya&&!Aa?0:Ya?Aa?Ya-Aa:-1:1});case"sqft-desc":return er.sort((ga,As)=>{const Ya=Js(ga),Aa=Js(As);return!Ya&&!Aa?0:Ya?Aa?Aa-Ya:-1:1});case"beds-desc":return er.sort((ga,As)=>(As.beds||0)-(ga.beds||0));case"distance":return er;case"match":return er.sort((ga,As)=>(As.matchScore||0)-(ga.matchScore||0));case"avm":return er.sort((ga,As)=>(As.avmScore||0)-(ga.avmScore||0));case"location":return er.sort((ga,As)=>(As.echoLocationScore?.score||0)-(ga.echoLocationScore?.score||0));default:return er.sort((ga,As)=>(ga.dom??0)-(As.dom??0))}},[jc,re.filters,re.searchPerformed,qt,Ma,ch,Cf,T,t,s,di,us,qn,Bi,Da,pi,Tr,
53Nn,Fr,mr,Fn,Yu,Zs,bp,ru,Bo,co,as,ro,U,Sy,Er]),hF=o.useMemo(()=>{const g=[...jc];if(Tr&&Nn.length>0)for(const I of Nn){const k=I.snapshotId||I.id;g.some(L=>(L.snapshotId||L.id)===k)||g.push(I)}if(Fr&&mr.length>0)for(const I of mr){const k=I.snapshotId||I.id;g.some(L=>(L.snapshotId||L.id)===k)||g.push(I)}return g.map(I=>I.snapshotId||I.id).filter(Boolean).sort().join(",")},[jc,Tr,Fr,Nn,mr]);o.useEffect(()=>{const g=[...jc];if(Tr&&Nn.length>0)for(const Y of Nn){const K=Y.snapshotId||Y.id;g.some(q=>(q.snapshotId||q.id)===K)||g.push(Y);const te=Pc(Y);te&&K!==te?Ui([K,te,Y.id]):Y.snapshotId&&Y.id&&Y.snapshotId!==Y.id&&Ui([Y.snapshotId,Y.id])}if(Fr&&mr.length>0)for(const Y of mr){const K=Y.snapshotId||Y.id;g.some(q=>(q.snapshotId||q.id)===K)||g.push(Y);const te=Pc(Y);te&&K!==te?Ui([K,te,Y.id]):Y.snapshotId&&Y.id&&Y.snapshotId!==Y.id&&Ui([Y.snapshotId,Y.id])}const I=g.map(Y=>Y.snapshotId||Y.id).filter(Y=>Y&&!CC.current.has(Y));if(I.length===0){Dt(!0);return}Dt(!1);const L=setTimeout(async()=>{const K=[];for(let ee=0;ee<I.length;ee+=500)K.push(I.slice(ee,ee+500));const te=new Map,q=new Map,ie=async ee=>{try{const we=await fetch("/api/sales/scores/batch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:ee})});if(!we.ok)return;const ve=await we.json();if(!ve.success||!ve.scores)return;ee.forEach(Qe=>CC.current.add(Qe));const Se=ve.scores;for(const[Qe,Nt]of Object.entries(Se))if(Nt.echoLocationScore&&(te.set(Qe,Nt.echoLocationScore),sn.current.add(Qe)),Nt.conditionRating||Nt.qualityRating){q.set(Qe,{condition:Nt.conditionRating,quality:Nt.qualityRating,confidence:.8});const Ct=g.find(Ht=>(Ht.snapshotId||Ht.id)===Qe),va=Pc(Ct||{});va&&rn.current.add(va)}}catch(we){console.warn("[PropertyLab] Batch scores chunk failed:",we)}};await Promise.all(K.map(ie)),te.size>0&&Ki(ee=>{const we=new Map(ee);return te.forEach((ve,Se)=>we.set(Se,ve)),we}),q.size>0&&kl(ee=>{const we=new Map(ee);let ve=!1;return q.forEach((Se,Qe)=>{const Nt=ee.get(Qe);(!Nt?.condition||!Nt?.quality)&&(we.set(Qe,Se),ve=!0)}),ve?we:ee}),(te.size>0||q.size>0)&&(console.log("[PropertyLab] Batch scores loaded - ELS:",te.size,"AI:",q.size),(Tr||Fr)&&pm(ee=>ee+1)),Dt(!0)},200);return()=>clearTimeout(L)},[hF]);const{pollingComplete:LC}=OG({properties:Xr,enabled:Xr.length>0,batchScoresLoaded:Wn,isStreaming:re.isLoading,compAiCacheRef:Dr,onRatingReceived:Dd}),{analysisComplete:fF}=EG({properties:Xr,enabled:Xr.length>0&&LC,batchScoresLoaded:Wn,alreadyFetchedMlsNumbers:rn.current,compAiCacheRef:Dr,prioritizedIds:ro,onAnalysisComplete:Dd}),[$N,vy]=o.useState(!1),Ep=o.useMemo(()=>{const g=[];s&&g.push({id:"subject",lat:s.lat,lng:s.lng,label:a||"Subject Property",type:"subject"});const I=Xr.filter(ve=>cI(ve.coordinates?.lat,ve.coordinates?.lng)).map(ve=>{const Se=!!ve.isStrProperty,Qe={id:ve.snapshotId||ve.id,lat:ve.coordinates.lat,lng:ve.coordinates.lng,label:ve.address,data:ve,mlsNumber:ve.mlsNumber??null,snapshotId:ve.snapshotId??null};return Se?{...Qe,type:"str",strData:{nightlyRate:ve.strAverageDailyRate,occupancyRate:ve.strOccupancyRate,annualRevenue:ve.strGrossRevenue12mo,bedrooms:ve.beds??void 0,bathrooms:ve.baths??void 0,gla:ve.sqft??void 0,platform:ve.strProvider,rentalType:void 0,photoUrl:ve.photoUrl??void 0,photos:ve.photos,rating:ve.strRating,reviewCount:ve.strReviewCount,listingName:ve.strListingName}}:{...Qe,type:"comp"}}),k=new Set;for(const ve of Xr)for(const Se of fj(ve))k.add(Se);let L=[];const Y=xo||js.length>0;U&&Da==="all"&&Kr.length>0&&Y&&(L=SZ({allCachedSales:Kr,visibleAliasSet:k,getAliases:fj,drawnIds:qt?new Set(qt):null,hasGeometry:Y,radiusMiles:re.marketDefinition?.radiusMiles,subject:s??null}));const K=xo||js.length>0,q=(!U||Da==="rentals"||Da==="all")&&(!U||K)?(ya||[]).filter(ve=>cI(ve.lat,ve.lng)).map(ve=>({id:ve.id,lat:ve.lat,lng:ve.lng,label:ve.address||"STR Rental",type:"str",strData:{nightlyRate:ve.nightlyRate,occupancyRate:ve.occupancyRate,annualRevenue:ve.annualRevenue,bedrooms:ve.bedrooms,bathrooms:ve.bathrooms,gla:ve.gla,platform:ve.platform,rentalType:ve.rentalType,photoUrl:ve.photoUrl,photos:ve.photos,rating:ve.rating,reviewCount:ve.reviewCount,listingName:ve.listingName}})):[],ie=new Set,ee=ve=>{const Se=fj({mlsNumber:ve.mlsNumber,snapshotId:ve.snapshotId,id:ve.id});return Se.length>0?Se:[`coord:${ve.lat?.toFixed(5)},${ve.lng?.toFixed(5)}:${ve.label}`]};return $N?g:[...g,...I,...L,...q].filter(ve=>{if(ve.type==="subject")return!0;const Se=ee(ve);if(Se.some(Qe=>ie.has(Qe)))return!1;for(const Qe of Se)ie.add(Qe);return!0})},[Xr,s,a,ya,U,Da,Kr,re.marketDefinition?.radiusMiles,xo,js.length,qt,re.filters.statusSelection,re.filters.status,$N]),Ny=o.useMemo(()=>Kr.filter(g=>g.coordinates!=null&&g.coordinates.lat!=null&&g.coordinates.lng!=null).map(g=>({id:g.snapshotId||g.id,lat:g.coordinates.lat,lng:g.coordinates.lng,label:g.address||"Unknown",type:"comp",propertyType:g.propertyType??null,mlsStatus:g.status??null,salePrice:g.price??null,bedrooms:g.beds??null,bathrooms:g.baths??null,sqft:g.gla??null,yearBuilt:g.yearBuilt??null,saleDate:g.saleDate??null})),[Kr]),gF=o.useMemo(()=>UV(re.filters.propertyTypes),[re.filters.propertyTypes]),xF=o.useMemo(()=>{const g=(re.filters.propertyTypes||[]).filter(I=>I!=="STR");return{status:re.filters.statusSelection?.length?re.filters.statusSelection:re.filters.status,propertyType:g.length===1?g[0]:void 0,propertyTypes:g.length>
530?g:void 0,minPrice:re.filters.minPrice,maxPrice:re.filters.maxPrice,minBeds:re.filters.minBeds,maxBeds:re.filters.maxBeds,minBaths:re.filters.minBaths,maxBaths:re.filters.maxBaths,minSqft:re.filters.minSqft,maxSqft:re.filters.maxSqft,minYearBuilt:re.filters.minYearBuilt,maxYearBuilt:re.filters.maxYearBuilt,includeZeroGla:re.filters.includeZeroGla!==!1,monthsBack:re.filters.monthsBack??12}},[re.filters.statusSelection,re.filters.status,re.filters.propertyTypes,re.filters.minPrice,re.filters.maxPrice,re.filters.minBeds,re.filters.maxBeds,re.filters.minBaths,re.filters.maxBaths,re.filters.minSqft,re.filters.maxSqft,re.filters.minYearBuilt,re.filters.maxYearBuilt,re.filters.includeZeroGla,re.filters.monthsBack]),vm=o.useMemo(()=>{const g=new Set(Xr.map(k=>k.snapshotId||k.id)),I=new Map;return re.properties.forEach(k=>{const L=k.snapshotId||k.id;g.has(L)&&I.set(L,k)}),Kr.forEach(k=>{const L=k.snapshotId||k.id;g.has(L)&&!I.has(L)&&I.set(L,k)}),re.selectedComps.forEach(k=>{const L=k.snapshotId||k.id;g.has(L)&&!I.has(L)&&I.set(L,k)}),Array.from(I.values())},[Xr,re.properties,Kr,re.selectedComps]),[Ay,bF]=o.useState(vm);o.useEffect(()=>{const g=setTimeout(()=>{bF(vm)},250);return()=>clearTimeout(g)},[vm]);const DC=o.useMemo(()=>nK(Ay),[Ay]),Ab=o.useMemo(()=>({...DC,...Dg}),[DC,Dg]),yF=o.useCallback(g=>{yf(I=>({...I,...g}))},[]),SF=o.useMemo(()=>u1(Ay),[Ay]),BN=o.useMemo(()=>a&&jm(a)?.city||"",[a]),kC=o.useMemo(()=>!qt||qt.length===0?vm:vm.filter(g=>qt.includes(g.snapshotId||g.id)),[vm,qt]);o.useMemo(()=>Tr?SQ(vm,kC,new Date,12):{marketData:[],subMarketData:[],marketAvgRate:0,subMarketAvgRate:0},[Tr,vm,kC]),o.useCallback(async(g,I)=>{lu(g),Jm(I);const k=Y1(re.selectedComps,I,new Date);if(qe(L=>({...L,selectedComps:k.map((Y,K)=>{const te=L.selectedComps[K];return te?{...Y,...te.gridFieldOverrides?{gridFieldOverrides:te.gridFieldOverrides}:{},...te.strComparability!==void 0?{strComparability:te.strComparability}:{}}:Y})})),r)try{await dn("/api/market-session/time-adjustment",{assignmentId:r,source:g,ratePercent:I})}catch(L){L instanceof qo&&L.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to persist time adjustment:",L)}Ve({title:"Time Adjustment Locked",description:`${I>=0?"+":""}${I.toFixed(2)}%/mo from ${g==="market"?"Market":"Sub-Market"} applied to selected sales`})},[re.selectedComps,r,Ve]);const zN=o.useRef(null);o.useEffect(()=>{zN.current=null,Jm(null),lu(null)},[r]);const MC=re.selectedComps.length;o.useEffect(()=>{if(!r||ec===null||MC===0||zN.current===r)return;const g=mu.current;if(g.length===0)return;const I=Y1(g,ec,new Date);qe(k=>({...k,selectedComps:I.map((L,Y)=>{const K=k.selectedComps[Y];return K?{...L,...K.gridFieldOverrides?{gridFieldOverrides:K.gridFieldOverrides}:{},...K.strComparability!==void 0?{strComparability:K.strComparability}:{}}:L})})),zN.current=r},[r,ec,MC]);const FC=o.useRef(null),_C=o.useRef(P1());o.useEffect(()=>{_C.current=P1()},[r]);const qN=o.useRef(!1),jy=o.useRef(null),YN=o.useRef(null),UC=o.useCallback((g,I)=>{jy.current=I,ps(!0),cu(k=>O1(k,g)),nt(k=>k+1)}
53,[]),Ty=o.useCallback((g,I,k)=>{const L=g;D9({shapes:L,subjectCoordinates:s,allCachedSales:Kr,state:re,assignmentId:r,propmixCoverageRef:_C,setHasDrawnShapes:Yi,setGeometrySearchInFlight:ts,setGeometrySearchEmpty:Va,setGeometrySearchMeta:xs,setAppliedBoundaries:bo,commitAtomicResult:UC,clearAtomicCommitPending:()=>ps(!1),lastGeometrySearchRef:Sn,mlsFailureToastRef:Zt,geometrySearchAbortRef:ds,toast:Ve,dismissMlsFailureToast:Rs,propertyTypeFilter:Da,rerun:()=>FC.current?.(L,[],null)})},[s,Kr,re.filters.statusSelection,re.filters.status,re.filters.propertyType,re.filters.minPrice,re.filters.maxPrice,re.filters.minBeds,re.filters.maxBeds,re.filters.minBaths,re.filters.maxBaths,re.filters.minSqft,re.filters.maxSqft,re.filters.minYearBuilt,re.filters.maxYearBuilt,re.filters.includeZeroGla,re.filters.monthsBack,re.properties.length,r,Ve,Rs,Da,UC]);FC.current=Ty;const vF=o.useCallback(async(g,I)=>k9({shapes:g,signal:I,subjectCoordinates:s,state:re,assignmentId:r}),[s,re.filters.statusSelection,re.filters.status,re.filters.propertyType,re.filters.minPrice,re.filters.maxPrice,re.filters.minBeds,re.filters.maxBeds,re.filters.minBaths,re.filters.maxBaths,re.filters.minSqft,re.filters.maxSqft,re.filters.minYearBuilt,re.filters.maxYearBuilt,re.filters.includeZeroGla,re.filters.monthsBack,r]),VC=o.useMemo(()=>{if(Ma.circles.length===0)return null;const g=Ma.circles[0];return{radiusMiles:Math.round(g.radiusMeters/1609.34*10)/10}},[Ma.circles]),NF=o.useCallback(g=>{if(!s)return;Zs&&(Fi.current=null,al(null));const I=g*1609.34;Xn(k=>({...k,circles:[{id:`radius-${Date.now()}`,center:{lat:s.lat,lng:s.lng},radiusMeters:I}]})),Yi(!0),so(!0),qe(k=>({...k,marketDefinition:{...k.marketDefinition,radiusMiles:g,center:s,totalProperties:k.marketDefinition?.totalProperties||0}}))},[s]),AF=o.useCallback(g=>{const I={"school-district":"#3b82f6","census-tract":"#6366f1","flood-zone":"#ef4444"},k={"school-district":"school_district","census-tract":"custom","flood-zone":"custom"},L={id:g.id||`layer-${g.type}-${Date.now()}`,name:g.name,type:k[g.type]||"custom",color:I[g.type]||"#3b82f6",polygon:g.polygon,code:g.code,state:g.state,county:g.county,source:g.source,version:g.version,sourceId:g.sourceId};js.some(K=>g.id&&K.id===g.id||K.name===L.name)?Ve({title:"Already Added",description:`${g.name} is already a boundary`,variant:"default"}):(bo(K=>[...K,L]),Ve({title:"Boundary Added",description:`${g.name} added as market boundary`}))},[js,Ve]),jF=o.useCallback((g,I,k,L)=>{Ki(Y=>{const K=new Map(Y);return K.set(g,{score:I,tier:k,factors:L,isOverridden:!0}),K}),wd()},[wd]),TF=o.useCallback(()=>{xa(!0)},[]),[GN,Iy]=o.useState(null),[$C,HN]=o.useState(!1),[Cy,IF]=o.useState(null),Ry=o.useRef(!1),WN=o.useRef(Kr.length);WN.current=Kr.length;const Ey=o.useRef(Ma.polygons.length+Ma.circles.length);Ey.current=Ma.polygons.length+Ma.circles.length;const BC=o.useRef(Ma);BC.current=Ma;const zC=o.useRef(s);zC.current=s;const KN=o.useRef(r);KN.current=r;const wy=o.useRef(js);wy.current=js;const qC=o.useRef(null),CF=o.useCallback(g=>{const I=wy.current,k=I.length>0&&I.every(Y=>!!Y.id&&Y.id.startsWith("drawn-area-")),L=VV(g,{allCachedSalesCount:WN.current,externalShapeCount:Ey.current,hadSavedBoundary:ci.current,hasSentinelOnlyAppliedBoundaries:k});if(L.warning){const Y=g.requested===0,K=Y?"hydration-loss":"render-failure",te=[KN.current??"(no-order)",K,g.requested,g.rendered,g.styleReady?"1":"0",g.skippedReasons.join("|")].join("::");if(qC.current!==te){qC.current=te;const ie=$V(wy.current);console.warn("[PropertyLab] boundary watchdog tripped",{branch:K,orderId:KN.current??null,requested:g.requested,rendered:g.rendered,skipped:g.skipped,styleReady:g.styleReady,skippedReasons:g.skippedReasons,allCachedSalesCount:WN.current,externalShapeCount:Ey.current,hadSavedBoundary:ci.current,appliedBoundaryCount:wy.current.length,geometry:BV(ie),geometrySummaries:ie})}const q=zC.current;if(Y&&!Ry.current&&Ey.current===0&&q&&!jo.current&&ci.current){Ry.current=!0;const ie=1609.34;console.warn("[PropertyLab] Watchdog auto-recovery: re-seeding 1-mile auto-radius around subject");const ee={polygons:[],circles:[{id:`auto-radius-${Date.now()}`,center:{lat:q.lat,lng:q.lng},radiusMeters:ie}]};Xn(ee),JN.current=ee,Yi(!0),so(!0),setTimeout(()=>{!Qn.current&&Nr.current?Nr.current():En.current=!0},50)}}Iy(L.warning),HN(L.fallbackActive),IF({requested:g.requested,rendered:g.rendered,skipped:g.skipped,styleReady:g.styleReady})},[]),QN=o.useMemo(()=>{const g=Tr||Fr,I=Vi(new Date,"yyyy-MM-dd"),k=re.filters.monthsBack||12;let L="radius",Y={};if(Ma.circles.length>0){const K=Ma.circles[0];L="radius",Y={centerLat:K.center.lat,centerLng:K.center.lng,radiusMiles:Math.round(K.radiusMeters/1609.34*10)/10}}else if(Ma.polygons.length>0){const K=Ma.polygons[0];L="polygon",Y={coordinates:K.path.map(te=>[te.lat,te.lng])}}else s&&(L="radius",Y={centerLat:s.lat,centerLng:s.lng,radiusMiles:1});return{effectiveDate:I,windowMonths:k,scopeType:Fr?"submarket":"market",geometryType:L,geometryData:Y,filters:{propertyType:re.filters.propertyType,priceMin:re.filters.minPrice,priceMax:re.filters.maxPrice,bedsMin:re.filters.minBeds,bedsMax:re.filters.maxBeds,bathsMin:re.filters.minBaths,bathsMax:re.filters.maxBaths,glaMin:re.filters.minSqft,glaMax:re.filters.maxSqft},isLocked:g,lockedAt:g?new Date().toISOString():void 0,source:"embedded",assignmentId:r}},[Tr,Fr,Ma,re.filters,s,r]),RF=o.useMemo(()=>r?e.jsx(bQ,{assignmentId:r,marketContext:QN,marketLocked:Tr,subMarketLocked:Fr,lockedMarketCount:Gc,lockedSubMarketCount:Mi,lockedMarketResultIds:to,lockedSubmarketResultIds:Gi,lockedMarketSalesData:fl,lockedSubmarketSalesData:Ad,subjectState:i,subjectZipCode:l,selectedComps:re.selectedComps}
53):null,[r,QN,Tr,Fr,Gc,Mi,to,Gi,fl,Ad,i,l,re.selectedComps]),EF=o.useMemo(()=>{const g={};for(const I of re.selectedComps){const k=I.adjustments;if(!k)continue;const L={};for(const[K,te]of Object.entries(k))typeof te=="number"&&(L[K]=te);const Y=I.snapshotId??I.id;g[Y]=L}return g},[re.selectedComps]),dh=rZ({assignmentId:r,verifiedSubject:as,lockedSubmarketPropertyCards:mr,lockedMarketPropertyCards:Nn,marketLocked:Tr,subMarketLocked:Fr,locksHydrating:!ls,enabled:ih,subjectElsScore:_n,currentAdjustments:EF,onApplyAdjustments:tm,onComplianceComputed:Yg,embeddedTimeVault:RF}),Py=iZ();o.useEffect(()=>{Py(dh.drawerProps)},[Py,dh.drawerProps]),o.useEffect(()=>()=>Py(null),[Py]);const ZN=o.useRef(Bu?ma:!1),JN=o.useRef(st?.currentShapes??{polygons:[],circles:[]}),Qn=o.useRef(!1),En=o.useRef(!1),[wF,XN]=o.useState(!1),Tc=o.useRef(null),Su=o.useRef(null),Rf=o.useRef("idle"),Ef=o.useRef(null),wf=o.useRef(null),Zu=o.useRef(null),YC=o.useRef(0),td=o.useRef(!0),[PF,uh]=o.useState(null),eA=o.useRef(null);o.useEffect(()=>()=>{td.current=!1,Su.current&&clearTimeout(Su.current),Tc.current&&Tc.current.abort(),Ju.current&&Ju.current.abort(),yo.current&&clearTimeout(yo.current),Ef.current&&(clearTimeout(Ef.current),Ef.current=null),wf.current&&(clearTimeout(wf.current),wf.current=null),Zu.current&&(clearTimeout(Zu.current),Zu.current=null)},[]);const Nr=o.useRef(null),tA=o.useRef("effect-driven"),ph=o.useCallback(g=>{if(console.log(`[PropertyLab][clear-radius] ${g} — marking as user-cleared for the session`),jo.current=!0,Ry.current=!0,ci.current=!1,zu(!0),Tc.current){try{Tc.current.abort()}catch{}Tc.current=null}if(Ju.current){try{Ju.current.abort()}catch{}Ju.current=null,jb.current=!1,vy(!1)}yo.current&&(clearTimeout(yo.current),yo.current=null),Zu.current&&(clearTimeout(Zu.current),Zu.current=null),Qn.current=!1,qs(!1),Wc(null),uh(null),qe(I=>I.isLoading||I.properties.length>0?{...I,isLoading:!1,properties:[],error:null}:I),setTimeout(()=>{!Qn.current&&Nr.current?Nr.current():Nr.current&&(console.log(`[PropertyLab][clear-radius] Search in flight, queuing user-cleared search (${g})`),En.current=!0)},100)},[]),OF=o.useCallback(()=>{console.log("[PropertyLab] handleClearRadius called, preserving",Ma.polygons.length,"polygons");const g=Ma.polygons.length>0,I={polygons:Ma.polygons,circles:[]};Xn(I),Yi(g),g||la(null),g||ph("Radius chip removed by user")},[Ma.polygons,ph]),LF=o.useCallback(()=>{console.log("[PropertyLab] handleClearPolygon called, preserving",Ma.circles.length,"circles");const g=Ma.circles.length>0,I={polygons:[],circles:Ma.circles};Xn(I),Yi(g),g||la(null),g||ph("Polygon chip removed by user")},[Ma.circles,ph]),GC=o.useRef(re.properties);GC.current=re.properties;const HC=o.useRef(re.filters);HC.current=re.filters;const aA=o.useRef(new Set(["CLSD"])),mh=o.useRef(12),jb=o.useRef(!1),Ju=o.useRef(null),Oy=o.useRef(new Map),sA=o.useRef(new Set),[DF,rA]=o.useState({});o.useEffect(()=>{rA(g=>{if(Os)return g.status?g:{...g,status:!0};if(!g.status)return g;const{status:I,...k}=g;return k})},[Os]);const[kF,WC]=o.useState(!1),Ly=o.useRef(0),KC=o.useRef(!1),nA=o.useRef(!1),QC=o.useRef(!1);if(!QC.current){const g=re.marketDefinition?.radiusMiles??0;g>0&&re.properties.length>0&&(Ly.current=g,QC.current=!0)}const Dy=o.useCallback(g=>{rA(I=>({...I,[g]:!0}))},[]);o.useEffect(()=>{const g=new Set;for(const I of re.properties)I.status&&g.add(I.status);for(const I of Kr)I.status&&g.add(I.status);g.size>0&&(aA.current=g)},[re.properties,Kr]),o.useEffect(()=>{const g=KC.current;if(KC.current=re.isLoading,re.isLoading||!g)return;rA(K=>Object.keys(K).length===0?K:{});const I=re.marketDefinition?.radiusMiles??0,k=nA.current,L=En.current||Qn.current;!re.error&&(!k||!L)&&I>Ly.current&&(Ly.current=I),!(!k||L)&&(nA.current=!1,WC(K=>K&&!1))},[re.isLoading,re.marketDefinition?.radiusMiles]);const iA=o.useRef(async()=>{});iA.current=async()=>{if(!(!r||!re.searchPerformed))try{const g={filters:re.filters,marketDefinition:re.marketDefinition,searchPerformed:re.searchPerformed,mapCenter:Ks,mapZoom:Bn,viewMode:rs,comparisonDataSource:qn,savedAt:new Date().toISOString()};await Lh(r,{saveProgress:{stepKey:"property_lab_search_state",stepData:g}})}catch{}},o.useEffect(()=>{Ee.current=!1,Ry.current=!1,jo.current=!1,ci.current=js.length>0||Ma.circles.length>0||Ma.polygons.length>0},[r]),o.useEffect(()=>{if(!Cf||!En.current)return;if(ei.current){En.current=!1;return}if(Qn.current||!Nr.current)return;console.log("[PropertyLab] Geometry now available — firing deferred search"),En.current=!1;const g=setTimeout(()=>{ei.current||(!Qn.current&&Nr.current?Nr.current():En.current=!0)},50);return()=>clearTimeout(g)},[Cf]),o.useEffect(()=>{if(!r||Ee.current)return;if(ei.current){Ee.current=!0;return}Ee.current=!0;let g=!1;return(async()=>{try{let k=null;for(let te=0;te<=Uj.length;te++)try{k=await Ho(`/api/v2/orders/${r}/progress`,{throwOnSuccessFalse:!1});break}catch(q){if(q instanceof qo&&(q.status===401||q.status===403||q.status===404)||te>=Uj.length)throw q;if(await new Promise(ie=>setTimeout(ie,Uj[te])),g||ei.current)return}if(g)return;const L=k?.progress;if(!Array.isArray(L))return;const Y=L.find(te=>te.stepKey==="property_lab_search_state");if(!Y?.stepData)return;const K=Y.stepData;if(console.log("[PropertyLab] Restoring saved search state from",K.savedAt),ei.current)return;if(K.filters&&qe(te=>({...te,filters:{...te.filters,...K.filters}})),K.marketDefinition&&qe(te=>({...te,marketDefinition:K.marketDefinition})),K.mapCenter&&Tn(K.mapCenter),K.mapZoom&&Ka(K.mapZoom),K.viewMode&&Gs(K.viewMode),K.comparisonDataSource&&gd(K.comparisonDataSource),K.elsCache&&Array.isArray(K.elsCache)){const te=new Map(K.elsCache);Ki(q=>{const ie=new Map(q);return te.forEach((ee,we)=>{ie.has(we)||ie.set(we,ee)}),ie}),K.elsCache.forEach(([q])=>sn.current.add(q)),console.log("[PropertyLab] Rehydrated ELS cache from saved state:",K.elsCache.length,"entries")}if(K.compAiCache&&Array.isArray(K.compAiCache)){const te=new Map(K.compAiCache);kl(q=>{const ie=new Map(q);return te.forEach((ee,we)=>{ie.has(we)||ie.set(we,ee)}),ie}
53),K.compAiCache.forEach(([q])=>rn.current.add(q)),console.log("[PropertyLab] Rehydrated AI cache from saved state:",K.compAiCache.length,"entries")}K.searchPerformed&&setTimeout(()=>{ei.current||(Nr.current&&!Qn.current?(console.log("[PropertyLab] Auto-triggering search from restored state"),Nr.current()):En.current=!0)},500)}catch(k){console.warn("[PropertyLab] Could not restore saved state:",k)}})(),()=>{g=!0}},[r]);const MF=JSON.stringify(re.filters),FF=JSON.stringify(re.marketDefinition);o.useEffect(()=>{if(!(!r||!re.searchPerformed))return dt.current&&clearTimeout(dt.current),dt.current=setTimeout(()=>{iA.current?.()},1500),()=>{dt.current&&clearTimeout(dt.current)}},[MF,FF,re.searchPerformed,Ks?.lat,Ks?.lng,Bn,rs,qn,r]);const ZC=o.useRef(os);ZC.current=os;const ky=o.useCallback(()=>{setTimeout(()=>{dt.current&&(clearTimeout(dt.current),dt.current=setTimeout(()=>{iA.current?.()},300)),ZC.current?.()},0)},[]),_F=o.useCallback(g=>{(g.targets.includes("comps")||g.targets.includes("market"))&&g.comps.length>0&&(cu(k=>O1(k,g.comps)),YN.current=BC.current,nt(k=>k+1),ky()),g.targets.includes("subject")&&Le&&Le(g.subjectValues),Fg(g.fingerprint,g.confirmedMapping),bc(!1)},[ky,Fg,Le]),JC=o.useRef(!1),UF=o.useMemo(()=>re.selectedComps.map(g=>g.snapshotId||g.id).join("|"),[re.selectedComps]),VF=o.useMemo(()=>{const g=Ma.circles.map(k=>`${k.center.lat.toFixed(5)},${k.center.lng.toFixed(5)}@${Math.round(k.radiusMeters)}`).join(";"),I=Ma.polygons.map(k=>`${k.path.length}`).join(";");return`c=${g}|p=${I}|b=${js.length}`},[Ma.circles,Ma.polygons,js.length]);o.useEffect(()=>{if(!(!r||!re.searchPerformed)){if(!JC.current){JC.current=!0;return}re.isLoading||ky()}},[r,re.searchPerformed,re.isLoading,UF,rs,qn,VF,ky]),o.useEffect(()=>{Qn.current=re.isLoading,!re.isLoading&&En.current&&!ei.current?(En.current=!1,console.log("[PropertyLab] Search completed, triggering pending re-search"),setTimeout(()=>{if(ei.current){console.log("[PropertyLab] Locked data restored - skipping pending search");return}!Qn.current&&Nr.current?Nr.current():Nr.current?(console.log("[PropertyLab] Another search started, re-queuing"),En.current=!0):(console.log("[PropertyLab] handleSearchRef still not ready, keeping pending"),En.current=!0)},200)):!re.isLoading&&En.current&&ei.current&&(console.log("[PropertyLab] Locked data restored - clearing pending search"),En.current=!1)},[re.isLoading]);const oA=o.useRef(!1);o.useEffect(()=>{if(!ei.current||oA.current||re.isLoading||!(re.filters.statusSelection?.some(L=>Hf.has(L))??!1))return;re.properties.some(L=>{const Y=L.status;return Hf.has(Y)})||(oA.current=!0,console.log("[PropertyLab] Locked data restored with active status filter but no active listings — triggering PropMix search"),setTimeout(()=>{Nr.current&&Nr.current()},300))},[re.filters.statusSelection,re.isLoading,re.properties]),o.useEffect(()=>{(re.filters.statusSelection?.some(I=>Hf.has(I))??!1)||(oA.current=!1)},[re.filters.statusSelection]),o.useEffect(()=>{if(Wt){qN.current=!1,jy.current=null,ps(!1);return}const g=jy.current;if(g!==null){jy.current=null,qN.current=!0;const Y=M9(Kr,g);console.log(`[PropertyLab] Atomic boundary commit (pending-commit branch): ${Y.length} in-boundary of ${Kr.length} in pool`),la(Y),ps(!1);return}const I=YN.current;if(I!==null){YN.current=null;const Y=F9(Kr,I);Y!==null&&(console.log(`[PropertyLab] CSV import recomputed drawnAreaPropertyIds: ${Y.length} of ${Kr.length} in pool`),la(Y));return}if(qN.current||!(Ma.polygons.length>0||Ma.circles.length>0)||Kr.length===0)return;const L=LI(Kr,Ma);console.log("[PropertyLab] Recalculated containedIds from cached sales (non-session path):",L.length,"of",Kr.length),la(L)},[Kr,Ma,Wt,yt]);const $F=o.useCallback(g=>{const I=JN.current,k=g.polygons.length>0||g.circles.length>0,L=I.polygons.length>0||I.circles.length>0,Y=(()=>{if(g.circles.length!==I.circles.length||g.polygons.length!==I.polygons.length)return!0;for(const K of g.circles){const te=I.circles.find(q=>q.id===K.id);if(!te||Math.abs(K.radiusMeters-te.radiusMeters)>10||Math.abs(K.center.lat-te.center.lat)>1e-4||Math.abs(K.center.lng-te.center.lng)>1e-4)return!0}
53for(const K of g.polygons){const te=I.polygons.find(q=>q.id===K.id);if(!te||K.path.length!==te.path.length)return!0;for(let q=0;q<K.path.length;q++)if(Math.abs(K.path[q].lat-te.path[q].lat)>1e-6||Math.abs(K.path[q].lng-te.path[q].lng)>1e-6)return!0}return!1})();if((Y||!L&&k)&&(Xn(g),JN.current=g),k&&!Ea){if(so(!0),g.circles.length>0){const K=Math.round(g.circles[0].radiusMeters/1609.34*10)/10;qe(te=>({...te,marketDefinition:{...te.marketDefinition,radiusMiles:K,center:g.circles[0].center,totalProperties:te.marketDefinition?.totalProperties||0}}))}if(!ZN.current){ZN.current=!0;const K=wi.current.length>0||ei.current,te=Rd.current.length>0,q=K||te,ie=Ug.current||tc.current||Vg.current;ie&&!q?console.log("[PropertyLab] Shapes initialized, LOCKED but no cards yet - loadLockedState will handle"):ie&&q?(console.log("[PropertyLab] Shapes initialized, LOCKED with market cards:",wi.current.length,"submarket cards:",Rd.current.length,"or lockedDataRestoredRef=true - skipping search"),ei.current=!0):(console.log("[PropertyLab] Shapes initialized, triggering initial search"),setTimeout(()=>{if(ei.current){console.log("[PropertyLab] Locked data restored during wait - skipping initial search");return}console.log("[PropertyLab] Attempting initial search, handleSearchRef:",!!Nr.current,"inFlight:",Qn.current),!Qn.current&&Nr.current?Nr.current():Nr.current?(console.log("[PropertyLab] Initial search deferred, queuing pending search"),En.current=!0):(console.log("[PropertyLab] handleSearchRef not ready, scheduling retry"),En.current=!0)},250))}}else if(Ea&&Y&&k)if(yc.current)console.log("[PropertyLab] Shapes modified but in review mode — skipping re-search"),En.current=!1;else{if(console.log("[PropertyLab] Shapes modified, triggering re-search"),g.circles.length>0){const K=Math.round(g.circles[0].radiusMeters/1609.34*10)/10;K>Ly.current&&(nA.current=!0,WC(!0)),qe(te=>({...te,marketDefinition:{...te.marketDefinition,radiusMiles:K,center:g.circles[0].center,totalProperties:te.marketDefinition?.totalProperties||0}}))}Qn.current?(console.log("[PropertyLab] Search in progress, queuing re-search"),En.current=!0):setTimeout(()=>{!Qn.current&&Nr.current?Nr.current():Nr.current&&(console.log("[PropertyLab] Skipping re-search, another search started"),En.current=!0)},300)}else L&&!k&&($u.current?(console.log("[PropertyLab] Shapes cleared by enterReviewMode — skipping re-search"),$u.current=!1):Date.now()-$m.current<2e3?console.log("[PropertyLab] Shapes cleared right after view toggle — ignoring (map remount artifact)"):(so(!1),ZN.current=!1,Yi(!1),la(null),ph("All shapes cleared")))},[Ea,ph]),XC=g=>{tA.current="sort-change",qe(I=>({...I,filters:{...I.filters,sortBy:g}}))},eR=o.useCallback(g=>{qe(I=>({...I,hoveredPropertyId:g}))},[]),Pf=o.useCallback(async g=>{const I=g.snapshotId||g.id;I&&cA.current?.panToProperty(I);const L=(()=>{const ee=iO(mu.current,g);if(ee?.mlsData)return ee;const we=iO(GC.current,g);return we?.mlsData?we:null})();if(L){if(T0(L,g)){zn(Vb(L,vf.current.has(g.snapshotId||g.id)));return}console.warn("[PropertyLab] findRichComp returned a non-matching record; falling back to clicked row data",{clicked:{snapshotId:g.snapshotId,id:g.id,mlsNumber:g.mlsNumber,address:g.address},rich:{snapshotId:L.snapshotId,id:L.id,mlsNumber:L.mlsNumber,address:L.address}})}if(g.mlsData||g.publicRecordData){zn(g);return}const Y=(ee,we,ve)=>{ve!=null&&(ee[we]=ve)},K={};Y(K,"bedrooms",g.beds),Y(K,"bathrooms",g.baths),Y(K,"bathroomsFull",g.fullBathrooms),Y(K,"bathroomsHalf",g.halfBathrooms),Y(K,"basementFullBaths",g.basementFullBaths),Y(K,"basementHalfBaths",g.basementHalfBaths),Y(K,"squareFeet",g.sqft),Y(K,"yearBuilt",g.yearBuilt),Y(K,"garageSpaces",g.garageSpaces),Y(K,"style",g.style),Y(K,"stories",g.stories),Y(K,"lotSize",g.lotSqft),Y(K,"daysOnMarket",g.dom),Y(K,"closePrice",g.price),Y(K,"listPrice",g.listPrice),Y(K,"closeDate",g.saleDate),Y(K,"listDate",g.listDate),Y(K,"propertyType",g.propertyType),Y(K,"standardStatus",g.status),Y(K,"pricePerSqft",g.pricePerSqft),Y(K,"mlsNumber",g.mlsNumber),Y(K,"distance",g.distance);const te={};Y(te,"squareFeet",g.sqftPR),Y(te,"yearBuilt",g.yearBuiltPR),Y(te,"lotSize",g.lotSqftPR);const q={...g,mlsData:Object.keys(K).length>0?K:void 0,publicRecordData:Object.keys(te).length>0?te:void 0};zn(q);const ie=g.snapshotId||g.id;try{const ee=await Ho(`/api/comps/${ie}`,{throwOnSuccessFalse:!1});if(ee.success&&ee.comp){const we=fd.current;if((we?.snapshotId||we?.id)!==ie)return;const Se=ee.comp,Qe={id:Se.id??null,snapshotId:Se.snapshotId??null,mlsNumber:Se.mlsNumber??Se.mlsData?.mlsNumber??null};if(!T0(Qe,g)){console.warn("[PropertyLab] /api/comps enrichment returned a non-matching record; dropping",{requestedSnapshotId:ie,clicked:{snapshotId:g.snapshotId,id:g.id,mlsNumber:g.mlsNumber,address:g.address},returned:{...Qe,address:Se.address}});return}const Nt={...g,mlsData:{...K,...Se.mlsData||{}},publicRecordData:{...te,...Se.publicRecordData||{}},baths:Se.mlsData?.bathrooms??g.baths,beds:Se.mlsData?.bedrooms??g.beds,sqft:Se.mlsData?.squareFeet??g.sqft,yearBuilt:Se.mlsData?.yearBuilt??g.yearBuilt,style:Se.mlsData?.style??g.style,garageSpaces:Se.mlsData?.garageSpaces??g.garageSpaces,contractDate:g.contractDate||Se.mlsData?.contractDate||Se.mlsData?.ContractDate||Se.mlsData?.PurchaseContractDate||null};zn(Nt)}}catch(ee){console.warn("[PropertyLab] Failed to fetch comp details for expanded card:",ee)}},[]),lA=o.useCallback(g=>{if(g.type==="str"&&g.strData){const I=Ac.find(L=>L.id===g.id||L.snapshotId===g.id);if(I){const L=Vb(I,!1);zn(L)}else{const L=g.strData,Y={id:g.id,snapshotId:g.id,address:g.label||"STR Rental",price:L.nightlyRate||0,beds:L.bedrooms||0,baths:L.bathrooms||0,sqft:L.gla||0,coordinates:{lat:g.lat,lng:g.lng},photoUrl:L.photoUrl,photos:L.photos||(L.photoUrl?[L.photoUrl]:[]),isStrProperty:!0,strListingName:L.listingName,strAverageDailyRate:L.nightlyRate,strOccupancyRate:L.occupancyRate,strGrossRevenue12mo:L.annualRevenue,strRating:L.rating,strReviewCount:L.reviewCount,strSource:L.platform,strRe
53ntalType:L.rentalType};zn(Y)}const k=document.getElementById(`property-card-${g.id}`);k&&(k.scrollIntoView({behavior:"smooth",block:"center"}),k.classList.add("ring-2","ring-purple-500"),setTimeout(()=>{k.classList.remove("ring-2","ring-purple-500")},2e3))}else if(g.data){const I=g.data;Pf(I);const k=document.getElementById(`property-card-${g.id}`);k&&(k.scrollIntoView({behavior:"smooth",block:"center"}),k.classList.add("ring-2","ring-blue-500"),setTimeout(()=>{k.classList.remove("ring-2","ring-blue-500")},2e3))}},[Ac,Pf]),cA=o.useRef(null),dA=o.useCallback(g=>{g.coordinates&&ml({lat:g.coordinates.lat,lng:g.coordinates.lng})},[]),BF=async(g,I)=>{if(C&&Us!=="rental"&&!Ed.current)return;const k=g.snapshotId||g.id;let L;const Y=K=>{const te=FZ(K),q=r0(K),ie=K.rawMlsStatus??K.status,ee=J0(ie),we=ee==="CLSD"?"CLSD":ee==="PEND"?"PEND":O0(ee)?"ACTV":"PEND",ve=[K.address||"",K.city||"",K.state||"",K.zip||""].filter(Boolean).join(", ");return{id:K.id,snapshotId:q,mlsNumber:K.mlsNumber,mlsBoard:K.mlsBoard,address:K.address||"",fullAddress:ve,city:K.city||"",state:K.state||"",zip:K.zip||"",price:K.price??0,listPrice:K.listPrice,beds:K.beds,baths:K.baths,sqft:K.sqft,gla:K.sqft??0,lotSqft:K.lotSqft,yearBuilt:K.yearBuilt,status:we,rawMlsStatus:ie,saleDate:K.saleDate,listDate:K.listDate,contractDate:void 0,dom:K.dom??0,distance:K.distance??0,propertyType:K.propertyType||"SFR",coordinates:K.coordinates||{lat:0,lng:0},source:"cache",photos:K.photos||[],selectionState:"none",similarityScore:K.similarityScore,matchScore:K.matchScore,pricePerSqft:K.pricePerSqft,echoLocationScore:K.echoLocationScore,conditionRating:K.conditionRating,qualityRating:K.qualityRating,garageSpaces:te.garageSpaces,mlsData:te.mlsData||void 0,publicRecordData:te.publicRecordData||void 0}};if(Fr&&mr.length>0){const K=mr.find(te=>(te.snapshotId||te.id)===k);K&&(L=Y(K))}if(!L&&Tr&&Nn.length>0){const K=Nn.find(te=>(te.snapshotId||te.id)===k);K&&(L=Y(K))}if(L||(L=re.properties.find(K=>(K.snapshotId||K.id)===k)),L||(L=Kr.find(K=>(K.snapshotId||K.id)===k)),L||(L=Ac.find(K=>(K.snapshotId||K.id)===k)),L&&!pu(L)){const K=Math.max(0,vt-Te);if((C&&Us!=="rental"?ar?.selectedCount??re.selectedComps.length:re.selectedComps.length)>=K){Ve({title:"Comparable limit reached",description:`The report supports up to ${K} sales comparable${K!==1?"s":""} given other active comparable types. Unselect one before adding another.`});return}qe(Se=>({...Se,selectedComps:[...Se.selectedComps,L]})),C&&Us!=="rental"&&Xs(Se=>_j(Se,1));const q=dI(L);let ie=q;const ee=YZ(L,Dr.current.get(L.snapshotId||L.id)),we=()=>{!C||Us==="rental"||(qe(Se=>({...Se,selectedComps:SO(Se.selectedComps,{id:L.id,snapshotId:ie})})),Xs(Se=>_j(Se,-1)))};if(rJ({enableUad36:C,compSelectionMode:Us,snapshotId:ie})){if(r)try{console.log("[PropertyLab] Saving comp to database before selection:",L.address||L.id);const Se={mlsNumber:C&&Us!=="rental"?oJ({id:L.id,mlsNumber:L.mlsNumber,mlsData:L.mlsData,canonicalSnapshotId:q}):_M({id:L.id,mlsNumber:L.mlsNumber,mlsData:L.mlsData}),mlsBoard:i0({mlsBoard:L.mlsBoard,mlsData:L.mlsData}),address:L.address||L.fullAddress,city:L.city,state:L.state,zipCode:L.zip,latitude:L.coordinates?.lat?.toString(),longitude:L.coordinates?.lng?.toString(),salePrice:L.price?.toString(),mlsStatus:L.status,saleDate:L.saleDate,listDate:L.listDate,bedrooms:L.beds,bathrooms:L.baths?.toString(),sqft:L.gla||L.sqft,garageSpaces:L.garageSpaces,yearBuilt:L.yearBuilt,propertyType:L.propertyType,primaryPhotoUrl:L.photoUrl||L.photos?.[0],btQualityRating:ee.quality,btConditionRating:ee.condition,daysOnMarket:L.dom,rawMlsData:{...L.mlsData??{},rawMlsStatus:L.rawMlsStatus??L.status},rawPublicRecordData:L.publicRecordData};L.isStrProperty&&(Se.isStrProperty=!0,Se.strSource=L.strSource,Se.strProviderId=L.strProviderId,Se.strListingName=L.strListingName,Se.strRentalType=L.strRentalType,Se.strAverageDailyRate=L.strAverageDailyRate,Se.strOccupancyRate=L.strOccupancyRate,Se.strGrossRevenue12mo=L.strGrossRevenue12mo,Se.strRating=L.strRating,Se.strReviewCount=L.strReviewCount,Se.strGuestCapacity=L.strGuestCapacity,Se.strProvider=L.strProvider||L.strS
53ource,Se.strAmenities=L.strAmenities);const Qe=C&&Us!=="rental"?await dn(`/api/uad36/comparables/${encodeURIComponent(r)}/resolve-snapshot`,{candidateSnapshotId:q??null,snapshot:Se},{headers:ho(r)}):await dn("/api/comps",Se);if(Qe.success&&Qe.comp?.id){ie=Qe.comp.id;const Nt=L.snapshotId||L.id;console.log("[PropertyLab] Comp saved with snapshotId:",ie),qe(Ct=>({...Ct,selectedComps:Ct.selectedComps.map(va=>(va.snapshotId||va.id)===Nt?{...va,snapshotId:ie}:va),properties:Ct.properties.map(va=>(va.snapshotId||va.id)===Nt?{...va,snapshotId:ie}:va)})),_o(Ct=>Ct.map(va=>(va.snapshotId||va.id)===Nt?{...va,snapshotId:ie}:va)),Jl(Ct=>Ct.map(va=>(va.snapshotId||va.id)===Nt?{...va,snapshotId:ie}:va)),Qu(Ct=>Ct.map(va=>(va.snapshotId||va.id)===Nt?{...va,snapshotId:ie}:va)),cu(Ct=>Ct.map(va=>(va.snapshotId||va.id)===Nt?{...va,snapshotId:ie}:va))}else ie=void 0}catch(Se){ie=void 0,console.error("[PropertyLab] Failed to save comp to database:",Se)}}else qe(Se=>({...Se,selectedComps:Se.selectedComps.map(Qe=>(Qe.snapshotId||Qe.id)===(L.snapshotId||L.id)?{...Qe,snapshotId:ie}:Qe)}));const ve=He?I||yl:void 0;if(He&&ve){const Se=L.id;gu(Qe=>({...Qe,[Se]:ve}))}if(r&&ie)try{if(console.log("[PropertyLab] Persisting comp selection:",ie,"for assignment:",r),C&&Us!=="rental"){++$o.current,++Sc.current;const Se=await dn(`/api/uad36/comparables/${encodeURIComponent(r)}/memberships`,{compSnapshotId:ie,...s?{subjectCoordinates:{latitude:s.lat,longitude:s.lng}}:{}},{headers:ho(r)});++Sc.current,zS(Se).length>0&&dr(Se,!1),is(Nt=>Nt+1)}else await dn("/api/comps/select",{compSnapshotId:ie,assignmentId:r,selectionOrder:re.selectedComps.length+1,...ve?{scenarioTag:ve}:{}});console.log("[PropertyLab] Selection persisted successfully")}catch(Se){C&&Us!=="rental"&&(++Sc.current,we(),is(Qe=>Qe+1),Ve({title:"Comparable not selected",description:"The comparable was not added to the report. Please try again.",variant:"destructive"})),Se instanceof qo&&Se.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to persist selection:",Se)}else ie?(console.warn("[PropertyLab] No assignmentId available - selection not persisted to database"),we()):(console.warn("[PropertyLab] No database snapshotId available - selection not persisted"),C&&Us!=="rental"&&(we(),Ve({title:"Comparable not selected",description:"The property could not be saved before adding it to the report. Please try again.",variant:"destructive"})))}},tR=async(g,I)=>{if(Cp.current)return;const k=C&&Us!=="rental",L=k?++Wi.current:0,Y=r,K=BF(g,I);if(!k){await K;return}ti.current.add(K);try{await K}finally{if(ti.current.delete(K),r&&ti.current.size===0)try{const te=await Ho(`/api/uad36/comparables/${encodeURIComponent(r)}`,{cache:"no-store"});VZ({requestGeneration:L,currentGeneration:Wi.current,requestAssignmentId:Y,currentAssignmentId:sl.current,pendingCount:ti.current.size})&&dr(te,!0)}catch(te){console.error("[PropertyLab] Failed to settle ordered comparables after selection:",te)}}},My=o.useRef(tR);My.current=tR;const Tb=o.useCallback(async(g,I)=>{if(He){const k=I?.currentTarget?.getBoundingClientRect(),L=k?k.left:I?.clientX??window.innerWidth/2-96,Y=k?k.bottom+4:I?.clientY??window.innerHeight/2;Wu({property:g,x:L,y:Y});return}await My.current(g)},[He]),uA=o.useRef(new Set),Zg=o.useCallback(async g=>{const I=g.snapshotId||g.id,k=C&&Us!=="rental",L=k&&!!g.snapshotId,Y=k&&!!r;let K=null;if(Y){if(uA.current.has(I))return;uA.current.add(I)}if(qe(te=>({...te,selectedComps:te.selectedComps.filter(q=>(q.snapshotId||q.id)!==I)})),k){K=++$o.current,++Sc.current;const te=SO(Lr.current,{id:g.id,snapshotId:g.snapshotId});Lr.current=te,Pi(te),Xs(q=>q&&(L?_j(q,-1):{...q,gridCount:Math.max(0,q.gridCount-1),available:q.available+1}))}if(r)try{if(k){const te=await Wy(lJ(r,{id:g.id,snapshotId:g.snapshotId}),{headers:ho(r)});if(++Sc.current,K===$o.current){const q=zS(te),ie=n0(Vj(q),[...Qc.current,...Dl.current]);Lr.current=ie,Pi(ie)}is(q=>q+1)}else await Wy(`/api/comps/select/${I}/${r}`)}catch(te){k&&(++Sc.current,is(q=>q+1)),te instanceof qo&&te.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to persist deselection:",te)}finally{Y&&uA.current.delete(I)}}
53,[r,C,Us]),Of=o.useMemo(()=>{const g=new Set;return Ss.forEach(I=>{I.snapshotId&&g.add(I.snapshotId),I.mlsNumber&&g.add(I.mlsNumber)}),g},[Ss]),Ib=o.useCallback(g=>g?!!(g.snapshotId&&Of.has(g.snapshotId)||g.id&&Of.has(g.id)||g.mlsNumber&&Of.has(g.mlsNumber)):!1,[Of]);o.useEffect(()=>{if(!C||!r)return;let g=!1;return(async()=>{try{const I=await Ho(`/api/comps/rental-selection/${r}`);if(g)return;const k=Array.isArray(I?.comps)?I.comps:[];k.length>0?fr(k.map(L=>({snapshotId:L.id,mlsNumber:L.mlsNumber??null}))):Array.isArray(I?.compSnapshotIds)&&fr(I.compSnapshotIds.map(L=>({snapshotId:L,mlsNumber:null})))}catch(I){console.warn("[PropertyLab] Failed to load rental selection:",I)}})(),()=>{g=!0}},[C,r]);const Fy=o.useCallback(async g=>{if(r)try{await dn(`/api/comps/rental-selection/${r}`,{compSnapshotIds:g.map(I=>I.snapshotId)})}catch(I){I instanceof qo&&I.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to persist rental selection:",I)}},[r,Ve]),aR=o.useCallback(async g=>{if((k=>!!k&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(k))(g.snapshotId))return g.snapshotId;if(r)try{const k={mlsNumber:g.mlsData?.mlsNumber||g.id,address:g.address||g.fullAddress,city:g.city,state:g.state,zipCode:g.zip,latitude:g.coordinates?.lat?.toString(),longitude:g.coordinates?.lng?.toString(),salePrice:g.price?.toString(),mlsStatus:g.status,saleDate:g.saleDate,listDate:g.listDate,bedrooms:g.beds,bathrooms:g.baths?.toString(),sqft:g.sqft,yearBuilt:g.yearBuilt,propertyType:g.propertyType,primaryPhotoUrl:g.photoUrl||g.photos?.[0],daysOnMarket:g.dom,rawMlsData:g.mlsData,rawPublicRecordData:g.publicRecordData},L=await dn("/api/comps",k);if(L.success&&L.comp?.id)return L.comp.id}catch(k){console.error("[PropertyLab] Failed to save rental comp to database:",k)}},[r]),Cb=o.useCallback(async g=>{if(!r)return;const I=g.mlsNumber??g.mlsData?.mlsNumber??g.id??null;if(Ib({id:g.id,snapshotId:g.snapshotId,mlsNumber:I}))return;const k=await aR(g);if(!k){Ve({title:"Couldn't save rental comp",description:"Please try again.",variant:"destructive"});return}if(an.current.some(Y=>Y.snapshotId===k))return;const L=[...an.current,{snapshotId:k,mlsNumber:I}];fr(L),await Fy(L)},[r,Ib,aR,Fy,Ve]),Rb=o.useCallback(async g=>{const I=g.snapshotId||g.id,k=g.mlsNumber??g.mlsData?.mlsNumber??g.id??null,L=an.current.filter(Y=>!(g.snapshotId&&Y.snapshotId===g.snapshotId||I&&Y.snapshotId===I||k&&Y.mlsNumber===k));L.length!==an.current.length&&(fr(L),await Fy(L))},[Fy]),zF=async g=>{if(!g||!window.google?.maps?.Geocoder)return null;try{const I=new window.google.maps.Geocoder;return new Promise(k=>{I.geocode({address:g},(L,Y)=>{if(Y==="OK"&&L&&L[0]?.geometry?.location){const K=L[0].geometry.location;k({lat:K.lat(),lng:K.lng()})}else console.log("[PropertyLab] Geocoding failed:",Y),k(null)})})}catch(I){return console.error("[PropertyLab] Geocoding error:",I),null}},vu=C&&Us==="rental"&&Ut,pA=o.useCallback(g=>{g.data&&(vu?Cb(g.data):_a&&Tb(g.data))},[vu,_a,Cb,Tb]),mA=o.useCallback(g=>{g.data&&(vu?Rb(g.data):_a&&Zg(g.data))},[vu,_a,Rb,Zg]),qF=o.useCallback(()=>{if(Yn.isPopoutOpen)return;In.current=bs,Yn.openPopout()?ba(bs==="list"||bs==="list-map"?"list":"cards"):Ve({title:"Pop-up blocked",description:"Please allow pop-ups for this site to use the map pop-out feature.",variant:"destructive"})},[Yn,bs,Ve]),sR=o.useMemo(()=>{const g=[],I=re.filters,k=Y=>Y>=1e6?`$${(Y/1e6).toFixed(Y%1e6===0?0:1)}M`:Y>=1e3?`$${Math.round(Y/1e3)}K`:`$${Y}`;if(I.minSqft!=null||I.maxSqft!=null){const Y=I.minSqft!=null?I.minSqft.toLocaleString():"",K=I.maxSqft!=null?I.maxSqft.toLocaleString():"",te=Y&&K?`${Y}–${K} sqft`:Y?`${Y}+ sqft`:`≤ ${K} sqft`;g.push({key:"gla",label:te})}if(I.minPrice!=null||I.maxPrice!=null){const Y=I.minPrice!=null?k(I.minPrice):"",K=I.maxPrice!=null?k(I.maxPrice):"",te=Y&&K?`${Y}–${K}`:Y?`${Y}+`:`≤ ${K}`;g.push({key:"price",label:te})}if(I.minBeds!=null||I.maxBeds!=null){const Y=I.minBeds!=null?`${I.minBeds}`:"",K=I.maxBeds!=null?`${I.maxBeds}`:"",te=Y&&K?`${Y}–${K} bd`:Y?`${Y}+ bd`:`≤ ${K} bd`;g.push({key:"beds",label:te})}if(I.minBaths!=null||I.maxBaths!=null){const Y=I.minBaths!=null?`${I.minBaths}`:"",K=I.maxBaths!=null?`${I.maxBaths}`:"",te=Y&&K?`${Y}–${K} ba`:Y?`${Y}+ ba`:`≤ ${K} ba`;g.push({key:"baths",label:te})}const L=I.statusSelection??I.status;if(L&&L.length>0&&L.length<14){const Y=L.length<=3?L.join("/"):`${L.length} statuses`;g.push({key:"status",label:Y})}if(I.dateRangeMode==="custom"&&(I.dateRangeStart||I.dateRangeEnd)){const Y=`${I.dateRangeStart||"…"} → ${I.dateRangeEnd||"…"}`;g.push({key:"date",label:Y})}else if(I.monthsBack!=null){const Y=I.monthsBack>=12?`${Math.round(I.monthsBack/12)} yr`:`${I.monthsBack} mo`;g.push({key:"date",label:`Last ${Y}`})}return g},[re.filters]);o.useEffect(()=>{Yn.isPopoutOpen&&Yn.syncState({locations:Ep,subjectMarker:s??null,hoveredLocationId:re.hoveredPropertyId,selectedCompIds:Array.from(vu?Of:ro),shapes:Ma,appliedBoundaries:js,center:w,zoom:Bn??13,subjectAddress:a,subjectState:i,filterChips:sR})},[Yn.isPopoutOpen,Ep,s,re.hoveredPropertyId,vu,Of,ro,Ma,js,w,Bn,a,i,sR]);const hA=o.useRef(null);o.useEffect(()=>{Yn.onHoverRef.current=g=>{qe(I=>({...I,hoveredPropertyId:g}))},Yn.onMarkerClickRef.current=g=>{const I=Ep.find(k=>k.id===g);I&&lA(I)},Yn.onSelectRef.current=g=>{const I=Ep.find(k=>k.id===g);I&&pA(I)},Yn.onDeselectRef.current=g=>{const I=Ep.find(k=>k.id===g);I&&mA(I)},Yn.onApplyShapesRef.current=g=>{Xn(g);const I=zV(Ny??Ep,g);Ty(g,I)},Yn.onApplyBoundaryRef.current=g=>{hA.current?.add(g)},Yn.onRemoveBoundaryRef.current=g=>{hA.current?.remove(g)}},[Ep,Ny,lA,pA,mA,Ty]);const fA=o.useRef(!1);o.useEffect(()=>{if(Yn.isPopoutOpen)fA.current=!0;else if(fA.current){fA.current=!1;const g=In.current;(g==="map"||g==="cards-map"||g==="list-map")&&ba(g)}},[Yn.isPopoutOpen]);const rR=g=>{if(!g?.coordinates)return null;try{let I=[];if(g.type==="Polygon"&&Array.isArray(g.coordinates[0]))I=g.coordinates[0];else if(g.type==="MultiPolygon"&&Array.isArray(g.coordinates[0])){const te=g.coordinates;let q=0;for(const ie of te)Array.isArray(ie[0])&&ie[0].length>q&&(I=ie[0],q=ie[0].length)}if(I.length<3)return null;let k=1/0,L=-1/0,Y=1/0,K=-1/0;for(const te of I)if(Array.isArray(te)&&te.length>=2){const[q,ie]=te;typeof q=="number"&&typeof ie=="number"&&isFinite(q)&&isFinite(ie)&&(Y=Math.min(Y,q),K=Math.max(K,q),k=Math.min(k,ie),L=Math.max(L,ie))}
53return!isFinite(k)||!isFinite(L)||!isFinite(Y)||!isFinite(K)?null:{lat:(k+L)/2,lng:(Y+K)/2}}catch(I){return console.error("[PropertyLab] Error extracting polygon center:",I),null}},nR=async()=>{if(Qn.current&&Tc.current)console.log("[PropertyLab] handleSearch called while search in flight — aborting previous request"),Tc.current.abort();else if(Qn.current){console.log("[PropertyLab] handleSearch called but search already in flight, queuing"),En.current=!0;return}if(Zs){console.log("[PropertyLab] handleSearch BLOCKED - currently in review mode:",Zs),En.current=!1;return}if(!(Ma.circles.length>0||Ma.polygons.length>0||js.length>0)){jo.current?(console.log("[PropertyLab] handleSearch skipped — user cleared geometry, staying empty"),En.current=!1):(console.log("[PropertyLab] handleSearch deferred — no geometric constraint yet (waiting for boundary/shape)"),En.current=!0),Qn.current=!1;return}console.log("[PropertyLab] handleSearch STARTING with appliedBoundaries:",js.length,js.map(aa=>aa.name));{const aa=tA.current||"effect-driven";tA.current="effect-driven",console.log("[PropertyLab] refresh-trigger",aa,{preRefreshPropertyCount:re.properties.length,preRefreshSelectedCount:mu.current.length,sortBy:re.filters.sortBy,circles:Ma.circles.length,polygons:Ma.polygons.length,boundaries:js.length,geometrySearchInFlight:Wt})}Tc.current&&Tc.current.abort(),Ju.current&&(Ju.current.abort(),Ju.current=null,jb.current=!1,vy(!1));const I=new AbortController;Tc.current=I,Qn.current=!0,qs(!1);const k={monthsBack:re.filters.monthsBack??re.filters.dateRangePreset,dateFilterField:re.filters.dateFilterField??"closed"};Rf.current="preparing search",YC.current+=1;const L=YC.current;uh(null),qe(aa=>({...aa,isLoading:!0,error:null,dataSource:null}));const Y=Ma.circles.length>0||Ma.polygons.length>0;Wc("Checking saved comps…"),yo.current&&clearTimeout(yo.current),yo.current=setTimeout(()=>{Wc(aa=>
53aa&&(Y?"Still searching MLS in your drawn area…":"Still searching… expanding the radius for new areas can take a few seconds."))},5e3);const K=15e3,te=45e3;let q=!1;Ef.current=null,wf.current=null;const ie=setTimeout(()=>{I.signal.aborted||(console.log("[PropertyLab] Search soft timeout (15s) — still working, no abort"),Ud(td,()=>{Ve({title:"Still searching…",description:"Looking for nearby comps. This can take a moment for new areas."})}))},K),ee=setTimeout(()=>{I.signal.aborted||(q=!0,I.abort())},te);Ef.current=ie,wf.current=ee;const we=3e4,ve=setTimeout(()=>{I.signal.aborted||(console.warn(`[PropertyLab] Search kickoff watchdog fired at ${we}ms — surfacing Retry/Report (request still in flight)`),Ud(td,()=>{uh(aa=>aa??{title:"Still waiting on results",description:"The search is taking longer than usual to return. You can wait, retry, or report this so we can investigate.",kickoffToken:L})}))},we);Zu.current=ve;let Se=Ks||s,Qe=re.marketDefinition?.radiusMiles||1,Nt;if(Ma.circles.length>0){const aa=Ma.circles[0];Se=aa.center,Qe=aa.radiusMeters/1609.34,console.log("[PropertyLab] Using drawn circle:",aa.center,Qe,"miles")}else if(Ma.polygons.length>0){const aa=Ma.polygons[0];Nt=aa.path;let Ft=0,ss=0;for(const es of aa.path)Ft+=es.lat,ss+=es.lng;Se={lat:Ft/aa.path.length,lng:ss/aa.path.length};let da=0;for(const es of aa.path){const Js=Math.sqrt(Math.pow((es.lat-Se.lat)*69,2)+Math.pow((es.lng-Se.lng)*69*Math.cos(Se.lat*Math.PI/180),2));da=Math.max(da,Js)}Qe=Math.max(da*1.5,1),console.log("[PropertyLab] Using drawn polygon with center:",Se,"approx radius:",Qe)}if(js.length>0){const aa=js.find(Ft=>Ft.polygon?.coordinates);if(aa?.polygon){const Ft=rR(aa.polygon);Ft&&(console.log("[PropertyLab] Overriding search center with boundary centroid:",Ft,"(was:",Se,")"),Se=Ft)}else{const Ft=js.find(ss=>ss.center&&ss.radiusMiles);Ft?.center&&(console.log("[PropertyLab] Overriding search center with radius boundary center:",Ft.center),Se=Ft.center)}}if(!Se){const aa=js.find(Ft=>Ft.center&&Ft.radiusMiles);aa?.center&&(Se=aa.center)}if(!Se){const aa=js.find(Ft=>Ft.polygon?.coordinates);if(aa?.polygon){const Ft=rR(aa.polygon);Ft&&(Se=Ft,console.log("[PropertyLab] Using polygon bounding box center:",Ft))}}if(!Se&&a){console.log("[PropertyLab] Geocoding subject address:",a),Rf.current="Geocoding subject address",Ud(td,()=>{Ve({title:"Locating Address...",description:"Geocoding subject property address"})});const aa=await zF(a);aa&&(Se=aa,console.log("[PropertyLab] Geocoded coordinates:",aa))}if(!Se?.lat||!Se?.lng){const aa=kj(null,"Locate search area");Ud(td,()=>{uh(aa),qe(Ft=>({...Ft,isLoading:!1,error:aa.description,dataSource:null}))}),Qn.current=!1,Ud(td,()=>
53{Ve({title:aa.title,description:aa.description,variant:"destructive"})});return}const Ct=Qe||re.marketDefinition?.radiusMiles||1;let va=!1,Ht=0;const Cs=async()=>{try{const aa=re.filters.statusSelection?.length?re.filters.statusSelection:re.filters.status,Ft={lat:Se.lat,lng:Se.lng,subjectAddress:a,status:aa,monthsBack:re.filters.monthsBack,dateFilterField:re.filters.dateFilterField??"closed",assignmentId:r};Nt&&Nt.length>=3&&(Ft.polygon=Nt,console.log("[PropertyLab] Sending polygon with",Nt.length,"points to backend")),re.filters.propertyType&&(Ft.propertyType=re.filters.propertyType),re.filters.minPrice&&(Ft.minPrice=re.filters.minPrice),re.filters.maxPrice&&(Ft.maxPrice=re.filters.maxPrice),re.filters.minBeds&&(Ft.minBeds=re.filters.minBeds),re.filters.maxBeds&&(Ft.maxBeds=re.filters.maxBeds),re.filters.minBaths&&(Ft.minBaths=re.filters.minBaths),re.filters.maxBaths&&(Ft.maxBaths=re.filters.maxBaths),re.filters.minSqft&&(Ft.minSqft=re.filters.minSqft),re.filters.maxSqft&&(Ft.maxSqft=re.filters.maxSqft),Ft.includeZeroGla=re.filters.includeZeroGla!==!1;const ss=performance.now();let da=null,es=[],Js=0;const er=re.filters.monthsBack??re.filters.dateRangePreset,ga=er===void 0||er>36,As=aa?.some(Vs=>Hf.has(Vs))??!1,Ya=!1,Aa=js.length>0,ns=Tr||fe,Sr=Aa&&!ns,Or=s||Se;if(Sr?console.log("[PropertyLab] Using BOUNDARY CACHE strategy - querying cached comps by bounding box first"):Aa&&ns&&console.log("[PropertyLab] Using cache despite boundary - market is locked (marketLocked:",Tr,"initialMarketLocked:",fe,")"),ga&&console.log("[PropertyLab] Skipping cache for extended/unlimited date range:",er===void 0?"ALL":`${er} months`),Sr&&!Ya){const Vs=(()=>{let $s=1/0,Ar=-1/0,jn=1/0,_l=-1/0;for(const Ln of js)if(Ln.polygon?.coordinates){const zo=[];if(Ln.polygon.type==="MultiPolygon")for(const nn of Ln.polygon.coordinates)nn[0]&&zo.push(...nn[0]);else Ln.polygon.type==="Polygon"&&zo.push(...Ln.polygon.coordinates[0]);for(const nn of zo)if(Array.isArray(nn)&&nn.length>=2){const[vl,Nl]=nn;typeof vl=="number"&&typeof Nl=="number"&&isFinite(vl)&&isFinite(Nl)&&(jn=Math.min(jn,vl),_l=Math.max(_l,vl),$s=Math.min($s,Nl),Ar=Math.max(Ar,Nl))}}else if(Ln.center&&Ln.radiusMiles){const zo=Ln.radiusMiles/69,nn=Ln.radiusMiles/(69*Math.cos(Ln.center.lat*Math.PI/180));$s=Math.min($s,Ln.center.lat-zo),Ar=Math.max(Ar,Ln.center.lat+zo),jn=Math.min(jn,Ln.center.lng-nn),_l=Math.max(_l,Ln.center.lng+nn)}return isFinite($s)?{minLat:$s,maxLat:Ar,minLng:jn,maxLng:_l}:null})();if(Vs){const $s=performance.now();Rf.current="Boundary cache lookup";const Ar=await dn("/api/comps/cached-search/boundary",{bounds:Vs,centerLat:Se?.lat,centerLng:Se?.lng},{throwOnSuccessFalse:!1,signal:I.signal});Js=performance.now()-$s,Ar.cached&&Ar.comps?.length>0?(es=Ar.comps,Ht=es.length,da={success:!0,comps:es,source:"boundary-cache",meta:Ar.meta},console.log("[PropertyLab:Timing] Boundary cache HIT:",{source:"boundary-cache",cachedCount:es.length,t_api_fetch:Math.round(Js),t_db_fetch:Ar.meta?.t_db_fetch,t_server_total:Ar.meta?.t_total})):console.log("[PropertyLab] Boundary cache returned 0 results, will fall through to PropMix")}}if(!da&&r&&Or&&!ga&&!Ya&&!Sr){const Vs={assignmentId:r,lat:Or.lat,lng:Or.lng},$s=performance.now();Rf.current="Cached comp search";const Ar=await dn("/api/comps/cached-search/thin",Vs,{throwOnSuccessFalse:!1,signal:I.signal});Js=performance.now()-$s,Ar.cached&&Ar.comps?.length>0?(es=Ar.comps,Ht=es.length,da={success:!0,comps:es,source:"cache",cacheKey:Ar.meta?.cacheKey,finalRadiusUsed:Ar.meta?.finalRadiusUsed,meta:Ar.meta},console.log("[PropertyLab:Timing] Cache HIT from thin endpoint:",{source:"compSearches",cachedCount:es.length,t_api_fetch:Math.round(Js),t_db_fetch:Ar.meta?.t_db_fetch,t_server_total:Ar.meta?.t_total})):console.log("[PropertyLab] Cache MISS from compSearches, cacheKey:",Ar.cacheKey)}const Li=!da||!As||es.length===0?!1:es.filter($s=>$s?.status&&Hf.has($s.status)).length===0?(console.log("[PropertyLab] Cache hit but contains 
53no active comps for requested status filter — falling through to PropMix"),!0):!1;if(!da||es.length===0||Li){console.log("[PropertyLab] Cache empty, fetching from PropMix..."),Rf.current="PropMix comp search";const Vs=Math.round(Ct*10)/10;if(Wc(`Searching nearby sales within ${Vs} mi…`),da=await dn("/api/comps/search",Ft,{throwOnSuccessFalse:!1,signal:I.signal}),console.log("[PropertyLab] PropMix response:",{source:da.source,count:da.comps?.length||0,finalRadiusUsed:da.finalRadiusUsed}),da.propMixUnavailable){Ud(td,()=>{qe($s=>({...$s,isLoading:!1,properties:[],searchPerformed:!0,error:"PROPERTY_DATA_SERVICE_UNAVAILABLE"})),Ve({title:"Property data service unavailable",description:"Property search is not available — PropMix API credentials are not configured. Contact your administrator.",variant:"destructive"})});return}}const Ti=da.comps||da.results||[];console.log("[PropertyLab] Search response:",{success:da.success,fromCache:da.fromCache,rawResultsCount:Ti.length,sampleCoords:Ti[0]?.coordinates,photoHealth:da.meta?.photoHealth}),da.meta?.photoHealth?.pending>5&&dn("/api/comps/hydrate-photos",{limit:Math.min(da.meta.photoHealth.pending,50)},{throwOnSuccessFalse:!1}).then(()=>console.log("[PropertyLab] Triggered photo hydration for pending comps")).catch(()=>{});const Ic=Ti.filter(Vs=>{const $s=Vs.coordinates&&typeof Vs.coordinates.lat=="number"&&typeof Vs.coordinates.lng=="number"&&!isNaN(Vs.coordinates.lat)&&!isNaN(Vs.coordinates.lng);return!$s&&Ti.length>0&&console.log("[PropertyLab] Invalid coords for comp:",Vs.id,Vs.coordinates),$s});console.log("[PropertyLab] Valid results after coord filter:",Ic.length);const oc=re.filters.monthsBack??re.filters.dateRangePreset,Lf=js.length>0,Xg=re.filters.dateFilterField??"closed",wb=Vs=>Xg==="contract"?Vs.contractDate:Vs.saleDate;let Pp;if(oc===void 0)Lf?(Pp=Ic,console.log("[PropertyLab] Results with no date filter (boundary search - all results):",Pp.length)):(Pp=Ic.filter(Vs=>!!(wb(Vs)||Vs.listDate)),console.log("[PropertyLab] Results with no date filter (all dates):",Pp.length));else{const Vs=new Date;Vs.setMonth(Vs.getMonth()-oc),Pp=Ic.filter($s=>{if(O0($s.status)||$s.status==="PEND")return!0;const Ar=wb($s)||$s.listDate;return Ar?new Date(Ar)>=Vs:!!(Lf&&$s.status==="CLSD")}),console.log("[PropertyLab] Results after date filter:",Pp.length,"monthsBack:",oc,"dateField:",Xg,"boundaryApplied:",Lf)}const Fl=performance.now(),ad=Pp.map(Vs=>({...Vs,similarityScore:eS(Ld,Vs)})),Df=performance.now()-Fl,zy=performance.now()-ss;console.log("[PropertyLab:Timing] Complete:",{t_api_fetch:Math.round(Js),t_process:Math.round(Df),t_total:Math.round(zy),compsCount:ad.length}),eA.current=k,er===void 0?mh.current=Number.POSITIVE_INFINITY:er>mh.current&&(mh.current=er);const qy=Vs=>{let $s=2166136261;for(let Ar=0;Ar<Vs.length;Ar++)$s^=Vs.charCodeAt(Ar),$s=$s+(($s<<1)+($s<<4)+($s<<7)+($s<<8)+($s<<24))>>>0;return("00000000"+$s.toString(16)).slice(-8)},Cc=Ft,m5=JSON.stringify({s:Cc?.status??null,pt:Cc?.propertyType??null,bds:[Cc?.minBeds??null,Cc?.maxBeds??null],ba:[Cc?.minBaths??null,Cc?.maxBaths??null],sq:[Cc?.minSqft??null,Cc?.maxSqft??null],yr:[Cc?.minYearBuilt??null,Cc?.maxYearBuilt??null],pr:[Cc?.minPrice??null,Cc?.maxPrice??null],mb:Cc?.monthsBack??null,df:Cc?.dateFilterField??"closed",zg:Cc?.includeZeroGla!==!1,gh:Nt?`poly:${Nt.length}@${Nt[0]?.lat?.toFixed(2)},${Nt[0]?.lng?.toFixed(2)}`:`radius:${Math.round((Se?.lat??0)*100)/100},${Math.round((Se?.lng??0)*100)/100}@${Math.round(Qe*10)/10}`}),fh=`${r??"na"}|${qy(m5)}`,ex=Oy.current.get(fh)??0,kf=ad.length,h5=ex>0&&kf<ex-20&&kf<Math.floor(ex*.7)&&!sA.current.has(fh);if(kf>ex&&Oy.current.set(fh,kf),h5){sA.current.add(fh),console.warn(`[PropertyLab] Count floor breach detected: returned=${kf} < floor=${ex} for key=${fh} — kicking force-live refloor`);const Vs={...Ft,useCache:!1};dn("/api/comps/search",Vs,{throwOnSuccessFalse:!1}).then($s=>{const _l=($s?.comps||$s?.results||[]).filter(nn=>nn.coordinates&&typeof nn.coordinates.lat=="number"&&typeof nn.coordinates.lng=="number"&&!isNaN(nn.coordinates.lat)&&!isNaN(nn.coordinates.lng)).map(nn=>({...nn,similarityScore:eS(Ld,nn)}));if(_l.length===0)return;let Ln=0;qe(nn=>{const vl=new Set(nn.properties.map(Ul=>Ul.snapshotId||Ul.id)),Nl=new Set(nn.properties.map(Ul=>
53YS(Ul)).filter(Boolean)),Md=[...nn.properties];for(const Ul of _l){const Pb=Ul.snapshotId||Ul.id;if(Pb&&vl.has(Pb))continue;const Ur=YS(Ul);Ur&&Nl.has(Ur)||(vl.add(Pb),Ur&&Nl.add(Ur),Md.push(Ul),Ln++)}return Ln>0?{...nn,properties:Md}:nn}),cu(nn=>{const vl=new Set(nn.map(Md=>Md.snapshotId||Md.id)),Nl=[...nn];for(const Md of _l){const Ul=Md.snapshotId||Md.id;Ul&&!vl.has(Ul)&&(vl.add(Ul),Nl.push(Md))}return Nl});const zo=kf+Ln;zo>(Oy.current.get(fh)??0)&&Oy.current.set(fh,zo),console.log(`[PropertyLab] Refloor merged ${Ln} additional comps (was ${kf}, now ${zo}, floor was ${ex})`)}).catch($s=>{console.warn("[PropertyLab] Refloor follow-up failed (non-fatal):",$s)}).finally(()=>{sA.current.delete(fh)})}qe(Vs=>({...Vs,properties:ad,isLoading:!1,searchPerformed:!0,dataSource:da.source==="cache"?"comp-vault":"public-mls",marketDefinition:{radiusMiles:da.finalRadiusUsed||Ct,center:Se||void 0,totalProperties:ad.length},cacheMetadata:da.meta?{isStale:da.meta.isStale||!1,shouldRevalidate:da.meta.shouldRevalidate||!1,maxAgeMinutes:da.meta.maxAgeMinutes||0,propMixFailed:da.propMixFailed||!1,stalePercentage:da.meta.stalePercentage||0,source:da.meta.source||"cache"}:null})),clearTimeout(ve),Zu.current===ve&&(Zu.current=null),Ud(td,()=>{uh(Vs=>IQ(Vs,L))});const PA=Array.isArray(da?.meta?.pendingActiveStatuses)?da.meta.pendingActiveStatuses:[];if(PA.length>0){const Vs={...Ft,status:PA};console.log("[PropertyLab] Mixed-status fast path: streaming active statuses in background",PA),PQ(I,Vs,{apiPost:($s,Ar,jn)=>dn($s,Ar,jn),scoreComp:$s=>eS(Ld,$s),mergeScoredActiveComps:$s=>{qe(Ar=>{const jn=new Set(Ar.properties.map(nn=>nn.snapshotId||nn.id)),_l=new Set(Ar.properties.map(nn=>YS(nn)).filter(Boolean)),Ln=[...Ar.properties];for(const nn of $s){const vl=nn.snapshotId||nn.id;if(vl&&jn.has(vl))continue;const Nl=YS(nn);Nl&&_l.has(Nl)||(jn.add(vl),Nl&&_l.add(Nl),Ln.push(nn))}const zo=Ln.length-Ar.properties.length;return console.log(`[PropertyLab] Active stream merged ${zo} new comps into state.properties`),{...Ar,properties:Ln}}),cu(Ar=>{const jn=new Set(Ar.map(Ln=>Ln.snapshotId||Ln.id)),_l=[...Ar];for(const Ln of $s){const zo=Ln.snapshotId||Ln.id;zo&&!jn.has(zo)&&(jn.add(zo),_l.push(Ln))}return _l})},setActiveStreamLoading:qs,log:console.log,warn:console.warn,isCurrentSearch:()=>Tc.current===I})}const f5=Si.current,g5=Dr.current,Yy=new Map,Gy=new Map;for(const Vs of ad){const $s=Vs.snapshotId||Vs.id;Vs.echoLocationScore&&Vs.echoLocationScore.score>=0&&(f5.has($s)||Yy.set($s,Vs.echoLocationScore),sn.current.add($s)),(Vs.conditionRating||Vs.qualityRating)&&(g5.has($s)||Gy.set($s,{condition:Vs.conditionRating,quality:Vs.qualityRating,confidence:.8}),Vs.mlsNumber&&rn.current.add(Vs.mlsNumber))}Yy.size>0&&(Ki(Vs=>{const $s=new Map(Vs);return Yy.forEach((Ar,jn)=>{$s.has(jn)||$s.set(jn,Ar)}),$s}),console.log("[PropertyLab] Pre-seeded ELS cache from search:",Yy.size,"scores")),Gy.size>0&&(kl(Vs=>{const $s=new Map(Vs);return Gy.forEach((Ar,jn)=>{$s.has(jn)||$s.set(jn,Ar)}),$s}),console.log("[PropertyLab] Pre-seeded AI cache from search:",Gy.size,"ratings")),console.log("[PropertyLab] Search complete:",{source:da.source,cacheKey:da.cacheKey,uniqueCount:da.uniqueCount,finalRadiusUsed:da.finalRadiusUsed,duplicatesRemoved:da.duplicatesRemoved});const Mf=36,OA=k.dateFilterField;if(er!==void 0&&er<Mf&&OA==="closed"&&!jb.current){mh.current=er,jb.current=!0,vy(!0);const Vs=new AbortController;Ju.current=Vs;const $s={...Ft,monthsBack:Mf},Ar=performance.now();console.log(`[PropertyLab:BgWiden] Scheduling background widen ${er}mo → ${Mf}mo`),(async()=>{try{const jn=await dn("/api/comps/search",$s,{throwOnSuccessFalse:!1,signal:Vs.signal});if(Vs.signal.aborted)return;if(!jn||jn.success===!1||!Array.isArray(jn.comps)&&!Array.isArray(jn.results)){console.warn("[PropertyLab:BgWiden] Soft-failure response — leaving coverage unchanged",{success:jn?.success,error:jn?.error});return}const Ln=(jn.comps||jn.results||[]).filter(Ur=>Ur.coordinates&&typeof Ur.coordinates.lat=="number"&&typeof Ur.coordinates.lng=="number"&&!isNaN(Ur.coordinates.lat)&&!isNaN(Ur.coordinates.lng)),zo=new Date;zo.setMonth(zo.getMonth()-Mf);const vl=Ln.filter(Ur=>
53{if(O0(Ur.status)||Ur.status==="PEND")return!0;const Vl=(OA==="contract"?Ur.contractDate:Ur.saleDate)||Ur.listDate;return Vl?new Date(Vl)>=zo:!1}).map(Ur=>({...Ur,similarityScore:eS(Ld,Ur)}));let Nl=0;qe(Ur=>{if(mh.current>=Mf)return Ur;const Vl=new Set;for(const ep of Ur.properties)Vl.add(ep.snapshotId||ep.id);const Ff=vl.filter(ep=>!Vl.has(ep.snapshotId||ep.id));return Nl=Ff.length,Ff.length===0?Ur:{...Ur,properties:[...Ur.properties,...Ff]}});const Md=new Map,Ul=new Map;for(const Ur of vl){const Vl=Ur.snapshotId||Ur.id;Ur.echoLocationScore&&Ur.echoLocationScore.score>=0&&(Md.set(Vl,Ur.echoLocationScore),sn.current.add(Vl)),(Ur.conditionRating||Ur.qualityRating)&&(Ul.set(Vl,{condition:Ur.conditionRating,quality:Ur.qualityRating,confidence:.8}),Ur.mlsNumber&&rn.current.add(Ur.mlsNumber))}Md.size>0&&Ki(Ur=>{const Vl=new Map(Ur);return Md.forEach((Ff,ep)=>{Vl.has(ep)||Vl.set(ep,Ff)}),Vl}),Ul.size>0&&kl(Ur=>{const Vl=new Map(Ur);return Ul.forEach((Ff,ep)=>{Vl.has(ep)||Vl.set(ep,Ff)}),Vl}),mh.current=Mf,eA.current={monthsBack:Mf,dateFilterField:OA};const Pb=performance.now()-Ar;console.log(`[PropertyLab:BgWiden] Complete: fetched=${vl.length}, merged=${Nl} new comps in ${Math.round(Pb)}ms (source=${jn?.source??"unknown"})`)}catch(jn){if(jn instanceof DOMException&&jn.name==="AbortError"||Vs.signal.aborted){console.log("[PropertyLab:BgWiden] Aborted (superseded by new search)");return}console.warn("[PropertyLab:BgWiden] Background widen failed (will fall back to on-demand expansion):",jn)}finally{Ju.current===Vs&&(Ju.current=null),jb.current=!1,vy(!1)}})()}}catch(aa){if(aa instanceof DOMException&&aa.name==="AbortError"||aa instanceof TypeError&&I.signal.aborted||aa instanceof Error&&aa.message?.includes("aborted")||I.signal.aborted){if(q){const As=Rf.current||"Property search";if(Ht>=50)console.warn(`[PropertyLab] Live PropMix leg timed out at ${te}ms — keeping ${Ht} cached comps on screen, banner suppressed`),Ud(td,()=>{qe(Aa=>Aa.isLoading?{...Aa,isLoading:!1}:Aa)});else{console.warn(`[PropertyLab] Search timed out after ${te}ms — surfacing failure UI`);const Aa=kj(null,As,{timedOut:!0});Ud(td,()=>{uh(Aa),qe(ns=>({...ns,isLoading:!1,error:Aa.description,dataSource:null})),Ve({title:Aa.title,description:Aa.description,variant:"destructive"})})}}else{const As=Tc.current!==I;console.log(As?"[PropertyLab] Search request aborted (superseded by newer search)":"[PropertyLab] Search request aborted (unmount or manual cancel)")}return}if((aa instanceof qo&&(aa.status===502||aa.status===503)||aa instanceof TypeError&&(aa.message?.includes("Failed to fetch")||aa.message?.includes("NetworkError")||aa.message?.includes("Load failed")))&&!va)return va=!0,console.log("[PropertyLab] Transient error detected, will retry search in 1s...",aa),await new Promise(As=>setTimeout(As,1e3)),I.signal.aborted?void 0:Cs();const da=Rf.current||"Property search",es=aa instanceof Error?aa.message:String(aa),Js=aa instanceof qo&&aa.isAuthError,er=Js?null:kj(aa,da),ga=Js?"Session expired — please sign in again.":er.description;console.error(`[PropertyLab] ${da} failed:`,aa),!Js&&er&&Ud(td,()=>{uh(er)}),Ud(td,()=>{qe(As=>({...As,isLoading:!1,error:ga,dataSource:null}))});try{fetch("/api/client-errors",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:`[PropertyLab] ${da} failed: ${es}`,stack:aa instanceof Error?aa.stack:void 0,metadata:{orderId:r||null,step:"PropertyLab",lastAction:da,boundaryCount:js.length,shapeCount:Ma.circles.length+Ma.polygons.length,hasSubject:!!s,status:aa instanceof qo?aa.status:void 0,url:typeof window<"u"?window.location.href:"",timestamp:new Date().toISOString()}}),keepalive:!0}).catch(()=>{})}catch{}Js?Ud(td,()=>{Ve({title:"Session Expired",description:"Please sign in again to continue.",variant:"destructive"})}):er&&Ud(td,()=>{Ve({title:er.title,description:er.description,variant:"destructive"})})}};try{await Cs()}finally{clearTimeout(ee),clearTimeout(ie),clearTimeout(ve),wf.current===ee&&(wf.current=null),Ef.current===ie&&(Ef.current=null),Zu.current===ve&&(Zu.current=null),I.signal.aborted&&!q&&Tc.current!==I||(Qn.current=!1,qe(Ft=>Ft.isLoading?{...Ft,isLoading:!1}:Ft)),yo.current&&(clearTimeout(yo.current),yo.current=null),Wc(null)}};o.useEffect(()=>{Nr.current=nR}),o.useEffect(()=>{if(ou.current&&Nr.current){if(ei.current){console.log("[PropertyLab] Skipping boundary search - locked data already restored"),ou.current=!1;return}console.log("[PropertyLab] Executing search triggered by boundary addition"),ou.current=!1,setTimeout(()=>{ei.current||!Qn.current&&Nr.current&&Nr.current()},50)}},[js]);const iR=o.useRef(!1);o.useEffect(()=>{if(ei.current){En.current=!1;return}
53!iR.current&&En.current&&Nr.current&&(iR.current=!0,console.log("[PropertyLab] handleSearchRef now set, executing pending search"),En.current=!1,setTimeout(()=>{ei.current||!Qn.current&&Nr.current&&Nr.current()},100))},[]);const YF=async()=>{if(!(!as||!Fn||re.selectedComps.length===0)){qm(!0);try{const g={gla:as.gla||0,condition:as.condition||"C3",quality:as.quality||"Q3",bedrooms:as.bedrooms||3,bathrooms:as.bathrooms||2,basement:as.basement||"None",garage:as.garage||0,lotSize:as.lotSize||0,yearBuilt:as.yearBuilt||1990,elsScore:Fn?.verifiedSubject?.elsScore||50,saleDate:new Date().toISOString().split("T")[0]},I=re.selectedComps.map(te=>({id:te.snapshotId||te.id,address:te.address||"",salePrice:te.price||te.salePrice||te.closePrice||0,saleDate:te.saleDate||"",gla:te.gla||te.livingArea||0,condition:te.condition||"C3",quality:te.quality||"Q3",bedrooms:te.beds||te.bedrooms||3,bathrooms:te.baths||te.bathrooms||2,basement:te.basement||"None",garage:te.garageSpaces||0,lotSize:te.lotSize||te.lotSizeSf||0,yearBuilt:te.yearBuilt||1990,elsScore:te.elsScore||50})),k=Fn.adjustmentRates,Y=(Fr&&Ad.length>0?Ad:Tr&&fl.length>0?fl:[]).map(te=>({salePrice:te.salePrice||0,gla:te.gla||0,bedrooms:te.bedrooms||3,bathrooms:te.bathrooms||2})),K=await fetch("/api/avm/derive-adjustments",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subject:g,gridComps:I,rates:k,marketPool:Y})});if(K.ok){const te=await K.json();te.success&&Xd(te.data)}}catch(g){console.error("[PropertyLab] Failed to fetch advisor data:",g)}finally{qm(!1)}}},GF=async()=>{if(!as||!Tr){Ve({title:"Prerequisites not met",description:"Verify subject data and lock market boundaries before running AVM.",variant:"destructive"});return}gm(!0),hl("comps");try{const g=new Map;re.properties.forEach(K=>{const te=K.snapshotId||K.id;g.set(te,K)}),Kr.forEach(K=>{const te=K.snapshotId||K.id;g.has(te)||g.set(te,K)});const I=new Set([...to||[],...Gi||[]]);let k=Array.from(g.values()).filter(K=>{const te=K.snapshotId||K.id;return I.has(te)||I.has(K.id)}).map(K=>({id:K.snapshotId||K.id,address:K.address||K.fullAddress,salePrice:K.price||K.listPrice||0,saleDate:K.saleDate,gla:K.gla||0,beds:K.beds||0,baths:K.baths||0,yearBuilt:K.yearBuilt||0,lotSizeAcres:K.lotSize?K.lotSize>100?K.lotSize/43560:K.lotSize:0,lat:K.coordinates?.lat,lng:K.coordinates?.lng,photos:K.photos||[],mlsNumber:K.mlsNumber||K.snapshotId||K.id}));if(k.length===0&&qt&&qt.length>0){console.log("[PropertyLab] No locked IDs matched, falling back to drawnAreaPropertyIds:",qt.length);const K=new Set(qt);k=Array.from(g.values()).filter(te=>{const q=te.snapshotId||te.id;return K.has(q)}).map(te=>({id:te.snapshotId||te.id,address:te.address||te.fullAddress,salePrice:te.price||te.listPrice||0,saleDate:te.saleDate,gla:te.gla||0,beds:te.beds||0,baths:te.baths||0,yearBuilt:te.yearBuilt||0,lotSizeAcres:te.lotSize?te.lotSize>100?te.lotSize/43560:te.lotSize:0,lat:te.coordinates?.lat,lng:te.coordinates?.lng,photos:te.photos||[],mlsNumber:te.mlsNumber||te.snapshotId||te.id}))}console.log("[PropertyLab] AVM propertyDataForAvm count:",k.length,"from",g.size,"total available");const L={...as,listPrice:as.listPrice??ht?.listPrice??void 0,listingStatus:as.listingStatus??(typeof ht?.status=="string"?ht.status:ht?.status?.Type)??void 0,listDate:as.listDate??ht?.listDate??void 0},Y=await dn("/api/avm/analyze",{subject:L,marketBoundary:Ma,marketLocked:Tr,subMarketLocked:Fr,marketPropertyIds:to,subMarketPropertyIds:Gi,propertyData:k,boostPriorities:T?.priorities||[]});Y.results&&(Zc(Y.results),no(new Set(Y.results.rankedComps.slice(0,5).map(K=>K.id))),xd({column:"avmScore",direction:"desc"}),Ve({title:"AVM Analysis Complete",description:`Found ${Y.results.rankedComps.length} comparable sales with adjustments calculated.`}))}catch(g){console.error("[PropertyLab] AVM analysis failed:",g),Ve({title:"AVM Analysis Failed",description:g instanceof Error?g.message:"Could not complete AVM analysis",variant:"destructive"})}finally{gm(!1)}};io.current.runAVM=GF;const oR=async()=>{if(C&&Us!=="rental"){if(Cp.current)return;Cp.current=!0,Ip(!0);try{if(r){const Se=await $Z(ti.current,()=>Ho(`/api/uad36/comparables/${encodeURIComponent(r)}`,{cache:"no-store"})),Qe=zS(Se),Nt=n0(Vj(Qe),[...Qc.current,...Dl.current]);Lr.current=Nt,Pi(Nt),Xs({gridCount:Qe.length,selectedCount:typeof Se?.selectedCount=="number"?Se.selectedCount:Qe.filter(Ct=>Ct.compSnapshotId).length,available:typeof Se?.capacity?.available=="number"?Se.capacity.available:Math.max(0,24-Qe.length)})}}catch(Se){console.error("[PropertyLab] Failed to prepare ordered comparables for grid:",Se),Ve({title:"Grid is still syncing",description:"Please try Next again after the selected comparables finish saving.",variant:"destructive"});return}finally{Cp.current=!1,Ip(!1)}}let g=[...re.selectedComps];if(Fn&&wn.size>0){const Se=new Set(re.selectedComps.map(Ct=>Ct.id)),Qe=[],Nt=re.properties?.length>0?re.properties:Xr;for(const Ct of Fn.rankedComps){if(!wn.has(Ct.id)||Se.has(Ct.id))continue;const va=Nt.find(Ht=>Ht.id===Ct.id||Ht.snapshotId===Ct.id||Ht.id===Ct.snapshotId);if(va){const Ht={...va,adjustments:{...Ct.adjustments,normalizedCondition:Ct.normalizedCondition,normalizedQuality:Ct.normalizedQuality,normalizedConditionSource:Ct.normalizedConditionSource,normalizedQualitySource:Ct.normalizedQualitySource},adjustedPrice:Ct.adjustedPrice};Qe.push(Ht)}else console.warn("[PropertyLab] AVM comp not found in properties, skipping:",Ct.id)}g=[...g,...Qe],console.log("[PropertyLab] Added",Qe.length,"AVM comps to selection"),qe(Ct=>({...Ct,selectedComps:g}))}const I=g.map(Se=>HH(Se));eo(I);const k=Je,L=ht,Y=t,K=jm(a||""),te=K?.city||"",q=K?.state||i||"",ie=k?.ph
53otos?.length?k.photos:L?.photos?.length?L.photos:ni,ee=v0(L);console.log("[PropertyLab] Proceeding to cleanup with subject data:",{subjectAddress:a,parsedAddr:K,parsedCity:te,parsedState:q,details:k,listing:L,photos:ie,selectedCompsCount:g.length,manualComps:re.selectedComps.length,avmComps:wn.size});const we={id:"subject",address:a||"Unknown Address",city:te,state:q,zipCode:l||K?.zip||"",lat:s?.lat,lng:s?.lng,photoUrl:ie[0]||null,photos:ie,status:OS(ee),isSubject:!0,elsScore:typeof _n=="number"?_n:null,elsTier:typeof _n=="number"?_n>=67?"Beneficial":_n>=34?"Neutral":"Adverse":null,fields:{salePrice:{value:L?.soldPrice||k?.lastSalePrice||Y?.salePrice?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},dateOfSale:{value:(()=>{const Se=L?.soldDate||k?.lastSaleDate||Y?.saleDate?.value||null,Qe=L?.contractDate||Y?.contractDate?.value||null;return Se?Mm(Se,Qe):null})(),source:"MLS",hasConflict:!1,isVerified:!0},gla:{value:k?.squareFeet||L?.squareFeet||Y?.gla?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},yearBuilt:{value:(()=>{const Se=k?.yearBuilt||L?.yearBuilt||Y?.yearBuilt?.value;return Se?Number(Se):null})(),source:"MLS",hasConflict:!1,isVerified:!0},aboveGrade:{value:(()=>{const Se=k?.bedrooms||L?.bedrooms||Y?.beds?.value,Qe=k?.bathrooms||L?.bathrooms||Y?.baths?.value,Nt=k?.fullBathrooms??L?.fullBathrooms??Y?.fullBaths?.value,Ct=k?.halfBathrooms??L?.halfBathrooms??Y?.halfBaths?.value,va=Uh(Nt!=null?Number(Nt):null,Ct!=null?Number(Ct):null,Qe!=null?Number(Qe):null),Ht=Qe!=null?Number(Qe):Nt!=null?Number(Nt)+(Ct!=null?Number(Ct)*.5:0):0;return Se!=null?`${Number(Se)+Math.ceil(Ht)+2}|${Se}|${va}`:null})(),source:"MLS",hasConflict:!1,isVerified:!0},...DS(L,k,Y),...Qb(Y),site:{value:k?.lotSize||L?.lotSize||Y?.lotSize?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},view:{value:Y?.view?.value||null,source:"MLS",hasConflict:!1,isVerified:!1},design:{value:k?.style||L?.style||Y?.style?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},strBedrooms:{value:k?.bedrooms||L?.bedrooms||Y?.beds?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},strBathrooms:{value:k?.bathrooms||L?.bathrooms||Y?.baths?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},strGLA:{value:(()=>{const Se=k?.squareFeet||L?.squareFeet||Y?.gla?.value;return Se?`${Se} sf`:null})(),source:"MLS",hasConflict:!1,isVerified:!0},strParking:{value:k?.garage||L?.garage||Y?.garage?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},strLocation:{value:"N;Res",source:"AI",hasConflict:!1,isVerified:!1},strNightlyRate:{value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},strOccupancy:{value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},strAnnualNights:{value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},strGrossIncome:{value:"N/A",source:"MLS",hasConflict:!1,isVerified:!0},strDataSource:{value:"MLS / Public Record",source:"MLS",hasConflict:!1,isVerified:!0}}},ve=Mb(Kb(we,as),he);console.log("[PropertyLab] Created subjectGridProp with verified subject overlay:",{condition:ve.fields.condition?.value,quality:ve.fields.quality?.value,gla:ve.fields.gla?.value,aboveGrade:ve.fields.aboveGrade?.value,site:ve.fields.site?.value,verifiedSubjectPresent:!!as}),$c(ve),oi(!0),f?.()},HF=async(g,I,k,L,Y)=>{eo(K=>K.map(te=>te.id===g?WH(te,I,k,L,Y):te));try{await dn("/api/field-lineage/verify",{entityType:"comp",entityId:g,fieldName:I,value:k,source:L,note:Y})}catch(K){K instanceof qo&&K.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to persist field verification:",K)}},WF=()=>{v?.(re.selectedComps);const g=re.selectedComps.map(I=>CT(I));console.log("[PropertyLab] Passing cleanedComps to wizard:",g.length),S?.(g),f?.()},[KF,lR]=o.useState(!1),[QF,cR]=o.useState(!1),gA=async()=>{if(Tr){if(Zs==="market"&&Nm(),Zl(!1),sm(null),$r(null),Ao(null),im([]),Uo(null),om(null),nu(null),xc(null),Uu(null),r)try{await dn("/api/market-session/unlock",{assignmentId:r,type:"market"}),uu.current?.()}catch(g){console.error("[PropertyLab] Failed to persist market unlock:",g)}Ve({title:"Market Unlocked",description:"You can now modify the market boundaries"})}else{const g=Xr.length,I=Xr.map(te=>te.snapshotId||te.id).filter(te=>!!te&&te.trim().length>0);console.log("[PropertyLab] Locking market with",I.length,"result IDs");const k=Xr.map(te=>{const q=te.address?.trim()||"",ie=te.city?.trim()||"";let ee="Unknown";q&&ie?ee=`${q}, ${ie}`:q?ee=q:ie&&(ee=ie);const we=te.mlsData,ve=we?.ListingContractDate||we?.PurchaseContractDate||we?.ContractDate||null;return{id:te.snapshotId||te.id,address:ee,contractDate:ve,closeDate:te.saleDate||null,saleDate:te.saleDate||null,salePrice:te.price||0,status:te.status||"CLSD"}}),L=gw(Xr),Y=()=>{sm(Ab),$r(g),Ao(I),im(k),_o(Xr),Uo({...re.filters}),om([...js]),nu(re.marketDefinition?.radiusMiles??1),xc(nI(Ma)),Uu(L),Zl(!0)};if(r||Y(),r){lR(!0);try{const te=Xr.map(q=>({id:q.id,snapshotId:r0(q),mlsNumber:q.mlsNumber||q.mlsData?.mlsNumber||q.mlsData?.MlsListingNumber||null,mlsBoard:i0({mlsBoard:q.mlsBoard,mlsData:q.mlsData})||null,address:q.address||"",city:q.city||"",state:q.state||"",zip:q.zip||"",price:q.price||0,listPrice:q.listPrice,beds:q.beds,baths:q.baths,fullBathrooms:q.fullBathrooms??null,halfBathrooms:q.halfBathrooms??null,sqft:q.sqft,sqftPR:q.sqftPR||q.prLivingArea||null,lotSqft:q.lotSqft,lotSqftPR:q.lotSqftPR||null,yearBuilt:q.yearBuilt,yearBuiltPR:q.yearBuiltPR||null,status:q.status||"CLSD",saleDate:q.saleDate,listDate:q.listDate,dom:q.dom||0,distance:q.distance,style:q.style,btDesignStyle:q.btDesignStyle??null,btStyleConfidence:q.btStyleConfidence??null,stories:q.stories,garageSpaces:q.garageSpaces,coordinates:q.coordinates,photos:q.photos||[],photoUrl:q.photoUrl,photoCount:q.photoCount||0,photosStatus:q.photosStatus,propertyType:q.propertyType||"SFR",similarityScore:q.similarityScore,matchScore:q.matchScore,matchBreakdown:q.matchBreakdown,avmScore:q.avmScore,avmAdjustedPrice:q.avmAdjustedPrice,isSelected:q.isSelected,pricePerSqft:q.pricePerSqft,propMixCachedAt:q.propMixCachedAt,echoLocationScore:q.echoLocationScore,conditionRating:q.conditionRating,conditionSource:q.conditionSource,qualityRating:q.qualityRating,qualitySource:q.qualitySource,distressedYN:q.distressedYN??null,distressType:q.distressType??null,specialListingConditions:q.specialListingConditions??null,isStrProperty:q.isStrProperty,strListingName:q.strListingName,strNightlyRate:q.strNightlyRate,strAverageDailyRate:q.strAverageDailyRate,strOccupancyRate:q.strOccupancyRate,strGrossRevenue12mo:q.strGrossRevenue12mo,strRating:q.strRating,strReviewCount:q.strReviewCount,strMaxGuests:q.strMaxGuests,strProvider:q.strProvider,strListingUrl:q.strListingUrl}));await pn(dn("/api/market-session/lock",{assignmentId:r,type:"market",stats:{...Ab,monthlyHistory:p1(vm)},filters:re.filters,lookbackMonths:re.filters.monthsBack??re.filters.dateRangePreset??12,radiusMiles:re.marketDefinition?.radiusMiles,propertyCount:g,resultIds:I,sales
53Data:k,propertyCards:te,boundaries:js,shapes:m1(Ma)})),console.log("[PropertyLab] Market lock persisted with",te.length,"full property cards"),uu.current?.(),Y();try{const q=Ma.circles[0],ie=Ma.polygons[0]||null,ee=await fetch(`/api/v2/orders/${r}`,{method:"PATCH",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({addMarketState:{stateType:"market",filters:re.filters,boundaries:js,polygon:ie,center:q?.center||s,radiusMiles:re.marketDefinition?.radiusMiles,salesCount:g,marketStats:Ab,selectedCompIds:null}})}),we=ee.ok?await ee.json():null;we&&(oT(r),Vo(ve=>{const Se=ve.filter(Qe=>Qe.stateType!=="market");return[we,...Se]}),console.log("[PropertyLab] Market state auto-saved to order history"))}catch(q){console.error("[PropertyLab] Market state history auto-save failed (lock itself persisted):",q)}}catch(te){te instanceof qo&&te.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):(console.error("[PropertyLab] Failed to persist market lock:",te),Ve({title:"Lock Failed",description:te instanceof Error?te.message:"Could not save the locked market. Please try again.",variant:"destructive"}));return}finally{lR(!1)}}Ve({title:"Market Locked",description:`Market area locked with ${g} sales`});const K=!su&&(el.boundaries||el.description||el.marketConditions);if(a&&!K){vn(!0);try{const te=Ma.polygons[0]||null,q=await dn("/api/neighborhood/generate",{address:a,city:BN,county:Je?.county,state:i,marketStats:Ab,radiusMiles:re.marketDefinition?.radiusMiles,salesCount:g,appliedBoundaries:js,polygon:te},{throwOnSuccessFalse:!1});if(q&&q.success&&(Jn({boundaries:q.boundaries||"",description:q.description||"",marketConditions:q.marketConditions||""}),Ei(!0),b?.(!0),console.log("[PropertyLab] AI-generated neighborhood info on market lock"),r))try{await dn("/api/market-session/neighborhood-info",{assignmentId:r,neighborhoodInfo:{boundaries:q.boundaries||"",description:q.description||"",marketConditions:q.marketConditions||""}},{throwOnSuccessFalse:!1}),console.log("[PropertyLab] Persisted neighborhoodInfo to property_lab_locks")}catch(ie){console.error("[PropertyLab] Failed to persist neighborhoodInfo:",ie)}}catch(te){console.error("[PropertyLab] Failed to generate neighborhood info:",te)}finally{vn(!1)}}else K&&console.log("[PropertyLab] Preserving user-edited neighborhood info on market lock")}},xA=async()=>{if(Fr){if(Zs==="submarket"&&Nm(),qc(!1),nm(null),tl(null),li(null),gl([]),Jl([]),Hc(null),Sp(null),vp(null),ao(null),yp(null),r)try{await dn("/api/market-session/unlock",{assignmentId:r,type:"submarket"}),uu.current?.()}catch(g){console.error("[PropertyLab] Failed to persist sub-market unlock:",g)}Ve({title:"Sub-Market Unlocked",description:"You can now modify the filters"})}else{const g=Xr.map(ie=>ie.snapshotId||ie.id).filter(ie=>!!ie&&ie.trim().length>0),I=Xr.length;console.log("[PropertyLab] Locking sub-market with",g.length,"result IDs (filtered subset)");const k=Xr.map(ie=>{const ee=ie.address?.trim()||"",we=ie.city?.trim()||"";let ve="Unknown";ee&&we?ve=`${ee}, ${we}`:ee?ve=ee:we&&(ve=we);const Se=ie.mlsData,Qe=Se?.ListingContractDate||Se?.PurchaseContractDate||Se?.ContractDate||null;return{id:ie.snapshotId||ie.id,address:ve,contractDate:Qe,closeDate:ie.saleDate||null,saleDate:ie.saleDate||null,salePrice:ie.price||0,status:ie.status||"CLSD"}}),L=Xr.map(ie=>({id:ie.snapshotId||ie.id,snapshotId:ie.snapshotId||ie.id,address:ie.address||"",fullAddress:`${ie.address||""}, ${ie.city||""}, ${ie.state||""} ${ie.zip||""}`.trim(),city:ie.city||"",state:ie.state||"",zip:ie.zip||"",price:ie.price,listPrice:ie.listPrice,beds:ie.beds,baths:ie.baths,sqft:ie.sqft,gla:ie.sqft||0,lotSqft:ie.lotSqft,yearBuilt:ie.yearBuilt,status:ie.status||"CLSD",saleDate:ie.saleDate,listDate:ie.listDate,contractDate:void 0,dom:ie.dom||0,distance:ie.distance??0,propertyType:ie.propertyType||"SFR",coordinates:ie.coordinates||{lat:0,lng:0},source:"cache",photos:ie.photos||[],selectionState:"none"})),Y=u1(L),K=gw(Xr),te=()=>{nm(Y),tl(I),li(g),gl(k),Jl(Xr),Hc({...re.filters}),Sp([...js]),vp(re.marketDefinition?.radiusMiles??1),ao(nI(Ma)),yp(K),qc(!0)};if(r||te(),r){cR(!0);try{const ie=Xr.map(ee=>({id:ee.id,snapshotId:r0(ee),mlsNumber:ee.mlsNumber||ee.mlsData?.mlsNumber||ee.mlsData?.MlsListingNumber||null,mlsBoard:i0({mlsBoard:ee.mlsBoard,mlsData:ee.mlsData})||null,address:ee.address||"",city:ee.city||"",state:ee.state||"",zip:ee.zip||"",price:ee.price||0,listPrice:ee.listPrice,beds:ee.beds,baths:ee.baths,fullBathrooms:ee.fullBathrooms??null,halfBathrooms:ee.halfBathrooms??null,sqft:ee.sqft,sqftPR:ee.sqftPR||ee.prLivingArea||null,lotSqft:ee.lotSqft,lotSqftPR:ee.lotSqftPR||null,yearBuilt:ee.yearBuilt,yearBuiltPR:ee.yearBuiltPR||null,status:ee.status||"CLSD",saleDate:ee.saleDate,listDate:ee.listDate,dom:ee.dom||0,distance:ee.distance,style:ee.style,btDesignStyle:ee.btDesignStyle??null,btStyleConfidence:ee.btStyleConfidence??null,stories:ee.stories,garageSpaces:ee.garageSpaces,coordinates:ee.coordinates,photos:ee.photos||[],photoUrl:ee.photoUrl,photoCount:ee.photoCount||0,propertyType:ee.propertyType||"SFR",similarityScore:ee.similarityScore,matchScore:ee.matchScore,pricePerSqft:ee.pricePerSqft,echoLocationScore:ee.echoLocationScore,conditionRating:ee.conditionRating,conditionSource:ee.conditionSource,qualityRating:ee.qualityRating,qualitySource:ee.qualitySource,distressedYN:ee.distressedYN??null,distressType:ee.distressType??null,specialListingConditions:ee.specialListingConditions??null}));await pn(dn("/api/market-session/lock",{assignmentId:r,type:"submarket",stats:{...Y,monthlyHistory:p1(L)},filters:re.filters,lookbackMonths:re.filters.monthsBack??re.filters.dateRangePreset??12,radiusMiles:re.marketDefinition?.radiusMiles,propertyCount:I,resultIds:g,salesData:k,boundaries:js,propertyCards:ie,shapes:m1(Ma)}
53)),console.log("[PropertyLab] Sub-market lock persisted with",k.length,"sales and",ie.length,"property cards"),uu.current?.(),te();try{const ee=Ma.circles[0],we=Ma.polygons[0]||null,ve=await fetch(`/api/v2/orders/${r}`,{method:"PATCH",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({addMarketState:{stateType:"sub-market",filters:re.filters,boundaries:js,polygon:we,center:ee?.center||s,radiusMiles:re.marketDefinition?.radiusMiles,salesCount:I,marketStats:Y,selectedCompIds:g}})}),Se=ve.ok?await ve.json():null;Se&&(oT(r),Vo(Qe=>{const Nt=Qe.filter(Ct=>Ct.stateType!=="sub-market");return[Se,...Nt]}),console.log("[PropertyLab] Sub-market state auto-saved to order history"))}catch(ee){console.error("[PropertyLab] Sub-market state history auto-save failed (lock itself persisted):",ee)}}catch(ie){ie instanceof qo&&ie.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):(console.error("[PropertyLab] Failed to persist sub-market lock:",ie),Ve({title:"Sub-Market Lock Failed",description:ie instanceof Error?ie.message:"Could not save the locked sub-market. Please try again.",variant:"destructive"}));return}finally{cR(!1)}}Ve({title:"Sub-Market Locked",description:`Sub-market locked with ${I} comparable sales`});const q=!su&&(el.boundaries||el.description||el.marketConditions);if(a&&!q){vn(!0);try{const ie=Ma.polygons[0]||null,ee=await dn("/api/neighborhood/generate",{address:a,city:BN,county:Je?.county,state:i,marketStats:Y,radiusMiles:re.marketDefinition?.radiusMiles,salesCount:I,appliedBoundaries:js,polygon:ie},{throwOnSuccessFalse:!1});if(ee&&ee.success&&(Jn({boundaries:ee.boundaries||"",description:ee.description||"",marketConditions:ee.marketConditions||""}),Ei(!0),b?.(!0),console.log("[PropertyLab] AI-generated neighborhood info on sub-market lock"),r))try{await dn("/api/market-session/neighborhood-info",{assignmentId:r,neighborhoodInfo:{boundaries:ee.boundaries||"",description:ee.description||"",marketConditions:ee.marketConditions||""}},{throwOnSuccessFalse:!1}),console.log("[PropertyLab] Persisted neighborhoodInfo to property_lab_locks")}catch(we){console.error("[PropertyLab] Failed to persist neighborhoodInfo:",we)}}catch(ie){console.error("[PropertyLab] Failed to generate neighborhood info on sub-market lock:",ie)}finally{vn(!1)}}else q&&console.log("[PropertyLab] Preserving user-edited neighborhood info on sub-market lock")}},_y=o.useCallback((g,I)=>{$u.current=!0,Fi.current=I??lK({filters:re.filters,boundaries:js,radius:re.marketDefinition?.radiusMiles??1,shapes:Ma}),g==="market"?(Xn(f1(lm)),xl&&bo(xl),Br!=null&&qe(k=>({...k,marketDefinition:{...k.marketDefinition,radiusMiles:Br,totalProperties:k.marketDefinition?.totalProperties||0}})),jd&&qe(k=>({...k,filters:{...jd}}))):(Xn(f1(Np)),Hi&&bo(Hi),iu!=null&&qe(k=>({...k,marketDefinition:{...k.marketDefinition,radiusMiles:iu,totalProperties:k.marketDefinition?.totalProperties||0}})),cm&&qe(k=>({...k,filters:{...cm}}))),al(g),Ve({title:g==="market"?"Viewing Locked Market":"Viewing Locked Sub-Market",description:"Showing filters and boundaries from lock time"}),setTimeout(()=>{$u.current=!1},500)},[re.filters,js,Ma,re.marketDefinition?.radiusMiles,xl,Br,jd,lm,Hi,iu,cm,Np,Ve]),Nm=o.useCallback(()=>{if(!Fi.current){al(null);return}const g=Fi.current;qe(I=>({...I,filters:{...g.filters},marketDefinition:{...I.marketDefinition,radiusMiles:g.radius,totalProperties:I.marketDefinition?.totalProperties||0}})),bo(g.boundaries),Xn(g.shapes),Fi.current=null,al(null)},[]),ZF=o.useCallback(()=>{if(!Tr)gA();else if(Zs==="market")Nm();else{const g=Fi.current;Zs&&al(null),_y("market",g??void 0)}},[Tr,Zs,_y,gA]),JF=o.useCallback(()=>{if(!Fr)xA();else if(Zs==="submarket")Nm();else{const g=Fi.current;Zs&&al(null),_y("submarket",g??void 0)}},[Fr,Zs,_y,xA]),XF=o.useCallback(async()=>{if(Zs&&Nm(),Zl(!1),sm(null),$r(null),Ao(null),im([]),Uo(null),om(null),nu(null),xc(null),Uu(null),r)try{await dn("/api/market-session/unlock",{assignmentId:r,type:"market"}),uu.current?.()}catch(g){console.error("[PropertyLab] Failed to persist market unlock:",g)}
53Ve({title:"Market Unlocked",description:"You can now modify the market boundaries"})},[r,Zs,Nm,Ve]),e5=o.useCallback(async()=>{if(Zs&&Nm(),qc(!1),nm(null),tl(null),li(null),gl([]),Jl([]),Hc(null),Sp(null),vp(null),ao(null),yp(null),r)try{await dn("/api/market-session/unlock",{assignmentId:r,type:"submarket"}),uu.current?.()}catch(g){console.error("[PropertyLab] Failed to persist sub-market unlock:",g)}Ve({title:"Sub-Market Unlocked",description:"You can now modify the filters"})},[r,Zs,Nm,Ve]),Uy=re.selectedComps.length,dR=C&&Us!=="rental"?ar?.selectedCount??Uy:Uy;o.useEffect(()=>{Uy===0&&go&&Zd(!1)},[Uy,go]);const uR=Tr&&Gc!==null?Gc:Xr.length,Jg=re.isLoading||Wt||wF||U&&yu&&Da==="rentals",pR=45e3,mR=o.useRef(null),Am=o.useRef(null),Vy=o.useRef(!1),[hR,bA]=o.useState(!1),fR=o.useRef(!1),yA=o.useRef(null),SA=o.useRef(null),vA=o.useRef(null),NA=o.useRef(!1),AA=o.useRef(!1),jA=o.useRef(!1),gR=o.useRef(!1),xR=o.useRef(!1),bR=o.useRef(!1);o.useEffect(()=>{const g=Date.now(),I=U&&yu&&Da==="rentals";re.isLoading&&!NA.current?yA.current=g:!re.isLoading&&NA.current&&(yA.current=null),Wt&&!AA.current?(SA.current=g,XN(!1)):!Wt&&AA.current&&(SA.current=null,XN(!1)),I&&!jA.current?vA.current=g:!I&&jA.current&&(vA.current=null),NA.current=re.isLoading,AA.current=Wt,jA.current=I,gR.current=re.isLoading,xR.current=Wt,bR.current=I;const k=fR.current;Jg&&!k?(mR.current=g,Vy.current=!1,bA(!1),console.log("[PropertyLab] refresh in-flight: true",{stateIsLoading:re.isLoading,geometrySearchInFlight:Wt,strAggregatorLoading:I}),Am.current&&clearTimeout(Am.current),Am.current=setTimeout(()=>{if(!Vy.current){Vy.current=!0;const L=Date.now(),Y=K=>K===null?null:L-K;console.warn(`[PropertyLab] refresh watchdog tripped after ${pR}ms — force-clearing stuck in-flight flags. Likely an upstream stream (active-stream poll, STR aggregator, geometry search) failed to mark itself done.`,{stateIsLoading:{value:gR.current,elapsedMsSinceFlagRose:Y(yA.current)},geometrySearchInFlight:{value:xR.current,elapsedMsSinceFlagRose:Y(SA.current)},strAggregatorLoading:{value:bR.current,elapsedMsSinceFlagRose:Y(vA.current)}})}bA(!0),IA.current.length>0&&(qe(L=>L?.isLoading?{...L,isLoading:!1}:L),ts(!1),Wg(!1))},pR)):!Jg&&k&&(Am.current&&(clearTimeout(Am.current),Am.current=null),mR.current=null,Vy.current=!1,bA(!1),console.log("[PropertyLab] refresh in-flight: false")),fR.current=Jg},[Jg,re.isLoading,Wt,U,yu,Da]),o.useEffect(()=>()=>{Am.current&&(clearTimeout(Am.current),Am.current=null)},[]);const $y=Jg,[By,yR]=o.useState(null),[SR,TA]=o.useState(!1),kd=o.useRef(null);o.useEffect(()=>{if($y){kd.current&&(clearTimeout(kd.current),kd.current=null),TA(!1);return}return kd.current&&clearTimeout(kd.current),TA(!1),kd.current=setTimeout(()=>{yR(Xr.length),TA(!0),kd.current=null},500),()=>{kd.current&&(clearTimeout(kd.current),kd.current=null)}},[$y,Xr.length]),o.useEffect(()=>()=>{kd.current&&(clearTimeout(kd.current),kd.current=null)},[]);const hh=o.useRef(null);o.useEffect(()=>{const g=Tr||Fr||Zs!==null;if(hh.current&&(clearTimeout(hh.current),hh.current=null),!!TQ({lockedViewActive:g,stableHeaderCount:By,visibleRowCount:Xr.length}))return hh.current=setTimeout(()=>{hh.current=null,console.log(`[PropertyLab] locked-view count decay: snapshot ${By} → ${Xr.length}`),yR(Xr.length)},jQ),()=>{hh.current&&(clearTimeout(hh.current),hh.current=null)}},[Tr,Fr,Zs,By,Xr.length]);const t5=AQ({visibleRowCount:Xr.length,stableHeaderCount:By,isCountRefreshInFlight:$y,refreshWatchdogTripped:hR,reviewingLock:Zs!==null,settleWindowActive:$y||!SR}),vR=Jg&&!hR,NR=C&&Us!=="rental"&&(vR||!SR||jp||re.isLoading||Wt||Tp);Ed.current=!NR;const AR=Fr&&Mi!==null?Mi:Xr.length,wp=o.useCallback(g=>g?IA.current.findIndex(I=>T0(I,g)):-1,[]),IA=o.useRef([]),Nu=o.useMemo(()=>{let g=Xr;const I=zt?.trim().toLowerCase();return I&&(g=g.filter(k=>k.address?.toLowerCase().includes(I)||k.mlsNumber?.toLowerCase().includes(I)||k.city?.toLowerCase().includes(I)||k.zipCode?.includes(I))),g},[Xr,zt]);IA.current=Nu;const a5=o.useMemo(()=>N9(Xr,js,qt),[Xr,js,qt]),CA=o.useCallback(g=>{Zs&&(Fi.current=null,al(null));const I=Y=>Y?.coordinates?(Y.coordinates[0]||[]).slice(0,3).map(q=>{const ie=Array.isArray(q)&&typeof q[0]=="number"?q[0]:0,ee=Array.isArray(q)&&typeof q[1]=="number"?q[1]:0;return`${ie.toFixed(4)},${ee.toFixed(4)}`}).join("|"):"",k=I(g.polygon);if(js.some(Y=>Y.id===g.id&&g.id?!0:Y.name!==g.name||Y.type!==g.type?!1:Y.polygon&&g.polygon?I(Y.polygon)===k:Y.radiu
53sMiles&&g.radiusMiles?Y.radiusMiles===g.radiusMiles:!0)){Ve({title:"Boundary Already Added",description:`${g.name} is already in your market area`,variant:"default"});return}bo(Y=>[...Y,g]),g.radiusMiles&&(qe(Y=>({...Y,marketDefinition:{...Y.marketDefinition,radiusMiles:g.radiusMiles,totalProperties:Y.marketDefinition?.totalProperties||0}})),am("radius")),Ve({title:"Boundary Added",description:`${g.name} - searching properties...`})},[Ve,js]),RA=o.useCallback(g=>{Zs&&(Fi.current=null,al(null)),g.startsWith("drawn-area-")&&(Xn({polygons:[],circles:[]}),Yi(!1),la(null),console.log("[PropertyLab] Cleared drawn shapes via pill removal")),bo(I=>I.filter(k=>k.id!==g)),Iy(null),HN(!1),ph("Boundary chip removed by user")},[Zs,ph]);o.useEffect(()=>{hA.current={add:CA,remove:RA}},[CA,RA]);const s5=o.useCallback(g=>{Zs&&(Fi.current=null,al(null)),Su.current&&(clearTimeout(Su.current),Su.current=null);let I=!1,k=null;qe(L=>{const Y={...L.filters};if("beds"in g&&(Y.minBeds=g.beds),"baths"in g&&(Y.minBaths=g.baths),"minPrice"in g&&(Y.minPrice=g.minPrice),"maxPrice"in g&&(Y.maxPrice=g.maxPrice),"minSqft"in g&&(Y.minSqft=g.minSqft),"maxSqft"in g&&(Y.maxSqft=g.maxSqft),"status"in g&&(Y.status=g.status),"monthsBack"in g&&(Y.monthsBack=g.monthsBack,L.filters.dateRangeMode!=="custom"&&(Y.dateRangePreset=g.monthsBack)),"propertyType"in g&&(Y.propertyType=g.propertyType),"style"in g&&(Y.styleSelection=Array.isArray(g.style)?g.style:void 0),"basementCategories"in g&&(Y.basementCategories=g.basementCategories),"remarksSearch"in g&&(Y.remarksSearch=g.remarksSearch),"status"in g&&g.status&&(Array.isArray(g.status)?g.status:[g.status]).filter(q=>Hf.has(q)&&!aA.current.has(q)).length>0&&(I=!0,k="status"),"monthsBack"in g){const K=g.monthsBack,te=mh.current;(K===void 0&&te!==Number.POSITIVE_INFINITY||typeof K=="number"&&K>te)&&(I=!0,k=k??"date")}return{...L,filters:Y}}),I&&(k&&Dy(k),Su.current=setTimeout(()=>{Su.current=null,Nr.current&&!Qn.current&&(console.log("[PropertyLab] DualSearchBar expansion needed — triggering re-search",{kind:k}),Nr.current())},100))},[Dy]),r5=o.useCallback(g=>{Zs&&(Fi.current=null,al(null)),Su.current&&(clearTimeout(Su.current),Su.current=null),Object.keys(g).length===1&&"remarksSearch"in g||XN(!0);let k=null;if("statusSelection"in g&&g.statusSelection&&g.statusSelection.filter(Y=>Hf.has(Y)&&!aA.current.has(Y)).length>0&&(k="status"),k===null){const L=Y=>{const K=mh.current;return Y===void 0&&K!==Number.POSITIVE_INFINITY||typeof Y=="number"&&Y>K};("monthsBack"in g&&L(g.monthsBack)||"dateRangePreset"in g&&g.dateRangeMode!=="custom"&&L(g.dateRangePreset))&&(k="date")}(()=>{const L=eA.current;if(!L)return!1;const K={...HC.current,...g};if(g.dateRangeMode==="custom"?(K.monthsBack=void 0,K.dateRangePreset=void 0):"dateRangePreset"in g&&(K.monthsBack=g.dateRangePreset),K.dateRangeMode==="custom")return!1;const te=K.monthsBack??K.dateRangePreset;return(K.dateFilterField??"closed")!==L.dateFilterField||te===void 0&&L.monthsBack!==void 0||te!==void 0&&L.monthsBack!==void 0&&te>L.monthsBack})(),qe(L=>{const Y={...L.filters,...g};!U&&Y.propertyTypes?.includes("STR")&&(Y.propertyTypes=Y.propertyTypes.filter(te=>te!=="STR"),Y.strOnly=!1);const K=Y.dateRangeMode==="custom";return"dateRangePreset"in g&&!K&&Y.monthsBack!==g.dateRangePreset&&(Y.monthsBack=g.dateRangePreset),g.dateRangeMode==="custom"&&(Y.monthsBack=void 0,Y.dateRangePreset=void 0),{...L,filters:Y}}),k&&(Dy(k),console.log("[PropertyLab] FilterBar expansion needed — queuing re-search",{kind:k}),Su.current=setTimeout(()=>{Su.current=null,Nr.current&&(console.log("[PropertyLab] Executing expansion re-search",{kind:k}),Nr.current())},300))},[Dy,U]),n5=o.useCallback(()=>{Zs&&(Fi.current=null,al(null)),qe(g=>({...g,filters:{...nk,...U?{propertyTypes:["STR"],strOnly:!0}:{}}}))},[U]),jR=(g,I,k,L)=>{if(!r)return;const Y=Lr.current.find(we=>we.id===g);if(!Y||!Array.isArray(Y.transferHistory)){is(we=>we+1);return}const K=Y.transferHistory,te=zZ(K,0,I,k,L),q=uI(te).TotalSalesConcessionAmount,ie=typeof q?.value=="string"||typeof q?.value=="number"?q.value:"",ee=r;Pi(we=>{const ve=we.map(Se=>Se.id!==g?Se:{...Se,transferHistory:te,gridFieldOverrides:{...Se.gridFieldOverrides??{},concessions:{...q??{},value:ie}}});return Lr.current=ve,ve}),Im(Cr.current,ee,()=>ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}`,{patch:{transferHistory:te}},{headers:ho(r)}),we=>dr(we,!0)).catch(we=>{console.error("[PropertyLab] Failed to persist UAD concession transaction:",we),is(ve=>ve+1)}),Me?.(g,"concessions",ie,{compId:g},I==="User"?"User":`SelectOnly:${I}`)},i5=(g,I)=>{if(!C)return;const k=g==="None"?{SalesConcessionIndicator:!1,SalesConcessionAmountKnownIndicator:null,TotalSalesConcessionAmount:null}:g==="Unknown"?{SalesConcessionIndicator:!0,SalesConcessionAmountKnownIndicator:!1,TotalSalesConcessionAmount:null}:g==="Amount"?{SalesConcessionIndicator:!0,SalesConcessionAmountKnownIndicator:!0,TotalSalesConcessionAmount:I??null}:{SalesConcessionIndicator:null,SalesConcessionAmountKnownIndicator:null,TotalSalesConcessionAmount:null},L=cs?.salesContract??{},Y=Bc.current?.fields??{};for(const[K,te]of Object.entries(k)){const q=Y[K==="TotalSalesConcessionAmount"?"concessions":K],ie=xO(L[K],q,te,"User");Jt("salesContract",K,ie.value,ie)}},TR=(g,I,k,L)=>{if(I=pZ(I,F,C),g==="subject"){const Y=I==="concessions"||I==="TotalSalesConcessionAmount"?"TotalSalesConcessionAmount":I==="SalesConcessionIndicator"||I==="SalesConcessionAmountKnownIndicator"||I==="SalesConcessionsTypicalToMarketIndicator"?I:null;if(C&&Y){const ie=cs?.salesContract?.[Y],ee=Bc.current?.fields?.[Y==="TotalSalesConcessionAmount"?"concessions":Y],we=xO(ie,ee,k,L);Jt("salesContract",Y,we.value,we);return}const te=C&&(I==="listPrice"||I==="listingStatus"||I==="daysOnMarket")?XZ(lh?.[I],k,L):null;if(C&&(I==="OverallQualityRatingCode"||I==="OverallConditionRatingCode")){Jt("improvements",I,k);return}if(C&&(I==="listPrice"||I==="listingStatus"||I==="daysOnMarket")){const ie=te?.value,ee=I==="listPrice"?{FinalListPriceAmount:ie===""?null:Number(ie)}:I==="daysOnMarket"?{DaysOnMarketCount:String(ie)}:{ListingStatusType:String(ie)},we=I==="listPrice"?"FinalListPriceAmount":I==="daysOnMarket"?"DaysOnMarketCount":"ListingStatusType",Se=AE(ys.current)?.__gridSourceState,Qe=te?.source==="PublicRecord"||te?.source==="AI"||te?.source==="User"?te.source:"MLS",Nt=te?{source:Qe,mlsValue:te.mlsValue,prValue:te.prValue,aiValue:te.aiValue,userValue:te.userValue}:{};ee.__gridSourceState=eJ(Se,we,Nt);const Ct=PU(ys.current,ee);ys.current=Ct,Rt("subjectListing","listings",Ct)}if(C&&(I==="ProjectName"||I==="AssociationChargeAmount"||I==="ProjectCommonAmenityType"||I==="AssociationSpecialAssessmentStatusType"||I==="SameProjectAsSubjectIndicator")){const ie=I==="AssociationChargeAmount"?"AssociationDuesAmount":I==="ProjectCommonAmenityType"?"AmenityTypes":I==="AssociationSpecialAssessmentStatusType"?"SpecialAssessmentCharges":I,ee=I==="ProjectCommonAmenityType"?String(k).split("|").map(we=>
53we.trim()).filter(Boolean):I==="AssociationSpecialAssessmentStatusType"?(()=>{const we=dp(cs?.projectInformation?.SpecialAssessmentCharges),ve=String(k).split("|").map(Se=>Se.trim()).filter(Boolean);return vO(we,ve)})():k;Jt("projectInformation",ie,ee)}else C&&I==="PropertyInProjectIndicator"&&Jt("subjectProperty",I,k);const q=ie=>{ie(ee=>{if(!ee)return ee;const we={};return I==="city"&&(we.city=String(k)),I==="state"&&(we.state=String(k)),I==="zipCode"&&(we.zipCode=String(k)),{...ee,...we,fields:{...ee.fields,[I]:te??{...ee.fields[I],value:k,source:L,hasConflict:!1,isVerified:!0}}}})};if(He&&yl==="after-repaired")q(Hu);else{if(q($c),I!=="leaseholdFeeSimple")if(!as)hm(ie=>({...ie,[I]:{value:k,source:L}}));else{const{vsPatch:ie}=XT(I,k);mm(ee=>ee&&{...ee,...ie,gridSubjectOverrides:{...ee.gridSubjectOverrides,[I]:{value:k,source:L}}})}if(C&&(I==="LandOwnedInCommonIndicator"||I==="NeighborhoodName"||I==="LotSizeAreaMeasure"||I==="AreaUnitOfMeasureType"||I==="SiteZoningComplianceType"||I==="HazardZoneType")){const ie=Yt.site??{},ee=we=>we&&typeof we=="object"&&"value"in we?we.value:we;if(I==="LandOwnedInCommonIndicator"||I==="NeighborhoodName")Jt("subjectProperty",I,k);else if(I==="SiteZoningComplianceType"){const we=ee(ie.zoning);Jt("site","zoning",{...we&&typeof we=="object"?we:{},SiteZoningComplianceType:k})}else if(I==="LotSizeAreaMeasure"||I==="AreaUnitOfMeasureType"){const we=ee(ie.parcels),ve=Array.isArray(we)?we.filter(Ht=>Ht&&typeof Ht=="object"):[],Se=k===""?null:Number(k),Qe=.09290304,Nt=(Ht,Cs)=>Cs==="Acres"?Ht*jE*Qe:Cs==="Hectares"?Ht*TE:Cs==="SquareMeters"?Ht:Ht*Qe,Ct=(Ht,Cs)=>Cs==="Acres"?Ht/(jE*Qe):Cs==="Hectares"?Ht/TE:Cs==="SquareMeters"?Ht:Ht/Qe,va=I==="AreaUnitOfMeasureType"?(ve.length>0?ve:[{}]).map((Ht,Cs)=>{const aa=String(Ht.areaUnit??"SquareFeet"),Ft=Number(Ht.ParcelAreaMeasure);return{...Ht,id:Ht.id??`grid-parcel-${Cs+1}`,areaUnit:k,...Number.isFinite(Ft)?{ParcelAreaMeasure:Ct(Nt(Ft,aa),String(k))}:{}}}):(()=>{const Ht=String(Ge?.unit??ve[0]?.areaUnit??"SquareFeet"),Cs=ve.reduce((da,es)=>{const Js=Number(es.ParcelAreaMeasure);return Number.isFinite(Js)?da+Nt(Js,String(es.areaUnit??Ht)):da},0),aa=Se===null||Number.isNaN(Se)?null:Nt(Se,Ht),Ft=aa===null||Cs<=0?null:aa/Cs;return(ve.length>0?ve:[{}]).map((da,es)=>({...da,id:da.id??`grid-parcel-${es+1}`,...Se===null?{ParcelAreaMeasure:null}:Number.isFinite(Number(da.ParcelAreaMeasure))&&Ft!==null?{ParcelAreaMeasure:Number(da.ParcelAreaMeasure)*Ft}:es===0?{ParcelAreaMeasure:Ct(aa??Nt(Se,Ht),String(da.areaUnit??Ht))}:{}}))})();Jt("site","parcels",va)}else{const we=ee(ie.hazardZones),ve=String(k).split("|").map(Qe=>Qe.trim()).filter(Boolean),Se=Array.isArray(we)?we.filter(Qe=>Qe&&typeof Qe=="object"):[];Jt("site","hazardZones",(ve.length>0?ve:["None"]).map((Qe,Nt)=>({...Se[Nt]??{},id:Se[Nt]?.id??`grid-hazard-${Nt+1}`,HazardZoneType:Qe})))}}if(C&&I==="attachedDetached"){const ie=Bc.current?.fields?.attachedDetached??Gt;Rt("subjectProperty","AttachmentType",WZ(pa,ie,k,L))}if(ut?.(I,k,L),C&&r){let ie=!1;const ee=xf[I];ee&&(No.current.push({section:ee.section,field:ee.field,value:k}),ie=!0,ee.section==="improvements"&&(I==="quality"||I==="condition"||I==="OverallQualityRatingCode"||I==="OverallConditionRatingCode")&&qi.setQueriesData({queryKey:["/api/uad36/prefill",r]},Se=>{if(!Se)return Se;const Qe=Se.sections?.[ee.section]?.[ee.field];return{...Se,sections:{...Se.sections,[ee.section]:{...Se.sections?.[ee.section],[ee.field]:{...typeof Qe=="object"&&Qe!==null?Qe:{},value:k}}}}}));let we=!1;const ve=/^Outbuilding(\d+)_OutbuildingType(OtherDescription)?$/.exec(I);if(ve){const Se=parseInt(ve[1],10),Qe=!!ve[2],Nt=gt.current;if(Nt.length>0){let Ct=0;const va=Nt.map(Ht=>{if(Ht.improvementType!=="Outbuilding"||Ht.outbuildingRealPropertyIndicator!==!0||!Ht.outbuildingType||Ht.outbuildingType==="StandaloneADU"||Ht.outbuildingType==="Other"&&Ht.outbuildingTypeOtherDescription==="ADUGarage")return Ht;if(Ct++,Ct!==Se){if(Bc.current!=null){const aa=Bc.current.fields?.[`Outbuilding${Ct}_OutbuildingType`]?.value,Ft=Bc.current.fields?.[`Outbuilding${Ct}_OutbuildingTypeOtherDescription`]?.value,ss=aa||null;return{...Ht,outbuildingType:ss,outbuildingTypeOtherDescription:Ft||null,outbuildingRealPropertyIndicator:ss?Ht.outbuildingRealPropertyIndicator:!1}}return Ht}if(Qe)return{...Ht,outbuildingTypeOtherDescription:String(k)};const Cs=String(k);return Cs?{...Ht,outbuildingType:Cs}:Ht});gt.current=va;try{const Ht={};let Cs=0;for(const aa of va)aa.improvementType!=="Outbuilding"||aa.outbuildingRealPropertyIndicator!==!0||!aa.outbuildingType||aa.outbuildingType==="StandaloneADU"||aa.outbuildingType==="Other"&&aa.outbuildingTypeOtherDescription==="ADUGarage"||(Cs++,Ht[`Outbuilding${Cs}_OutbuildingType`]=aa.outbuildingType||null,Ht[`Outbuilding${Cs}_OutbuildingTypeOtherDescription`]=aa.outbuildingTypeOtherDescription||null);sessionStorage.setItem(`uad36_ob_types_${r}`,JSON.stringify(Ht))}catch{}No.current=No.current.filter(Ht=>!(Ht.section==="improvements"&&Ht.field==="buildings")),No.current.push({section:"improvements",field:"buildings",value:va}),ie=!0,we=!0}}ie&&Jo(we?50:1500)}}}else{if(C&&Us!=="rental"&&r){const ie=UZ(I);if(ie==="DataSources"){let ss=k;if(typeof k=="string")try{ss=JSON.parse(k)}catch{ss=[]}const da=GL(ss,{allowIncomplete:!0}),es=da[0]?.source==="mls"?"MLS":da[0]?.source==="public_records"?"PublicRecord":"User";Pi(er=>{const ga=er.map(As=>As.id!==g?As:{...As,gridFieldOverrides:{...As.gridFieldOverrides??{},dataSource:{value:HL(da),source:es,dataSources:da}}});return Lr.current=ga,ga});const Js=r;Im(Cr.current,Js,()=>ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}/fields/${ie}`,{value:da,source:"User"},{headers:ho(r)}),er=>dr(er,!0)).catch(er=>{console.error("[PropertyLab] Failed to persist comparable Data Sources:",er),is(ga=>ga+1)}),Me?.(g,I,k,{compId:g},"User");return}const ee=I==="attachedDetached"?"AttachmentType":I==="listPrice"?"FinalListPriceAmount":I==="listingStatus"?"ListingStatusType":I==="daysOnMarket"?"DaysOnMarketCount":I==="AssociationChargeAmount"?"AssociationDuesAmount":I==="ProjectCommonAmenityType"?"AmenityTypes":I==="AssociationSpecialAssessmentStatusType"?"SpecialAssessmentCharges":I,we=Lr.current.find(ss=>ss.id===g),ve=I==="AssociationChargeAmount"||I==="ProjectCommonAmenityType"||I==="AssociationSpecialAssessmentStatusType",Se=I==="ProjectCommonAmenityType"?String(k).split("|").map(ss=>
53ss.trim()).filter(Boolean):I==="AssociationSpecialAssessmentStatusType"?(()=>{const ss=String(k).split("|").map(Js=>Js.trim()).filter(Boolean),da=we?.fields,es=dp(we?.gridFieldOverrides?.SpecialAssessmentCharges??we?.gridFieldOverrides?.AssociationSpecialAssessmentStatusType??da?.SpecialAssessmentCharges??da?.AssociationSpecialAssessmentStatusType);return vO(es,ss)})():k,Qe=I.match(/^saleHistory(\d+)_([A-Za-z0-9]+)$/),Ct={salePrice:"OwnershipTransferTransactionAmount",saleType:"SaleType",saleTypeOtherDescription:"SaleTypeOtherDescription",financingOtherDescription:"MortgageTypeOtherDescription",dateOfSale:"OwnershipTransferDate",concessions:"TotalSalesConcessionAmount"}[I];if(Qe||Ct){const ss=Qe?Number(Qe[1]):0,da=Qe?Qe[2]:Ct,es=Lr.current.find(er=>er.id===g),Js=es?.transferHistory;if(es&&Array.isArray(Js)){const er=L.startsWith("SelectOnly:"),ga=Qe?da:Ct,As=FM(es.gridFieldOverrides?.[ga]),Ya=Dx(Js,ss,da,k,L,{promoteCurrentSale:!Qe&&!er,candidateSeed:As}),Aa=Ya[ss]?.[da],ns=Qe?MN({[da]:Aa})[da]:uI(Ya)[ga],Sr=r;Pi(Or=>{const Li=Or.map(Ti=>Ti.id!==g?Ti:{...Ti,transferHistory:Ya,gridFieldOverrides:{...Ti.gridFieldOverrides??{},[ga]:{...ns??{},value:ns?.value===null||ns?.value===void 0?"":ns.value}}});return Lr.current=Li,Li}),Im(Cr.current,Sr,()=>ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}`,{patch:{transferHistory:Ya}},{headers:ho(r)}),Or=>dr(Or,!0)).catch(Or=>{console.error("[PropertyLab] Failed to persist UAD sale history:",Or),is(Li=>Li+1)})}Me?.(g,ee,k,{compId:g},L);return}if(L==="Mirror"){Me?.(g,I,k,{compId:g},L);return}const va=new Set(["AttachmentType","FinalListPriceAmount","ListingStatusType","DaysOnMarketCount","OwnershipTransferTransactionAmount","SalesContractAmount","ContractAmountUnknownIndicator","SalesContractDate","ContractDateUnknownIndicator","ProximityToSubjectDistanceLinearMeasure","LinearUnitOfMeasureType","ComparableToSubjectDirectionType"]).has(ee),Ht=L.startsWith("SelectOnly:")?L.slice(11):L,Cs=ss=>tJ(ss,Se,Ht,va,ee==="ProximityToSubjectDistanceLinearMeasure"||ee==="LinearUnitOfMeasureType"||ee==="ComparableToSubjectDirectionType"),aa=ss=>({...ss??{},value:Se,source:Ht});Pi(ss=>{const da=ss.map(es=>es.id!==g?es:{...es,gridFieldOverrides:{...es.gridFieldOverrides??{},[I]:ve?aa(es.gridFieldOverrides?.[I]):Cs(es.gridFieldOverrides?.[I]),...ee!==I?{[ee]:ve?aa(es.gridFieldOverrides?.[ee]):Cs(es.gridFieldOverrides?.[ee])}:{}}});return Lr.current=da,da});const Ft=r;Im(Cr.current,Ft,()=>ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}/fields/${encodeURIComponent(ee)}`,{value:Se,source:Ht},{headers:ho(r)}),ss=>dr(ss,!0)).catch(ss=>{console.error("[PropertyLab] Failed to persist UAD grid field:",ss),is(da=>da+1)}),Me?.(g,I,k,{compId:g},L);return}const Y=ie=>{if(typeof ie=="number")return ie;const ee=String(ie).replace(/[$%,]/g,"").trim(),we=parseFloat(ee);return isNaN(we)?void 0:we},K=F&&!C&&I==="neighborhoodName"?xu.find(ie=>ie.id===g)?.fields.neighborhoodName:void 0;qe(ie=>({...ie,selectedComps:ie.selectedComps.map(ee=>{if(ee.id!==g&&ee.snapshotId!==g)return ee;const we={...ee.gridFieldOverrides||{},...K&&!ee.gridFieldOverrides?.neighborhoodName?{neighborhoodName:{...K,value:K.value==null?"":String(K.value)}}:{}},ve=fZ(we,I,k,L,F&&!C&&I==="neighborhoodName",F&&!C),Se={gridFieldOverrides:ve};if(F&&!C&&mZ(_u.current,ee,ve),I.startsWith("str"))switch(I){case"strNightlyRate":Se.strAverageDailyRate=Y(k);break;case"strOccupancy":const Qe=Y(k);Se.strOccupancyRate=Qe!==void 0?Qe>1?Qe:Qe*100:void 0;break;case"strGrossIncome":Se.strGrossMonthlyIncome=Y(k);break}return{...ee,...Se}})})),HF(g,I,k,L);const te=re.selectedComps.find(ie=>ie.id===g||ie.snapshotId===g),q=F&&!C?hZ(re.selectedComps,g):te?{compId:te.id,snapshotId:te.snapshotId,mlsNumber:te.mlsNumber,address:te.address}:{compId:g};Me?.(g,I,k,q,L,K?.sourceCandidates)}},Eb=o.useRef(W7()),IR=o.useRef(Promise.resolve()),CR=o.useCallback((g,I)=>{!C||!r||Jt("energyFeatures",g,I.slice(0,8))},[r,C,Jt]),RR=o.useCallback(g=>{if(!C||!r)return;const I=cs?.salesComparisonGrid?.visibleRows,k=Array.isArray(I?.value)?I.value:[],L=new Set(["RenewableEnergyComponentType","GreenCertificationName","EfficiencyRatingName"]);Jt("salesComparisonGrid","visibleRows",[...k.filter(Y=>!L.has(Y.rowId)),...g])},[r,C,cs,Jt]),ER=o.useCallback(async g=>{if(!C||!r)return!1;const I=cs?.salesComparisonGrid?.visibleRows,k=Array.isArray(I?.value)?I.value:[],L=new Set(["LandOwnedInCommonIndicator","NeighborhoodName","SiteZoningComplianceType","HazardZoneType"]),Y=ne
53w Set(["LandOwnedInCommonIndicator","NeighborhoodName","SiteZoningComplianceType","HazardZoneType","LotSizeAreaMeasure"]),K=[...k.filter(te=>!Y.has(te.rowId)),...g.filter(te=>L.has(te.rowId))];return JSON.stringify(k)===JSON.stringify(K)?!0:(Jt("salesComparisonGrid","visibleRows",K),Bt())},[r,C,cs,Bt,Jt]),wR=o.useCallback(g=>{if(!C||!r)return;const I=cs?.salesComparisonGrid?.visibleRows,k=Array.isArray(I?.value)?I.value:[],L=new Set(cd.map(Y=>zx(Y)));Jt("salesComparisonGrid","visibleRows",[...k.filter(Y=>!L.has(Y.rowId)),...g])},[r,C,cs,Jt]),PR=o.useCallback(g=>{!C||!r||Jt("propertyAmenities","amenities",g)},[r,C,Jt]),OR=o.useCallback((g,I)=>{if(!C||!r)return;const k=I==="Condominium"||I==="Condop"||I==="Cooperative"?{ProjectClassificationType:I,ProjectLegalStructureType:I,PropertyInProjectIndicator:"true",PUDIndicator:"false"}:I==="PUD"?{ProjectClassificationType:I,ProjectLegalStructureType:null,PropertyInProjectIndicator:"false",PUDIndicator:"true"}:{ProjectClassificationType:I||null,ProjectLegalStructureType:null,PropertyInProjectIndicator:"false",PUDIndicator:"false"};Pi(L=>{const Y=L.map(K=>K.id!==g?K:{...K,gridFieldOverrides:{...K.gridFieldOverrides??{},...Object.fromEntries(Object.entries(k).map(([te,q])=>[te,{value:q,source:"User",userEdited:!0}]))}});return Lr.current=Y,Y}),Im(Cr.current,r,()=>Go(r,ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}/facts`,{projectClassification:I},{headers:ho(r)})),L=>dr(L,!0)).catch(()=>is(L=>L+1))},[dr,r,C,Go]),LR=o.useCallback((g,I)=>{if(!C||!r)return;const k=I.map((Y,K)=>({...Y,order:K})),L={dwellings:k.filter(Y=>Y.improvementType==="Dwelling"),outbuildings:k.filter(Y=>Y.improvementType==="Outbuilding")};Pi(Y=>{const K=Y.map(te=>te.id!==g?te:{...te,gridFieldOverrides:{...te.gridFieldOverrides??{},Dwellings:{value:L.dwellings,source:"User",userEdited:!0},Outbuildings:{value:L.outbuildings,source:"User",userEdited:!0}}});return Lr.current=K,K}),Im(Cr.current,r,()=>Go(r,ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}/facts`,{structures:L},{headers:ho(r)})),Y=>dr(Y,!0)).catch(()=>is(Y=>Y+1))},[dr,r,C,Go]),DR=o.useCallback((g,I)=>{if(!C||!r)return;const k={amenities:I};Pi(L=>L.map(Y=>Y.id===g?{...Y,gridFieldOverrides:{...Y.gridFieldOverrides??{},PropertyAmenities:{value:k,source:"User"}}}:Y)),Yb(Eb.current,`${g}:PropertyAmenities`,()=>Go(r,ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}/fields/PropertyAmenities`,{value:k},{headers:ho(r)})),()=>is(L=>L+1),()=>is(L=>L+1))},[r,C,Go]),o5=o.useCallback((g,I,k,L)=>{if(!C||!r)return;const Y=L.startsWith("ClearUser"),K=L==="MLS"?"mls":L==="PublicRecord"?"public_records":L==="AI"?"ai_derived":"user",q=xu.find(Qe=>Qe.id===g)?.fields[I],ie=q&&typeof q=="object"?q:{},ee={...ie.sourceCandidates&&typeof ie.sourceCandidates=="object"?ie.sourceCandidates:{}};let we=k,ve=L;if(Y){delete ee.user;const Qe=L.includes(":")?L.split(":")[1]:void 0,Nt=[["MLS","mls"],["PublicRecord","public_records"],["AI","ai_derived"]],Ct=Qe?Nt.find(([va])=>va===Qe):Nt.find(([,va])=>ee[va]!==void 0);Ct&&ee[Ct[1]]!==void 0?(we=ee[Ct[1]],ve=Ct[0]):(we=[],ve="User")}else ee[K]=k;const Se={...ie,value:we,source:ve,userEdited:Y?!0:K==="user",sourceCandidates:ee};Pi(Qe=>Qe.map(Nt=>Nt.id===g?{...Nt,gridFieldOverrides:{...Nt.gridFieldOverrides??{},[I]:Se}}:Nt)),Yb(Eb.current,`${g}:${I}`,()=>Go(r,ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}/fields/${I}`,{value:k,source:L},{headers:ho(r)})),()=>is(Qe=>Qe+1),()=>is(Qe=>Qe+1))},[r,C,xu,Go]),kR=o.useCallback((g,I)=>{!C||!r||Jt("site",g,I)},[r,C,Jt]),MR=(g,I,k)=>{if(!C||!r)return;const Y=xu.find(te=>te.id===g)?.fields.EnergyFeatures?.value,K={...Y&&typeof Y=="object"?Y:{},[I]:{value:k.slice(0,8),confidence:"manual",source:"user",userEdited:!0}};Pi(te=>te.map(q=>q.id===g?{...q,gridFieldOverrides:{...q.gridFieldOverrides??{},EnergyFeatures:{value:K,source:"User"}}}:q)),Yb(Eb.current,`${g}:EnergyFeatures`,()=>Go(r,ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}/fields/EnergyFeatures`,{value:K},{headers:ho(r)})),()=>is(te=>te+1),()=>is(te=>te+1))},FR=o.useCallback(g=>{if(F&&!C){const L=g.slice(0,12);$c(Y=>Y&&{...Y,vehicleStorageItems:L,vehicleStorageSource:"User",vehicleStorageUserEdited:!0,vehicleStorageExplicitNone:L.length===0}),ut?.("VehicleStorageItems",JSON.stringify(L));return}if(!C||!r)return;const I=g.slice(0,12);Rt("vehicleStorage","items",I);const k={value:I,confidence:"manual",source:"user",userEdited:!0};qi.setQueriesData({queryKey:["/api/uad36/prefill",r]},L=>{if(!L)return L;const Y=L.sections?.vehicleStorage?.items;return{...L,sections:{...L.sections,vehicleStorage:{...L.sections?.vehicleStorage,items:{...typeof Y=="object"&&Y!==null?Y:{},...k}}}}}),No.current=No.current.filter(L=>!(L.section==="vehicleStorage"&&L.field==="items")),No.current.push({section:"vehicleStorage",field:"items",value:k}),Jo(50)},[r,C,F,ut,qi,Jo,Rt]),l5=(g,I)=>{const k=I.slice(0,12).map(({photos:L,...Y})=>Y);if(F&&!C){qe(Y=>({...Y,selectedComps:Y.selectedComps.map(K=>K.id===g||K.snapshotId===g?{...K,vehicleStorageItems:k,vehicleStorageSource:"User",vehicleStorageUserEdited:!0,vehicleStorageExplicitNone:k.length===0}:K)}));const L=re.selectedComps.find(Y=>Y.id===g||Y.snapshotId===g);Me?.(g,"VehicleStorageItems",JSON.stringify(k),L?{compId:L.id,snapshotId:L.snapshotId,mlsNumber:L.mlsNumber,address:L.address}:{compId:g},"User");return}!C||Us==="rental"||!r||(Pi(L=>
53L.map(Y=>Y.id!==g?Y:{...Y,vehicleStorageItems:k})),Yb(Eb.current,`${g}:VehicleStorageItems`,()=>Go(r,ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}/fields/VehicleStorageItems`,{value:k},{headers:ho(r)})),()=>is(L=>L+1),L=>{console.error("[PropertyLab] Failed to persist Vehicle Storage:",L),is(Y=>Y+1)}))},_R=o.useCallback((g,I)=>{if(!C||!r)return Promise.resolve(!1);const k=async()=>{try{const Y=await Go(r,ol(`/api/uad36/comparables/${encodeURIComponent(r)}/vehicle-storage-rows`,{visibleRows:g,deleteCustomId:I},{headers:ho(r)})),K=Y.visibleRows??g;return Rt("salesComparisonGrid","visibleRows",K),qi.setQueriesData({queryKey:["/api/uad36/prefill",r]},te=>{if(!te)return te;const q=te.sections?.salesComparisonGrid?.visibleRows,ie={...te.sections?.salesComparison,...Y.orderedComparables?{orderedComparables:Y.orderedComparables}:{}};return I&&delete ie[`SubjectCustom_${I}`],{...te,sections:{...te.sections,salesComparison:ie,salesComparisonGrid:{...te.sections?.salesComparisonGrid,visibleRows:{...typeof q=="object"&&q!==null?q:{},value:K,confidence:"manual",source:"user",userEdited:!0}}}}}),await qi.invalidateQueries({queryKey:["/api/uad36/prefill",r]}),is(te=>te+1),!0}catch(Y){return console.error("[PropertyLab] Failed to persist Vehicle Storage Additional Rows:",Y),qi.invalidateQueries({queryKey:["/api/uad36/prefill",r]}),is(K=>K+1),!1}},L=IR.current.catch(()=>{}).then(k);return IR.current=L.then(()=>{}),L}
53,[r,C,qi,Go,Rt]),UR=o.useCallback((g,I,k)=>{if(!C||!r)return;const L=k===""?null:{value:k,confidence:"manual",source:"user",userEdited:!0};if(g==="subject"){qi.setQueriesData({queryKey:["/api/uad36/prefill",r]},Y=>Y&&{...Y,sections:{...Y.sections,salesComparison:{...Y.sections?.salesComparison,[`SubjectCustom_${I}`]:L}}}),No.current=No.current.filter(Y=>!(Y.section==="salesComparison"&&Y.field===`SubjectCustom_${I}`)),No.current.push({section:"salesComparison",field:`SubjectCustom_${I}`,value:L}),Jo(50);return}Pi(Y=>Y.map(K=>K.id===g?{...K,vehicleStorageCustomRows:{...K.vehicleStorageCustomRows??{},[I]:k}}:K)),Yb(Eb.current,`${g}:customRows`,()=>Go(r,ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}`,{patch:{customRows:{[I]:L}}},{headers:ho(r)})),()=>is(Y=>Y+1),Y=>{console.error("[PropertyLab] Failed to persist Vehicle Storage Additional Row value:",Y),is(K=>K+1)})},[r,C,qi,Jo,Go]),c5=(g,I,k)=>{if(!C||Us==="rental"||!r){Re?.(g,I,k);return}const L=I==="attachedDetached"?"AttachedOrDetached":I;Qi(Y=>({...Y,[g]:{...Y[g]??{},[L]:k}})),Go(r,ol(`/api/uad36/comparables/${encodeURIComponent(r)}/items/${encodeURIComponent(g)}/adjustments/${encodeURIComponent(L)}`,{value:k},{headers:ho(r)})).catch(Y=>{console.error("[PropertyLab] Failed to persist UAD grid adjustment:",Y),is(K=>K+1)})},Xu=o.useMemo(()=>{if(!(Ll&&!Wr))return null;const g=Je,I=ht,k=t,L=jm(a||""),Y=L?.city||"",K=L?.state||i||"",te=g?.photos?.length?g.photos:I?.photos?.length?I.photos:ni,q=v0(I),ie={id:"subject",address:a||"Unknown Address",city:Y,state:K,zipCode:l||L?.zip||"",lat:s?.lat,lng:s?.lng,photoUrl:te[0]||null,photos:te,status:OS(q),isSubject:!0,fields:{salePrice:{value:I?.soldPrice||g?.lastSalePrice||k?.salePrice?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},dateOfSale:{value:(()=>{const Se=I?.soldDate||g?.lastSaleDate||k?.saleDate?.value||null,Qe=I?.contractDate||k?.contractDate?.value||null;return Se?Mm(Se,Qe):null})(),source:"MLS",hasConflict:!1,isVerified:!0},gla:{value:g?.squareFeet||I?.squareFeet||k?.gla?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},yearBuilt:{value:(()=>{const Se=g?.yearBuilt||I?.yearBuilt||k?.yearBuilt?.value;return Se?Number(Se):null})(),source:"MLS",hasConflict:!1,isVerified:!0},aboveGrade:{value:(()=>{const Se=g?.bedrooms||I?.bedrooms||k?.beds?.value,Qe=g?.bathrooms||I?.bathrooms||k?.baths?.value,Nt=g?.fullBathrooms??I?.fullBathrooms??k?.fullBaths?.value,Ct=g?.halfBathrooms??I?.halfBathrooms??k?.halfBaths?.value,va=Uh(Nt!=null?Number(Nt):null,Ct!=null?Number(Ct):null,Qe!=null?Number(Qe):null),Ht=Qe!=null?Number(Qe):Nt!=null?Number(Nt)+(Ct!=null?Number(Ct)*.5:0):0;return Se!=null?`${Number(Se)+Math.ceil(Ht)+2}|${Se}|${va}`:null})(),source:"MLS",hasConflict:!1,isVerified:!0},...DS(I,g,k),...Qb(k),site:{value:g?.lotSize||I?.lotSize||k?.lotSize?.value||null,source:"MLS",hasConflict:!1,isVerified:!0},view:{value:k?.view?.value||null,source:"MLS",hasConflict:!1,isVerified:!1},design:{value:g?.style||I?.style||k?.style?.value||null,source:"MLS",hasConflict:!1,isVerified:!0}}},ee=Mb(Kb(ie,as),he),we=Object.entries(fu);return we.length===0?ee:{...ee,fields:{...ee.fields,...Object.fromEntries(we.map(([Se,Qe])=>[Se,{...ee.fields[Se]||{},value:Qe.value,source:Qe.source,hasConflict:!1,isVerified:!0}]))}}},[Ll,Wr,Je,ht,t,a,i,l,s?.lat,s?.lng,ni,Fn,as,fu]),VR=o.useCallback(g=>{const{fields:I,...k}=g;return k},[]),EA=e.jsxs(De,{variant:"outline",size:"sm",className:"h-[34px] text-[12px] gap-1.5",onClick:()=>bc(!0),"data-testid":"button-import-csv",children:[e.jsx(Zx,{size:14}),"Import CSV"]}),wA=e.jsx(fQ,{open:bb,onOpenChange:bc,onConfirm:_F,loadSavedMapping:Cd,availableTargets:Le?["comps","market","subject"]:["comps","market"],subjectColumn:{address:a,values:{yearBuilt:t.yearBuilt?.value!=null?String(t.yearBuilt.value):void 0,gla:t.gla?.value!=null?String(t.gla.value):t.squareFeet?.value!=null?String(t.squareFeet.value):void 0,beds:t.bedrooms?.value!=null?String(t.bedrooms.value):void 0,baths:t.bathrooms?.value!=null?String(t.bathrooms.value):void 0,lotSize:t.lotSize?.value!=null?String(t.lotSize.value):void 0,basement:t.basementFinish?.value!=null?String(t.basementFinish.value):void 0}}}),d5=o.useCallback((g,I)=>{if(!r)return;const k=r,L=Lr.current.find(ee=>ee.id===g),Y=L?.transferHistory;if(!L||!Array.isArray(Y))return;const K=I.map(ee=>Y[ee]).filter(ee=>!!ee);if(K.length===Y.length&&K.every((ee,we)=>ee===Y[we]))return;const q=Object.fromEntries(K.flatMap((ee,we)=>Object.entries(ee).map(([ve,Se])=>{const Qe=Se&&typeof Se=="object"&&"value"in Se?Se:{value:Se,source:"mls"},Nt=Qe.source==="user"?"User":Qe.source==="public_record"||Qe.source==="public_records"?"PublicRecord":Qe.source==="ai"||Qe.source==="ai_derived"?"AI":"MLS";return[`saleHistory${we}_${ve}`,{value:typeof Qe.value=="string"||typeof Qe.value=="number"?Qe.value:"",source:Nt}]})));EI(K);const ie=Lr.current.map(ee=>ee.id===g?{...ee,transferHistory:K,gridFieldOverrides:{...Object.fromEntries(Object.entries(ee.gridFieldOverrides??{}).filter(([we])=>!/^saleHistory\d+_/.test(we))),...q}}:ee);Lr.current=ie,Pi(ie),Im(Cr.current,k,()=>ol(`/api/uad36/comparables/${encodeURIComponent(k)}/items/${encodeURIComponent(g)}`,{patch:{transferHistory:K}},{headers:ho(k)}),ee=>dr(ee,!0)).catch(ee=>{console.error("[PropertyLab] Failed to persist reordered sale history:",ee),is(we=>we+1)})},[ol,r,dr]);if(Ll&&!Wr&&Xu)return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"px-4 py-2 bg-amber-50/80 border-b border-amber-200/60 flex items-center gap-2",children:[e.jsx(Di,{className:"w-3.5 h-3.5 text-amber-600 shrink-0"}),e.jsx("span",{className:"text-xs text-amber-700",children:"No comparables selected yet. Subject edits are saved; select comps in Property Lab to add comparable columns."})]}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(d1,{subject:C?VR(Xu):On(Xu),comps:[],uad36SubjectCanonicalFields:lh,onUad36SubjectCanonicalFieldChange:Jt,uad36SubjectContractExists:br??!1,uad36SubjectContractReviewed:zr??!1,subjectSiteInfo:{influences:_s.influences??[],views:_s.views??[],site:_s,influencesSource:et("influences"),viewsSource:et("views")},onSubjectSiteInfoChange:kR,subjectVehicleStorageItems:F?B?[]:M.length>0?[...M]:ae?[]:Xu.vehicleStorageUserEdited?Xu.vehicleStorageItems??[]:ks.items??Xu.vehicleStorageItems??[]:bt??[],subjectVehicleStorageLoading:F?!1:xe,subjectVehicleStorageSource:F?M.length>0||B||ae||Xu.vehicleStorageUserEdited?"User":ks.source:ra,subjectVehicleStorageUserEdited:F?M.length>0||B||ae||Xu.vehicleStorageUserEdited===!0:ta,subjectVehicleStorageExplicitNone:F?B||(ae?!1:Xu.vehicleStorageUserEdited?Xu.vehicleStorageExplicitNone===!0:ks.explicitNone)||Xu.vehicleStorageExplicitNone===!0:!1,onSubjectVehicleStorageChange:FR,vehicleStorageRows:Mt,vehicleStorageSubjectValues:ms,onVehicleStorageRowsChange:_R,onVehicleStorageCustomValueChange:UR,subjectEnergyFeatures:cr,energyRows:Cn,siteRows:Ai,amenityRows:Rn,onAmenityRowsChange:wR,subjectAmenities:Ml,subjectAmenitiesSource:bu,subjectAmenitiesHasManufacturedHome:Kn,uad36ProjectFields:{...cs?.subjectProperty??{},...cs?.projectInformation??{}},uad36SubjectPropertyFields:cs?.subjectProperty??{},onSubjectAmenitiesChange:PR,onComparableAmenitiesChange:DR,onComparableProjectClassificationChange:OR,onComparableStructuresChange:LR,onSubjectEnergyCollectionChange:CR,onComparableEnergyCollectionChange:MR,onEnergyRowsChange:RR,onSiteRowsChange:ER,detectedOptionalSections:he,effectiveDate:n,onFieldU
53pdate:TR,onSubjectConcessionTransactionChange:i5,onComparableConcessionTransactionChange:jR,onComplete:()=>{},onBack:()=>{oi(!1),h?.()},gridMode:"1004",enableUad36:C,uad36ReconciliationValue:Yt.reconciliation?.SalesComparisonValue?.value,uad36ReconciliationValueMode:Yt.salesComparisonGrid?.valueMode?.value,uad36ReconciliationFieldPresent:Object.prototype.hasOwnProperty.call(Yt.reconciliation??{},"SalesComparisonValue"),uad36ReconciliationHydrated:ha,onUad36ReconciliationValueChange:g=>Jt("reconciliation","SalesComparisonValue",g),onUad36ReconciliationValueModeChange:g=>Jt("salesComparisonGrid","valueMode",g),evalGridProfile:F,evalCustomComparisonFactors:_,onEvalCustomComparisonFactorsChange:$,assignmentId:r,onMapSnapshotChange:At,toolbarExtraActions:EA})}),wA]});if(Ll&&Wr){const g=He&&Gg||Wr,I=C?VR(g):g,k=He?vi:xu;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"h-full flex flex-col",children:[He&&e.jsx("div",{className:"flex items-center gap-2 px-4 py-2 bg-white border-b",children:e.jsxs("div",{className:"ml-auto flex items-center gap-2","data-testid":"scenario-toggle-bar",children:[e.jsx("span",{className:"text-xs text-slate-500 mr-1",children:"Scenario:"}),e.jsxs("div",{className:"flex rounded-md border border-slate-200 overflow-hidden",children:[e.jsx("button",{onClick:()=>zg("as-is"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${yl==="as-is"?"bg-[#0D3855] text-white":"bg-white text-slate-600 hover:bg-slate-50"}`,"data-testid":"button-scenario-as-is",children:"As-Is"}),e.jsx("button",{onClick:()=>zg("after-repaired"),className:`px-3 py-1.5 text-xs font-medium transition-colors ${yl==="after-repaired"?"bg-[#E67E22] text-white":"bg-white text-slate-600 hover:bg-slate-50"}`,"data-testid":"button-scenario-after-repaired",children:"After-Repaired"})]}),e.jsxs(kt,{className:"text-[10px] ml-1",variant:"outline","data-testid":"badge-scenario-comp-count",children:[k.length," comp",k.length!==1?"s":""]})]})}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[e.jsx(d1,{subject:C?I:On(I),comps:k,uad36SubjectCanonicalFields:lh,onUad36SubjectCanonicalFieldChange:Jt,uad36SubjectContractExists:br??!1,uad36SubjectContractReviewed:zr??!1,subjectSiteInfo:{influences:_s.influences??[],views:_s.views??[],site:_s,influencesSource:et("influences"),viewsSource:et("views")},onSubjectSiteInfoChange:kR,subjectVehicleStorageItems:F?B?[]:M.length>0?[...M]:ae?[]:I.vehicleStorageUserEdited?I.vehicleStorageItems??[]:ks.items??I.vehicleStorageItems??[]:bt??[],subjectVehicleStorageLoading:F?!1:xe,subjectVehicleStorageSource:F?M.length>0||B||ae||I.vehicleStorageUserEdited?"User":ks.source:ra,subjectVehicleStorageUserEdited:F?M.length>0||B||ae||I.vehicleStorageUserEdited===!0:ta,subjectVehicleStorageExplicitNone:F?B||(ae?!1:I.vehicleStorageUserEdited?I.vehicleStorageExplicitNone===!0:ks.explicitNone)||I.vehicleStorageExplicitNone===!0:!1,onSubjectVehicleStorageChange:FR,onComparableVehicleStorageChange:l5,vehicleStorageRows:Mt,vehicleStorageSubjectValues:ms,onVehicleStorageRowsChange:_R,onVehicleStorageCustomValueChange:UR,subjectEnergyFeatures:cr,energyRows:Cn,siteRows:Ai,amenityRows:Rn,onAmenityRowsChange:wR,subjectAmenities:Ml,subjectAmenitiesSource:bu,subjectAmenitiesHasManufacturedHome:Kn,uad36ProjectFields:{...cs?.subjectProperty??{},...cs?.projectInformation??{}},uad36SubjectPropertyFields:cs?.subjectProperty??{},onSubjectAmenitiesChange:PR,onComparableAmenitiesChange:DR,onComparableProjectClassificationChange:OR,onComparableStructuresChange:LR,onComparableSiteInfoChange:o5,onSubjectEnergyCollectionChange:CR,onComparableEnergyCollectionChange:MR,onEnergyRowsChange:RR,onSiteRowsChange:ER,detectedOptionalSections:he,onFieldUpdate:TR,onComparableConcessionTransactionChange:jR,onCopyContractDateToAllComps:X,saleHistoryGetValue:C?_r:lt,saleHistoryGetSource:C?Ni:Tt,saleHistorySetValue:C?P:je,onSaleHistoryReorder:d5,onComplete:WF,onAdjustmentChange:(L,Y,K)=>c5(L,Y,K??0),onRemoveComp:L=>{Zg(L)},persistedAdjustments:C?Io:ne,gridMode:U?"str":"1004",enableUad36:C,uad36ReconciliationValue:Yt.reconciliation?.SalesComparisonValue?.value,uad36ReconciliationValueMode:Yt.salesComparisonGrid?.valueMode?.value,uad36ReconciliationFieldPresent:Object.prototype.hasOwnProperty.call(Yt.reconciliation??{},"SalesComparisonValue"),uad36ReconciliationHydrated:ha,onUad36ReconciliationValueChange:L=>Jt("reconciliation","SalesComparisonValue",L),onUad36ReconciliationValueModeChange:L=>Jt("salesComparisonGrid","valueMode",L),evalGridProfile:F,evalCustomComparisonFactors:_,onEvalCustomComparisonFactorsChange:$,subjectOccupancy:t.occupancy?.value,subjectUnitCount:t.numUnits?.value,onMapSnapshotChange:At,activeScenario:He?yl:void 0,pendingAdvisorApply:Eg,pen
53dingAdvisorApplyForceFields:gy,onAdvisorApplyConsumed:()=>{Ym(null),Vc(null)},assignmentId:r,effectiveDate:n,multiMethodSubject:dh.orchestratorSubject,multiMethodComps:dh.orchestratorComps,onOpenTimeWizard:ih?dh.openDrawer:void 0,runAdjustmentsButton:dh.button,adjustmentBar:dh.bar,toolbarExtraActions:EA,onNonSalesSlotCountChange:at,multiMethodCanRun:ih?dh.canRun:!0,advisorSuggestions:Uc?(()=>{const L={};return Uc.compSuggestions.forEach(Y=>{L[Y.compId]={},Y.adjustments.forEach(K=>{K.suppressed||(L[Y.compId][K.factor]={amount:K.suggestedAmount,rangeLow:K.rangeLow,rangeHigh:K.rangeHigh})})}),L})():null,onComparabilityChange:(L,Y)=>{qe(K=>{const te=K.selectedComps.map(we=>we.id===L||we.snapshotId===L?{...we,strComparability:Y}:we),q=L,ie=Zr.current.get(q);ie&&Zr.current.set(q,{...ie,strComparability:Y}),Array.from(Zr.current.entries()).forEach(([we,ve])=>{ve.compId===L&&Zr.current.set(we,{...ve,strComparability:Y})});const ee=Array.from(Zr.current.values());return setTimeout(()=>Ys.current?.(ee),0),{...K,selectedComps:te}})},onCompOrderChange:L=>{if(C&&Us!=="rental"&&r){ol(`/api/uad36/comparables/${encodeURIComponent(r)}/order`,{orderedItemIds:L},{headers:ho(r)}).then(()=>is(ee=>ee+1)).catch(ee=>console.error("[PropertyLab] Failed to persist UAD grid reorder:",ee));return}const Y=mu.current,K=new Map(Y.map(ee=>[ee.id,ee])),te=new Map(Y.filter(ee=>ee.snapshotId).map(ee=>[ee.snapshotId,ee])),q=L.map(ee=>K.get(ee)||te.get(ee)).filter(ee=>ee!==void 0),ie=q.map(ee=>ee.snapshotId||ee.id).filter(ee=>typeof ee=="string"&&ee.length>0);qe(ee=>({...ee,selectedComps:q})),r&&ie.length>0&&(async()=>{await ol(`/api/comps/select/${r}/order`,{orderedCompIds:ie})})().catch(we=>{we instanceof qo&&we.isAuthError?Ve({title:"Session Expired",description:"Please sign in again.",variant:"destructive"}):console.error("[PropertyLab] Failed to persist comp reorder:",we)})},onPropertyClick:L=>{const Y=re.selectedComps.find(q=>q.id===L.id||q.snapshotId===L.id),K=re.properties.find(q=>q.id===L.id||q.snapshotId===L.id),te=(Y?.mlsData?Y:null)||(K?.mlsData?K:null)||Y||Kr.find(q=>q.id===L.id||q.snapshotId===L.id);if(te)zn(Vb(te,!0));else{const q=L.photos||(L.photoUrl?[L.photoUrl]:[]);if(q.length>0||L.address){const ie=L.id==="subject"||L.isSubject,ee=Je,we=ht,ve=t.propertyType,Se=ve&&(ve.source==="User"||ve.isEdited===!0||ve.isConfirmed===!0)?ve.value:void 0,Qe=we?.numberOfUnitsTotal??we?.NumberOfUnitsTotal??ee?.numberOfUnitsTotal??ee?.NumberOfUnitsTotal,Nt=we?.buildingAreaTotal??we?.BuildingAreaTotal??ee?.buildingAreaTotal??ee?.BuildingAreaTotal??ee?.areaSemanticProvenance?.buildingAreaTotal,Ct=u.filter(Ht=>Ht.candidate?.unitCount!=null||Ht.candidate?.propertySubType).map(Ht=>({value:Ht.candidate?.unitCount??(/four[\s-]?plex|quad[\s-]?plex/i.test(Ht.candidate?.propertySubType||"")?4:/triplex/i.test(Ht.candidate?.propertySubType||"")?3:/duplex/i.test(Ht.candidate?.propertySubType||"")?2:0),source:"mls",label:[Ht.displayLabel||(Ht.mlsNumber?`MLS #${Ht.mlsNumber}`:void 0),Ht.date,Ht.listingStatus].filter(Boolean).join(" · ")||void 0})).filter(Ht=>Ht.value>0),va={id:L.id,snapshotId:L.id,address:L.address,city:L.city||"",state:L.state||"",zip:"",price:Number(L.fields.salePrice?.value)||Number(L.fields.salePrice?.mlsValue)||0,listPrice:ie?we?.listPrice??null:null,beds:ie?ee?.bedrooms??we?.bedrooms??null:Number(L.fields.bedrooms?.mlsValue)||null,baths:ie?ee?.bathrooms??we?.bathrooms??null:Number(L.fields.bathrooms?.mlsValue)||null,sqft:ie?ee?.squareFeet??we?.squareFeet??null:Number(L.fields.grossLivingArea?.mlsValue)||null,sqftPR:ie?ee?.squareFeet??null:null,lotSqft:ie?we?.lotSize??ee?.lotSize??null:null,lotSqftPR:ie&&ee?.lotSize?ee.lotSize:null,yearBuilt:ie?ee?.yearBuilt??we?.yearBuilt:Number(L.fields.yearBuilt?.mlsValue)||void 0,yearBuiltPR:ie?ee?.yearBuilt:void 0,propertyType:String(ie?Se??ee?.propertyType??we?.propertyType??c??"Unknown":L.fields.propertyType?.mlsValue||""),unitCount:ie?Qe??null:null,unitCountSource:ie?we?.numberOfUnitsTotal!=null||we?.NumberOfUnitsTotal!=null?"mls":ee?.numberOfUnitsTotal!=null||ee?.NumberOfUnitsTotal!=null?"public-record":void 0:void 0,unitCountAlternatives:ie?Ct:void 0,buildingAreaSqft:ie?Nt??null:null,buildingAreaSource:ie?we?.buildingAreaTotal!=null||we?.BuildingAreaTotal!=null?"mls":ee?.buildingAreaTotal!=null||ee?.BuildingAreaTotal!=null||ee?.areaSemanticProvenance?.buildingAreaTotal!=null?"public-record":void 0:void 0,style:ie?we?.style??ee?.style??null:null,stories:ie?void 0:null,garageSpaces:ie?we?.garageSpaces??(ee?.garage&&parseInt(String(ee.garage))||null):null,status:ie?J0(L.status)??"Unknown":L.status==="Sold"?"CLSD":L.status==="Active"?"ACTV":"PEND",photoUrl:L.photoUrl||q[0]||null,photos:q,photoCount:q.length,dom:ie?we?.daysOnMarket??0:0,coordinates:ie&&s?s:{lat:L.lat||0,lng:L.lng||0},isSelected:!1,saleDate:ie?we?.soldDate??ee?.lastSaleDate??null:null,pricePerSqft:ie?ee?.pricePerSqFt??null:void 0,mlsData:ie?di:void 0,publicRecordData:ie?us:void 0};zn(va)}}}}),bm&&e.jsx("div",{className:"mt-4 px-2","data-testid":"container-multi-method-tightness",children:e.jsx(lZ,{compliance:bm,acknowledged:If,onAcknowledgeChange:ym})})]})]}),He&&_i&&e.jsxs("div",{className:"fixed z-50 bg-white border border-slate-200 rounded-lg shadow-lg p-3 w-48",style:{left:_i.x,top:_i.y},"data-testid":"scenario-tag-popup",children:[e.jsx("p",{className:"text-xs font-medium text-slate-700 mb-2",children:"Assign to scenario:"}),["as-is","after-repaired","both"].map(L=>e.jsxs("button",{onClick:()=>{gu(te=>({...te,[_i.compId]:L}));const K=re.selectedComps.find(te=>te.id===_i.compId)?.snapshotId||_i.compId;r&&K&&ol(`/api/comps/select/${K}/${r}/scenario`,{scenarioTag:L}
53).catch(te=>console.error("[PropertyLab] Failed to persist scenario tag:",te)),Af(null)},className:`w-full text-left px-2 py-1.5 text-xs rounded hover:bg-slate-50 flex items-center gap-2 ${Gu[_i.compId]===L?"bg-slate-100 font-medium":""}`,"data-testid":`button-tag-${L}`,children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${L==="as-is"?"bg-[#0D3855]":L==="after-repaired"?"bg-[#E67E22]":"bg-gradient-to-r from-[#0D3855] to-[#E67E22]"}`}),L==="as-is"?"As-Is Only":L==="after-repaired"?"After-Repaired Only":"Both Scenarios"]},L)),e.jsx("button",{onClick:()=>Af(null),className:"w-full text-center text-xs text-slate-400 mt-1 hover:text-slate-600","data-testid":"button-close-tag-popup",children:"Cancel"})]}),He&&oo&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Wu(null)}),e.jsxs("div",{className:"fixed z-50 bg-white border border-slate-200 rounded-xl shadow-xl p-3 w-52",style:{left:Math.min(oo.x,window.innerWidth-220),top:Math.min(oo.y,window.innerHeight-200)},"data-testid":"scenario-picker-popup",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-700 mb-1",children:"Add comp to which scenario?"}),e.jsx("p",{className:"text-[10px] text-slate-400 mb-2",children:oo.property.address}),[{tag:"as-is",label:"As-Is",color:"bg-[#0D3855]",hoverBg:"hover:bg-blue-50"},{tag:"after-repaired",label:"After-Repaired",color:"bg-[#E67E22]",hoverBg:"hover:bg-orange-50"},{tag:"both",label:"Both Scenarios",color:"bg-gradient-to-r from-[#0D3855] to-[#E67E22]",hoverBg:"hover:bg-slate-50"}].map(({tag:L,label:Y,color:K,hoverBg:te})=>e.jsxs("button",{onClick:async()=>{const q=oo.property;Wu(null),await My.current(q,L)},className:`w-full text-left px-3 py-2 text-sm rounded-lg ${te} flex items-center gap-2.5 transition-colors`,"data-testid":`button-scenario-${L}`,children:[e.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${K} flex-shrink-0`}),Y]},L)),e.jsx("button",{onClick:()=>Wu(null),className:"w-full text-center text-xs text-slate-400 mt-2 pt-2 border-t hover:text-slate-600","data-testid":"button-cancel-scenario-picker",children:"Cancel"})]})]}),e.jsx(jT,{property:ln,open:!!ln,onClose:()=>{zn(null)},isLoading:!1,onSelect:vu?Cb:_a?Tb:(()=>{}),onDeselect:vu?Rb:_a?Zg:(()=>{}),isSelected:(vu?Ib:pu)(ln),onFocusOnMap:dA,orderId:r||null,onNext:()=>{const L=wp(ln);L>=0&&L<Nu.length-1&&Pf(Nu[L+1])},onPrev:()=>{const L=wp(ln);L>0&&Pf(Nu[L-1])},hasNext:(()=>{const L=wp(ln);return L>=0&&L<Nu.length-1})(),hasPrev:wp(ln)>0,currentIndex:(()=>{const L=wp(ln);return L>=0?L:void 0})(),totalCount:Nu.length}),wA]})}const u5=Kt.isReady===!0,p5=!U&&!ea&&!ma&&!Qt&&!u5&&Kt.status!=="idle"&&Kt.status!=="completed",$R=_e,BR=Kt.status==="failed"||Kt.status==="error";if(p5){const g=Kt.propertiesFound||0,I=Kt.propertiesProcessed||0,k=g>0&&I>0?Math.min(Math.round(I/g*100),99):0;return e.jsx("div",{className:"h-full flex flex-col bg-slate-100","data-testid":"property-lab",children:e.jsx("div",{className:"flex-1 flex items-center justify-center p-8","data-testid":"preload-loading-gate",children:e.jsx("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-lg border border-slate-200 p-8 text-center",children:BR?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-amber-50 flex items-center justify-center mx-auto mb-4",children:e.jsx(Di,{className:"w-7 h-7 text-amber-500"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-800 mb-2","data-testid":"preload-gate-title",children:"Data Loading Issue"}),e.jsx("p",{className:"text-sm text-slate-500 mb-6","data-testid":"preload-gate-message",children:"Some nearby sales data couldn't be loaded. You can still proceed — search results will be available, but some enhancements may be missing."}),e.jsx("button",{onClick:()=>tr(!0),className:"px-5 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors","data-testid":"preload-gate-proceed",children:"Continue to Property Lab"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-blue-50 flex items-center justify-center mx-auto mb-4",children:e.jsx(Hh,{className:"w-7 h-7 text-blue-500"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-800 mb-2","data-testid":"preload-gate-title",children:Kt.isStalled?"Taking longer than expected...":k>=90?"Almost ready!":"Preparing Property Lab"}),e.jsx("p",{className:"text-sm text-slate-500 mb-6 transition-opacity duration-500","data-testid":"preload-gate-message",children:Kt.isStalled?"The data loading process is running slower than usual. You can wait or proceed with the data available so far.":$R||"Searching MLS for nearby comps…"},Kt.currentStage||"init"),e.jsx("div",{className:"w-full bg-slate-100 rounded-full h-3 mb-2 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-500 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(k,3)}%`},"data-testid":"preload-gate-progress-bar"})}),e.jsx("p",{className:"text-xs text-slate-400 mb-6","data-testid":"preload-gate-percentage",children:k>0?`${k}% complete — ${I} of ${g} properties loaded`:g>0?`Found ${g} nearby comps — preparing details…`:"Discovering nearby properties…"}),e.jsx("button",{onClick:()=>tr(!0),className:"text-xs text-slate-400 hover:text-slate-600 underline underline-offset-2 transition-colors","data-testid":"preload-gate-skip",children:"Skip waiting and enter Property Lab"})]})})})})}return e.jsx(wo,{stepName:"Property Lab",orderId:r??void 0,context:()=>({source:"StepPropertyLab",activeStep:"property-lab",enableStr:U,propertyTypeFilter:Da,hasGeometricConstraint:Cf,strCompResultsCount:Ac.length,sortedPropertiesCount:Xr.length,strAggregatorLoading:yu,subjectCoordinates:s?{lat:s.lat,lng:s.lng}:null,assignmentId:r??null}),children:e.jsxs("div",{className:"h-full flex flex-col bg-slate-100","data-testid":"property-lab",children:[e.jsx("div",{"data-testid":"boundary-render-state","data-rendered-count":Cy?.rendered??"","data-requested-count":Cy?.requested??"","data-skipped-count":Cy?.skipped??"","data-style-ready":Cy?.styleReady?"true":"false","data-fallback-active":$C?"true":"false",hidden:!0,"aria-hidden":"true"}),e.jsx(P9,{searchFailure:PF,setSearchFailure:uh,setState:qe,handleSearchRef:Nr,searchInFlightRef:Qn,subjectAddressForReport:a,enableStr:U,isPreloading:Sa,preloadFailed:BR,preloadStatus:Kt,stageLabel:$R,strAggregatorLoading:yu,reviewingLock:Zs,exitReviewMode:Nm,handleUnlockMarket:XF,handleUnlockSubMarket:e5,lockedMarketCount:Gc,lockedSubMarketCount:Mi,lockedMarketPropertyCardsLength:Nn.length,lockedSubmarketPropertyCardsLength:mr.length}),e.jsx(X9,{marketLocked:Tr,handleMarketButtonClick:ZF,propertiesInArea:uR,subMarketLocked:Fr,handleSubmarketButtonClick:JF,subMarketPropertiesCount:AR,isLockingMarket:KF,isLockingSubMarket:QF,state:re,enableStr:U,showToolbarFilterPanel:Mu,setShowToolbarFilterPanel:hp,labViewMode:bs,setLabViewMode:ba,showMapPanel:ki,preFullscreenMapModeRef:bd,handleSortChange:XC,handleFilterBarChange:r5,sortedProperties:Xr,handleClearAllFilters:n5,comparisonDataSource:qn,setComparisonDataSource:gd,reviewingLock:Zs,radiusCircle:VC,handleRadiusChange:NF,userQuickPicks:ac,verifiedSubject:as,expandingFilters:DF,activeStatusCounts:pF,strRentalPool:pi,toolbarExtraActions:EA,onOpenM
53atchSettings:O&&E?Ot:void 0}),wA,e.jsx(xi,{open:ir,onOpenChange:zs,children:e.jsxs(bi,{className:"max-w-5xl max-h-[90vh] overflow-y-auto","data-testid":"dialog-match-settings",children:[e.jsxs($i,{children:[e.jsx(si,{children:"Match settings"}),e.jsx(pl,{children:"Rank the facts used to calculate Match. Missing subject or comparable data contributes a neutral score."})]}),e.jsxs("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(min(100%,340px),1fr))] gap-4",children:[e.jsx(kZ,{boostItems:pr,onBoostItemsChange:$e,onSave:R,onReset:()=>$e(G?.()||[]),embedded:!0}),e.jsxs("div",{className:"rounded-lg border border-slate-200 p-3","data-testid":"match-subject-summary",children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:"Subject data used for matching"}),e.jsx("p",{className:"mt-1 text-[11px] text-slate-500",children:"Verified facts take precedence, followed by available MLS, public-record, AI, and location data."}),e.jsx("div",{className:"mt-3 space-y-2",children:mO({verifiedSubject:as,propertyData:t,subjectCoordinates:s,subjectElsScore:_n,mlsData:di,publicRecordData:us}).facts.filter(g=>pr.some(I=>I.fieldId===g.fieldId)).map(g=>e.jsxs("div",{className:"rounded-md border border-slate-100 p-2 text-xs","data-testid":`match-subject-fact-${g.fieldId}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:g.available?"font-medium text-slate-700":"text-slate-400",children:g.label}),g.hasConflict&&e.jsx(kt,{variant:"outline",className:"border-amber-300 bg-amber-50 text-[9px] text-amber-700",children:"Sources differ"})]}),g.available?e.jsx("div",{className:"mt-1.5 space-y-1",children:g.candidates.map(I=>e.jsxs("div",{className:Q("flex items-center justify-between gap-2",I.usedForMatching?"font-semibold text-slate-900":"text-slate-500"),"data-testid":`match-subject-candidate-${g.fieldId}-${I.source.toLowerCase()}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(kt,{variant:"outline",className:"h-5 px-1.5 text-[9px]",children:I.source}),I.usedForMatching&&e.jsx("span",{className:"text-[9px] uppercase tracking-wide text-[#A18A60]",children:"Used for matching"})]}),e.jsx("span",{className:"tabular-nums",children:I.value})]},`${I.source}-${I.value}`))}):e.jsx("div",{className:"mt-1 italic text-slate-400",children:"Unavailable"})]},g.fieldId))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(De,{variant:"outline",onClick:()=>zs(!1),"data-testid":"button-cancel-match-settings",children:"Cancel"}),e.jsx(De,{onClick:()=>{E?.(pr),zs(!1)},"data-testid":"button-apply-match-settings",children:"Apply"})]})]})}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[bs!=="map"&&e.jsx("div",{style:{width:ki?`${100-Jp}%`:"100%"},className:"h-full flex flex-col bg-white flex-shrink-0",children:e.jsx(w9,{isPreloading:Sa,sortedProperties:Xr,headerPropertiesCount:jp?null:t5,appliedBoundaries:js,cachesPending:qa,cardsHydrating:!VN,heavyCachePending:jp,setAppliedBoundaries:bo,setBoundaryRenderWarning:Iy,setBoundaryRenderFallbackActive:HN,enableStr:U,propertyTypeFilter:Da,setPropertyTypeFilter:Ia,strProperties:pi,comparisonDataSource:qn,setComparisonDataSource:gd,showMapPanel:ki,onBack:h,handleProceedToCleanup:oR,strAggregatorLoading:yu,strCompResults:Ac,strRentalComps:ya,strAggregatorProviders:vb,labViewMode:bs,geometrySearchMeta:Mr,geometrySearchInFlight:Wt,geometrySearchEmpty:gs,hasDrawnShapes:xo,lastGeometrySearchRef:Sn,currentShapes:Ma,displayProperties:Nu,state:re,searchInFlightRef:Qn,hasCachedState:ma,shapesInitialized:Ea,subjectCoordinates:s,loadingPhase:um,preloadStageLabel:_e,isBgWidenLoading:$N,handleClickProperty:Pf,handleHoverProperty:eR,assignmentId:r,setShowToolbarFilterPanel:hp,handleSortChange:XC,columnSort:Bi,setColumnSort:xd,handleFocusPropertyOnMap:dA,subjectElsFactors:vc,handleElsOverride:jF,visibleColumns:Jd,setVisibleColumns:Ig,handleSaveColumnsAsDefault:Cg,showSelectedOnly:go,setShowSelectedOnly:Zd,subjectRowData:wa,aiAnalysisReady:fF,bgCqPollingComplete:LC,batchScoresLoaded:Wn,isResultsRefreshing:vR,selectionPending:NR,backgroundPinCount:Ep.filter(g=>g.type==="background-sale").length,enableUad36:C,compSelectionMode:Us,setCompSelectionMode:Ut?Kc:void 0,semanticOnlyIds:Sy??void 0,semanticSearchDegraded:mF&&typeof re.filters.remarksSearch=="string"&&re.filters.remarksSearch.trim().length>0,selectedCount:C&&Us==="rental"?Ss.length:dR,reportSlotsAvailable:C&&Us!=="rental"?ar?.available??Math.max(0,vt-Te-dR):void 0,reportGridCount:C&&Us!=="rental"?ar?.gridCount:void 0,isCompSelected:C&&Us==="rental"?Ib:pu,selectedCompIdSet:C&&Us==="rental"?Of:ro,handleSelectProperty:C&&Us==="rental"?Cb:_a?Tb:(()=>{}),handleDeselectProperty:C&&Us==="rental"?Rb:_a?Zg:(()=>{})})},"property-panel"),bs!=="map"&&ki&&e.jsx("div",{className:"w-1.5 cursor-col-resize bg-slate-200 hover:bg-blue-400 active:bg-blue-500 transition-colors flex-shrink-0 relative group","data-testid":"split-resize-handle",onMouseDown:g=>{g.preventDefault(),_c.current={startX:g.clientX,startPercent:Jp};const I=g.currentTarget.parentElement;if(!I)return;const k=I.getBoundingClientRect().width,L=K=>{if(!_c.current)return;const q=(K.clientX-_c.current.startX)/k*100,ie=Math.min(80,Math.max(30,_c.current.startPercent-q));hf(ie)},Y=()=>{_c.current=null,document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",Y)},children:e.jsx("div",{className:"absolute inset-y-0 left-1/2 -translate-x-1/2 w-0.5 bg-slate-400 group-hover:bg-blue-500 transition-colors"})},"resize-handle"),Ol&&e.jsx("div",{style:{width:bs==="map"?"100%":`${Jp}%`,display:ki?void 0:"none"},className:"overflow-hidden flex flex-col",children:e.jsxs("div",{className:"relative flex-1 min-h-0",children:[e.jsx("div",{className:"absolute top-3 left-3 z-30 w-[280px]","data-testid":"map-search-overlay",children:e.jsx(M$,{subjectAddress:a,subjectState:i,appliedBoundaries:js,onAddBoundary:CA,onRemoveBoundary:RA,onFiltersChange:s5,onSearch:nR,isSearching:re.isLoading,currentFilters:{beds:re.filters.minBeds,baths:re.filters.minBaths,minPrice:re.filters.minPrice,maxPrice:re.filters.maxPrice,minSqft:re.filters.minSqft,maxSqft:re.filters.maxSqft,propertyType:re.filters.propertyType,status:re.filters.status,monthsBack:re.filters.monthsBack,style:re.filters.styleSelection,basementCategories:re.filters.basementCategories,remarksSearch:re.filters.remarksSearch},radiusCircle:VC,onClearRadius:OF,expandingRadius:kF,hasDrawnPolygon:Ma.polygons.length>0,onClearPolygon:LF,boundaryOnly:!0,savedSearches:Km,onSaveSearch:nF,onLoadSearch:iF,onDeleteSearch:oF,isSavingSearch:Zm,orderMarketStates:dm,librarySearches:xr,orderId:r,onApplyOrderState:wC,onApplyLibrarySearch:PC,onAddToLibrary:lF,onDeleteLibrarySearch:cF,boundaryCounts:a5})}),e.jsx(pL,{fallbackMessage:"Map failed to load — click retry to try again.",context:()=>{let g={initialized:!1};try{g=cA.current?.getMapStatus?.()??{initialized:!1}}catch{}return{source:"MapboxAppraiserMap",activeStep:"property-lab",mapStatus:g,mapLocations:Ep.length,allCompLocations:Ny.length,allCachedSales:Kr.length,drawnAreaPropertyIds:qt?.length??null,hasDrawnShapes:xo,shapes:{polygons:Ma.polygons.length,circles:Ma.circles.length},appliedBoundaries:js.length,subjectCoordinates:s?{lat:s.lat,lng:s.lng}:null,assignmentId:r??null}},children:e.jsx(qV,{ref:cA,center:w,zoom:Bn,locations:Ep,allCompLocations:Ny,activePropertyTypeFilters:gF,activeGeomFilters:xF,hoveredLocationId:re.hoveredPropertyId,onHoverLocation:eR,onMarkerClick:lA,onSelectProperty:pA,onDeselectProperty:mA,subjectMarker:s,showSearchRadius:$C,searchRadiusMiles:re.marketDefinition?.radiusMiles||1,enableDrawing:!0,enableLayers:!0,allSalesData:Kr,onShapesChange:Ty,onRequestLiveCount:vF,onMapsLoaded:TF,focusLocation:Sd,appliedBoundaries:js,isSearching:(Wt||fs)&&xo,autoInitialRadius:!1,initialRadiusPresetMiles:Bg,onShapesUpdated:$F,externalShapes:Ma,onLayerBoundarySelect:AF,onPopout:qF,isPopoutOpen:Yn.isPopoutOpen,onBoundaryRenderState:CF})}),U&&Cf&&!yu&&Ac.length===0&&e.jsxs("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-30 max-w-sm rounded-lg border border-slate-200 bg-white/95 backdrop-blur px-4 py-3 shadow-lg flex items-start gap-2 pointer-events-none",role:"status","data-testid":"map-str-empty-state",children:[e.jsx(lp,{className:"h-5 w-5 shrink-0 mt-0.5 text-slate-400"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-medium text-slate-700","data-testid":"text-map-str-empty-title",children:"No short-term rentals found in this area"}),e.jsx("div",{className:"mt-0.5 text-xs text-slate-500","data-testid":"text-map-str-empty-hint",children:"Try expanding the boundary."})]})]}),GN&&GN!==YV&&e.jsxs("div",{className:"absolute top-3 right-3 z-30 max-w-sm rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-xs text-amber-900 shadow-md flex items-start gap-2",role:"status","data-testid":"banner-boundary-render-warning",children:[e.jsx(Ns,{className:"h-4 w-4 shrink-0 mt-0.5 text-amber-600"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium","data-testid":"text-boundary-warning-title",children:"Boundary outline unavailable"}),e.jsx("div",{className:"mt-0.5","data-testid":"text-boundary-warning-message",children:GN})]}),e.jsx("button",{type:"button",onClick:()=>Iy(null),className:"text-amber-700 hover:text-amber-900 leading-none","aria-label":"Dismiss boun
53dary warning","data-testid":"button-dismiss-boundary-warning",children:"×"})]}),e.jsxs("div",{className:"absolute bottom-4 left-4 right-4 flex items-center justify-between pointer-events-none z-20",children:[e.jsxs(De,{size:"sm",variant:"outline",onClick:h,className:"gap-1.5 h-8 bg-white shadow pointer-events-auto","data-testid":"button-back",children:[e.jsx(yN,{className:"w-3.5 h-3.5"}),"Back"]}),e.jsx("div",{className:"flex items-center gap-3 pointer-events-auto mr-12",children:e.jsxs(De,{size:"sm",onClick:()=>{oR()},disabled:Tp,className:"gap-1.5 h-8 bg-green-600 hover:bg-green-700 shadow","data-testid":"button-continue",children:[Tp?e.jsx(za,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Zp,{className:"w-3.5 h-3.5"}),Tp?"Preparing grid…":"Next"]})})]})]})},"map-container")]}),e.jsx(jT,{property:ln,open:!!ln,onClose:()=>{zn(null)},isLoading:!1,onSelect:vu?Cb:Tb,onDeselect:vu?Rb:Zg,isSelected:(vu?Ib:pu)(ln),onFocusOnMap:dA,orderId:r||null,onNext:()=>{const g=wp(ln);g>=0&&g<Nu.length-1&&Pf(Nu[g+1])},onPrev:()=>{const g=wp(ln);g>0&&Pf(Nu[g-1])},hasNext:(()=>{const g=wp(ln);return g>=0&&g<Nu.length-1})(),hasPrev:wp(ln)>0,currentIndex:(()=>{const g=wp(ln);return g>=0?g:void 0})(),totalCount:Nu.length}),He&&oo&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Wu(null)}),e.jsxs("div",{className:"fixed z-50 bg-white border border-slate-200 rounded-xl shadow-xl p-3 w-52",style:{left:Math.min(oo.x,window.innerWidth-220),top:Math.min(oo.y,window.innerHeight-200)},"data-testid":"scenario-picker-popup",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-700 mb-1",children:"Add comp to which scenario?"}),e.jsx("p",{className:"text-[10px] text-slate-400 mb-2 truncate",children:oo.property.address}),[{tag:"as-is",label:"As-Is",color:"bg-[#0D3855]",hoverBg:"hover:bg-blue-50"},{tag:"after-repaired",label:"After-Repaired",color:"bg-[#E67E22]",hoverBg:"hover:bg-orange-50"},{tag:"both",label:"Both Scenarios",color:"bg-gradient-to-r from-[#0D3855] to-[#E67E22]",hoverBg:"hover:bg-slate-50"}].map(({tag:g,label:I,color:k,hoverBg:L})=>e.jsxs("button",{onClick:async()=>{const Y=oo.property;Wu(null),await My.current(Y,g)},className:`w-full text-left px-3 py-2 text-sm rounded-lg ${L} flex items-center gap-2.5 transition-colors`,"data-testid":`button-scenario-${g}`,children:[e.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${k} flex-shrink-0`}),I]},g)),e.jsx("button",{onClick:()=>Wu(null),className:"w-full text-center text-xs text-slate-400 mt-2 pt-2 border-t hover:text-slate-600","data-testid":"button-cancel-scenario-picker",children:"Cancel"})]})]}),e.jsx(b9,{isSubjectReportOpen:hu,setIsSubjectReportOpen:th,subjectAddress:a,listingDetails:ht,propDetails:Je,isLoadingSubjectData:it,showMarketModal:gc,setShowMarketModal:zm,marketLocked:Tr,subMarketLocked:Fr,lockedUrarStats:bf,urarStats:Ab,lockedForm1004mcStats:rm,form1004mcStats:SF,handleLockMarket:gA,handleLockSubMarket:xA,isLoading:re.isLoading,propertiesInArea:uR,subMarketPropertiesCount:AR,neighborhoodInfo:el,setNeighborhoodInfo:Jn,setNeighborhoodAiGenerated:Ei,onNeighborhoodAiGenerated:b,onUrarStatsChange:yF,parsedSubjectCity:BN,subjectState:i,radiusMiles:re.marketDefinition?.radiusMiles,isGeneratingNeighborhood:Yc,neighborhoodAiGenerated:su,showAdjustModal:gf,setShowAdjustModal:Gn,adjustModalTab:Nd,setAdjustModalTab:Fu,avmMarketLocked:fe,avmSubMarketLocked:be,previousTab:tu,setRightPanelTab:hl,avmResults:Fn,advisorData:Uc,advisorLoading:eu,fetchAdvisorData:YF,lockedTimeAdjRate:ec,verifiedSubject:as,assignmentId:r,comparisonDataSource:qn,lockedSubmarketSalesData:Ad,lockedMarketSalesData:fl,activeUtilityBands:Rp,marketContext:QN,lockedMarketCount:Gc,lockedSubMarketCount:Mi,lockedMarketResultIds:to,lockedSubmarketResultIds:Gi,subjectZipCode:l,selectedComps:re.selectedComps,setPendingAdvisorApply:g=>tm(g),showDerivationPanel:zi,setShowDerivationPanel:em,derivationState:Bm,setDerivationState:xb})]})})}function Y0(t){return`cachedLabState__user_${t}`}const pI="cachedLabState";function xJ({progress:t,userId:a}){const s=p=>t.find(u=>u?.stepKey===p)??null,r=s(pI),n=r?.stepData?.cachedLabState??null,i=a?s(Y0(a)):null,l=i?.stepData?.cachedLabState??null;
53let c=null,d=null;if(n&&(c=n,d="step"),l){const p=NO(i?.stepData?.savedAt),u=NO(r?.stepData?.savedAt);(!c||p>=u)&&(c=l,d="per-user")}return{snapshot:c,source:d}}function NO(t){if(!t)return 0;const a=Date.parse(t);return Number.isNaN(a)?0:a}function UM(t){return Array.isArray(t)?t.map(a=>{const{polygon:s,...r}=a;return r}):[]}function bJ(t){if(!Array.isArray(t))return[];const a=[];for(const s of t)!s?.id||!s.polygon||a.push({boundaryId:s.id,boundaryType:s.type??null,polygon:s.polygon});return a}function yJ(t){if(!t||typeof t!="object")return!1;const a=t;return a.type!=="Polygon"&&a.type!=="MultiPolygon"?!1:Array.isArray(a.coordinates)}function GS(t,a){if(!Array.isArray(t)||t.length===0)return t??[];if(!Array.isArray(a)||a.length===0)return t;const s=new Map;for(const r of a)r?.boundaryId&&yJ(r.polygon)&&s.set(r.boundaryId,r.polygon);return t.map(r=>{if(r?.polygon||!r?.id)return r;const n=s.get(r.id);return n?{...r,polygon:n}:r})}function SJ(t){return!t||!Array.isArray(t.appliedBoundaries)||t.appliedBoundaries.length===0?t:{...t,appliedBoundaries:UM(t.appliedBoundaries)}}function $j(t,a,s=new Date){const r=UM(t.appliedBoundaries??[]),n={...t,appliedBoundaries:r},i=bJ(t.appliedBoundaries??[]);return{saveProgress:{stepKey:Y0(a),stepData:{cachedLabState:n,savedAt:s.toISOString()}},saveBoundaryGeometries:{items:i}}}function Dn(t,a){const s=t[a]?.manualValue;return s==null?"":String(s).trim()}function HS(t,a){return Dn(t,a).split("|").map(s=>s.trim()).filter(Boolean)}function vJ(t){const a={},s=HS(t,"location");if(s.includes("BodyOfWater")){const m=Dn(t,"BodyOfWaterType");if(m&&(a.BodyOfWaterType=m,m==="Other")){const f=Dn(t,"BodyOfWaterTypeOtherDescription");f&&(a.BodyOfWaterTypeOtherDescription=f)}const h=Dn(t,"PrivateAccessIndicator");if(h&&(a.PrivateAccessIndicator=h),h==="true"){const f=Dn(t,"BodyOfWaterName");f&&(a.BodyOfWaterName=f);const v=Dn(t,"WaterAccessDepthType");if(v&&(a.WaterAccessDepthType=v,v==="Other")){const x=Dn(t,"WaterAccessDepthTypeOtherDescription");x&&(a.WaterAccessDepthTypeOtherDescription=x)}const S=Dn(t,"WaterFrontageTotalLengthLinearMeasure");S&&(a.WaterFrontageTotalLengthLinearMeasure=S);const N=Dn(t,"WaterfrontFeatureType");if(N){if(a.WaterfrontFeatureType=N,N.split("|").includes("Other")){const x=Dn(t,"WaterfrontFeatureTypeOtherDescription");x&&(a.WaterfrontFeatureTypeOtherDescription=x)}if(N==="None"){const x=Dn(t,"WaterfrontDevelopmentRightsIndicator");x&&(a.WaterfrontDevelopmentRightsIndicator=x)}}}}if(s.includes("Other")){const m=Dn(t,"SiteInfluenceTypeOtherDescription");m&&(a.SiteInfluenceTypeOtherDescription=m)}const r=Rm(Dn(t,"view"));r.forEach((m,h)=>{const f=kL(h),v=Dn(t,f.range);if(v&&(a[f.range]=v,v==="Other")){const N=Dn(t,f.rangeOther);N&&(a[f.rangeOther]=N)}const S=Dn(t,f.impact);if(S&&(a[f.impact]=S),m==="Other"){const N=Dn(t,"viewOtherDescription");N&&(a.viewOtherDescription=N)}});const n=Dn(t,Av);n&&r.includes(n)&&(a[Av]=n);const i=HS(t,"pool");i.length>0&&(a.AmenityType_WaterFeatures=i.join("|"));const l=HS(t,"porchPatioDeck");l.length>0&&(a.AmenityType_OutdoorLiving=l.join("|"));const c=Dn(t,"basementAccess");t.basementAccess?.selectedSource==="manual"&&c&&(a.BelowGradeExteriorAccessType=c);const d=[{enumKey:"design",descKey:"designOtherDescription",manualOnly:!0},{enumKey:"heatingType",descKey:"heatingOtherDescription"},{enumKey:"heatingFuel",descKey:"heatingFuelOtherDescription"},{enumKey:"cooling",descKey:"coolingOtherDescription"}];for(const m of d){if(m.manualOnly&&t[m.enumKey]?.selectedSource!=="manual"||Dn(t,m.enumKey)!=="Other")continue;const h=Dn(t,m.descKey);h&&(a[m.descKey]=h)}for(const m of["interiorQuality","interiorCondition","exteriorQuality","exteriorCondition"]){const h=Dn(t,m);h&&(a[m]=h)}const p=Dn(t,"garageCarport");p&&(a.garageCarport=p);const u=HS(t,"functionalUtility");if(u.length>0&&(a.FunctionalIssueType=u.join("|"),u.includes("Other"))){const m=Dn(t,"functionalIssueOtherDescription");m&&(a.FunctionalIssueTypeOtherDescription=m)}if(Dn(t,"efficiencyRatingExists")==="Yes"){const m=Dn(t,"efficiencyRatingName");m&&(a.EfficiencyRatingName=m);
53const h=Dn(t,"efficiencyRatingScore");h&&(a.EfficiencyRatingScoreValue=h)}if(Dn(t,"greenCertificationExists")==="Yes"){const m=Dn(t,"greenCertificationName");m&&(a.GreenCertificationName=m);const h=Dn(t,"greenCertificationLevel");h&&(a.GreenCertificationLevelName=h)}if(Dn(t,"renewableEnergyExists")==="Yes"){const m=Dn(t,"renewableEnergyType");m&&(a.RenewableEnergyComponentType=m)}return a}function NJ(t){if(t.heatingCooling?.selectedSource)return null;const a=t.heatingType?.manualValue??t.heatingFuel?.manualValue,s=t.cooling?.manualValue,r=a==null?"":String(a).trim(),n=s==null?"":String(s).trim();return!r&&!n?null:`${r};${n}`}function AJ(t){const a=t&&typeof t=="object"&&"value"in t?t.value:t;if(a==null||a==="")return null;if(a===!0)return!0;if(a===!1)return!1;const s=String(a).trim().toLowerCase();return s==="true"||s==="yes"?!0:s==="false"||s==="no"?!1:null}function mI(t,a,s,r,n,i,l){const c=t[s];return c?.selectedSource==="manual"&&c.manualValue!=null?c.manualValue:(c?.selectedSource==="ins"&&i!=null,c?.selectedSource==="ai"&&l!=null,c?.selectedSource==="mls"&&r!=null?r:c?.selectedSource==="pr"&&n!=null?n:a==="public-record"?n??r:r??n)}function WS(t){if(t==null||t==="")return{full:null,half:null};const a=parseFloat(String(t));if(!Number.isFinite(a))return{full:null,half:null};const s=Math.floor(a);return{full:s,half:a-s>.01?1:0}}function jJ(t,a,s,r){const n=mI(t,a,"bathsFull",s?.fullBathrooms??WS(s?.bathrooms).full,r?.fullBathrooms??WS(r?.bathrooms).full),i=mI(t,a,"bathsHalf",s?.halfBathrooms??WS(s?.bathrooms).half,r?.halfBathrooms??WS(r?.bathrooms).half),l=n!=null&&n!==""||i!=null&&i!=="",c=!!(t.bathsFull?.selectedSource||t.bathsHalf?.selectedSource),d=!!t.baths?.selectedSource;return c||!d&&l?(parseInt(String(n??0),10)||0)+.5*(parseInt(String(i??0),10)||0):null}function TJ(t,a,s,r){const n={location:[s?.siteInfluence||s?.locationInfluence,r?.siteInfluence||r?.locationInfluence],attachedDetached:[s?.attachmentType||s?.attachedDetached,r?.attachmentType||r?.attachedDetached],constructionMethod:[s?.constructionMethod||s?.constructionType,r?.constructionMethod||r?.constructionType]},i={};for(const l of["location","attachedDetached","constructionMethod"]){const c=t[l];if(c?.selectedSource)if(c.selectedSource==="manual"){const d=c.manualValue;d!=null&&String(d).trim()!==""&&(i[l]=String(d).trim())}else{const[d,p]=n[l],u=mI(t,a,l,d,p);if(u!=null&&String(u).trim()!==""){const m=Em(l,String(u));i[l]=m?.value??String(u).trim()}}}return i}function IJ(t){if(t)switch(t){case"MLS":return"MLS";case"PublicRecord":return"PR";case"AI":case"Derived":return"AI";case"Auto":return"AI";case"User":return"INS";case"Manual":return"INS";case"Echo":return;case"Zoneomics":return;default:return}}function CJ(t,a,s,r,n,i="mls"){return t!=null&&t!==""?"ins":n!=null&&n!==""?"ai":r==="public-record"&&s!=null&&s!==""?"pr":r==="mls"&&a!=null&&a!==""||a!=null&&a!==""?"mls":s!=null&&s!==""?"pr":i}function RJ({subjectAddress:t,subjectCity:a,subjectState:s,subjectZip:r,subjectData:n,propertyData:i,propMixData:l,inspectionImport:c,subjectPhotos:d,subjectCoordinates:p,initialIntent:u,onSave:m,showVerifyButton:h=!1,onVerifyComplete:f,isVerified:v=!1,activeAddOns:S,enableDualScenario:N,afterRepairedSubject:x,onAfterRepairedSubjectChange:y,renovationState:b,onRenovationStateChange:j,subjectQCLoading:T,subjectNormalizedGla:O,subjectGlaConfidence:E,subjectGlaNormNote:R,orderId:G,csvSubjectValues:U,enableUad36:C=!1,isActive:F,onRegisterUnloadFlush:A,externalSelectionEdits:M,step2SiteGridSeed:B}){const{profile:oe}=ly();hc();const ae=o.useMemo(()=>new Set(i$(S||[])),[S]),[D,_]=o.useState(u?.baselineSource||"mls"),[$,z]=o.useState(0),[V,le]=o.useState(0),W=o.useCallback((it,Je)=>{z(it),le(Je)},[]),[me,Z]=o.useState(u?.fieldSelections||{}),pe=o.useRef(0);o.useEffect(()=>{const it=M;!it||it.seq<=pe.current||(pe.current=it.seq,Object.keys(it.selections).length!==0&&Z(Je=>({...Je,...it.selections})))},[M]),o.useEffect(()=>{B&&Z(it=>{const Je={...it};let ht=!1;for(const[Kt,Sa]of Object.entries(B)){if(Sa==null||Sa==="")continue;const Qt=it[Kt];Qt?.manualValue!=null&&Qt.manualValue!==""||(Je[Kt]={...Qt??{},selectedSource:"manual",manualValue:String(Sa)},ht=!0)}return ht?Je:it})},[B]);const[se,fe]=o.useState("all"),[ue,be]=o.useState(v),[H,ye]=o.useState(null),[de,ge]=o.useState(!1),[Be,He]=o.useState("as-is"),[Ie,ce]=o.useState(b?.analysis||null),[Pe,We]=o.useState(!1),[Re,ne]=o.useState(b?.uploadedFileName||null),Me=o.useRef(null),[lt,Tt]=o.useState({}),{data:je}=Vr({queryKey:[`/api/uad36/prefill/${G}`,"inspection-manifest"],queryFn:()=>Zn(`/api/uad36/prefill/${G}`),enabled:!!G&&!!C,staleTime:3e4}),Le=o.useMemo(()=>AJ(je?.sections?.subjectProperty?.HomeownerResponsibleForExteriorMaintenanceIndicator),[je]),[ut,st]=o.useState([]),Xt=o.useRef(!1),[ua,Oa]=o.use
53State(!1),Xa=o.useRef(0);o.useEffect(()=>{if(!G){Xt.current=!0,Oa(!0);return}Xt.current=!1,Oa(!1);const it=++Xa.current;let Je=!1;return(async()=>{try{const ht=await fetch(`/api/orders/${G}/sales-grid-custom-rows`);if(!ht.ok)throw new Error(`HTTP ${ht.status}`);const Kt=await ht.json();if(Je||Xa.current!==it)return;const Sa=Array.isArray(Kt?.customRows)?Kt.customRows.map(Qt=>{if(!Qt||typeof Qt.id!="string"||typeof Qt.label!="string")return null;const ea=Qt.source==="catalog"?"catalog":"custom";return{id:Qt.id,label:Qt.label,source:ea,rowId:typeof Qt.rowId=="string"?Qt.rowId:void 0}}).filter(Boolean):[];st(C?IE(Sa):Sa)}catch(ht){console.warn("[StepCompIntent] Failed to load custom rows:",ht)}finally{!Je&&Xa.current===it&&(Xt.current=!0,Oa(!0))}})(),()=>{Je=!0}},[G]),Fx({enabled:!!G,scopeId:G,isHydrated:()=>Xt.current,label:"[StepCompIntent] custom rows",persist:()=>fetch(`/api/orders/${G}/sales-grid-custom-rows`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({customRows:C?IE(ut):ut}),keepalive:!0}),deps:[G,ut,C]});const qa=o.useMemo(()=>({condition:"condition",quality:"quality",gla:"gla",bedrooms:"beds",bathrooms:"baths",basementFinishedSqft:"basement",garageSpaces:"garage",heatingCooling:"heatingCooling",energyEfficient:"energyEfficient",functionalUtility:"functionalUtility",porchPatioDeck:"porchPatioDeck",pool:"pool"}),[]),os=o.useMemo(()=>{const it={};return x&&Object.entries(x).forEach(([Je,ht])=>{const Kt=qa[Je]||Je;ht!=null&&ht!==""&&(it[Kt]=ht)}),it},[x,qa]),ya=o.useCallback((it,Je,ht)=>{if(Tt(Kt=>({...Kt,[it]:{selectedSource:Je,manualValue:Je==="manual"?ht:Kt[it]?.manualValue}})),Je==="manual"&&ht!=null&&y){const Kt={};Object.entries(qa).forEach(([Qt,ea])=>{Kt[ea]=Qt});const Sa=Kt[it]||it;y({...x||{},[Sa]:ht})}},[x,y,qa]);o.useEffect(()=>{j&&j({analysis:Ie,uploadedFileName:Re})},[Ie,Re,j]);const At=l?.listingDetails||{},Fe=l?.propertyDetails||{};o.useEffect(()=>{if(!p?.lat||!p?.lng||H!==null||de)return;(async()=>{ge(!0);try{const Je=new URLSearchParams({lat:String(p.lat),lng:String(p.lng)}),ht=await fetch(`/api/els/subject?${Je}`);if(ht.ok){const Kt=await ht.json();Kt.success&&Kt.score!==void 0&&ye(Kt.score)}}catch(Je){console.warn("[StepCompIntent] Failed to fetch subject ELS:",Je)}finally{ge(!1)}})()},[p,H,de]);const Oe=o.useCallback((it,Je,ht)=>{Z(Kt=>({...Kt,[it]:{...Kt[it],selectedSource:Je,manualValue:Je==="manual"?ht:Kt[it]?.manualValue}}))},[]);o.useCallback((it,Je,ht,Kt,Sa,Qt="mls")=>me[it]?.selectedSource?me[it].selectedSource:CJ(Je,ht,Kt,D,Sa,Qt),[me,D]);const rt=(it,Je,ht,Kt,Sa)=>{if((it?.source==="User"||it?.isEdited)&&it?.value!=null&&it.value!=="")return{value:Sa?Sa(it.value):String(it.value),source:"INS",mlsVal:Je,prVal:ht};if(D==="public-record"){if(ht!=null&&ht!=="")return{value:Sa?Sa(ht):String(ht),source:"PR",mlsVal:Je,prVal:ht};if(Je!=null&&Je!=="")return{value:Sa?Sa(Je):String(Je),source:"MLS",mlsVal:Je,prVal:ht}}else{if(Je!=null&&Je!=="")return{value:Sa?Sa(Je):String(Je),source:"MLS",mlsVal:Je,prVal:ht};if(ht!=null&&ht!=="")return{value:Sa?Sa(ht):String(ht),source:"PR",mlsVal:Je,prVal:ht}}return it?.value!=null&&it.value!==""&&it.value!==0?{value:Sa?Sa(it.value):String(it.value),source:IJ(it.source),mlsVal:Je,prVal:ht}:Kt!=null&&Kt!==""?{value:Sa?Sa(Kt):String(Kt),source:void 0,mlsVal:Je,prVal:ht}:{value:void 0,source:void 0,mlsVal:Je,prVal:ht}};rt(i?.gla,At.squareFeet,Fe.squareFeet,n?.gla,it=>`${parseInt(String(it).replace(/,/g,"")).toLocaleString()} sf`),rt(i?.bedrooms,At.bedrooms,Fe.bedrooms,n?.beds),rt(i?.bathrooms,At.bathrooms,Fe.bathrooms,n?.baths),rt(i?.yearBuilt,At.yearBuilt,Fe.yearBuilt,n?.yearBuilt),rt(i?.lotSize,At.lotSize||At.lotSizeSquareFeet,Fe.lotSize||Fe.lotSizeSquareFeet,n?.lotSize,it=>{const Je=parseInt(String(it).replace(/[^0-9]/g,""));return Je>0?`${Je.toLocaleString()} sf`:""}),rt(i?.designStyle,At.style,Fe.style,n?.style),rt(i?.garageCars,At.garageSpaces,Fe.garageSpaces,(n?.gla,void 0),it=>it?`${it} car`:"");const $t=i?.basementArea,na=$t?.value&&Number($t.value)!==0&&String($t.value)!=="0"&&String($t.value).trim()!=="";rt(na?$t:null,At.basement||(At.basementSqFt?`${At.basementSqFt} sf`:null),Fe.basement||(Fe.basementSqFt?`${Fe.basementSqFt} sf`:null),void 0);
53const zt=(it,Je,ht,Kt,Sa)=>{const Qt=me[it];return Qt?.selectedSource==="manual"&&Qt.manualValue!=null?Qt.manualValue:Qt?.selectedSource==="ins"&&Kt!=null?Kt:Qt?.selectedSource==="ai"&&Sa!=null?Sa:Qt?.selectedSource==="mls"&&Je!=null?Je:Qt?.selectedSource==="pr"&&ht!=null?ht:D==="public-record"?ht??Je:Je??ht},Ua=o.useCallback(async it=>{We(!0),ne(it.name);try{const Je=new FormData;Je.append("file",it);const ht={},Kt=zt("gla",At.squareFeet,Fe.squareFeet);Kt&&(ht.gla=Kt);const Sa=zt("beds",At.bedrooms,Fe.bedrooms);Sa&&(ht.bedrooms=Sa);const Qt=zt("baths",At.bathrooms,Fe.bathrooms);Qt&&(ht.bathrooms=Qt);const ea=zt("condition",void 0,void 0,i?.condition?.source==="User"?i.condition.value:void 0,i?.condition?.source==="Derived"?i.condition.value:void 0);ea&&(ht.condition=ea);const tr=zt("quality",void 0,void 0,i?.quality?.source==="User"?i.quality.value:void 0,i?.quality?.source==="Derived"?i.quality.value:void 0);tr&&(ht.quality=tr),Je.append("currentSubjectData",JSON.stringify(ht));const ir=await fetch("/api/renovation/analyze",{method:"POST",body:Je});if(!ir.ok){const pr=await ir.text();ce({success:!1,summary:"",suggestions:[],scopeItems:[],error:`Server error (${ir.status}): ${pr}`});return}const zs=await ir.json();if(ce(zs),zs.success&&zs.suggestions?.length>0&&y){const pr={...x||{}};zs.suggestions.forEach($e=>{pr[$e.fieldName]=$e.suggestedValue}),y(pr)}}catch(Je){console.error("[StepCompIntent] Renovation analysis failed:",Je),ce({success:!1,summary:"",suggestions:[],scopeItems:[],error:"Upload failed. Please try again."})}finally{We(!1)}},[At,Fe,i,zt,x,y]),Ce=o.useCallback(()=>{const it=zt("gla",At.squareFeet,Fe.squareFeet,i?.gla?.source==="User"?i.gla.value:void 0),Je=zt("beds",At.bedrooms,Fe.bedrooms,i?.bedrooms?.source==="User"?i.bedrooms.value:void 0),ht=jJ(me,D,At,Fe),Kt=zt("baths",At.bathrooms,Fe.bathrooms,i?.bathrooms?.source==="User"?i.bathrooms.value:void 0),Sa=ht??Kt,Qt=zt("yearBuilt",At.yearBuilt,Fe.yearBuilt,i?.yearBuilt?.source==="User"?i.yearBuilt.value:void 0),ea=zt("lotSize",At.lotSize||At.lotSizeSquareFeet,Fe.lotSize||Fe.lotSizeSquareFeet,i?.lotSize?.source==="User"?i.lotSize.value:void 0),tr=String(me.garageCarport?.manualValue??"").trim();let ir;if(tr!==""){let Ka=0;for(const Ee of tr.split(";")){const dt=Ee.trim().match(/^(\d+)/);dt&&(Ka+=parseInt(dt[1],10))}ir=Ka}else ir=zt("garage",At.garageSpaces,Fe.garageSpaces,i?.garageCars?.source==="User"?i.garageCars.value:void 0);const zs=me.basementFinishedSqft?.manualValue,pr=me.basementUnfinishedSqft?.manualValue,$e=zs!=null&&zs!==""||pr!=null&&pr!=="",Ot=parseInt(String(zs??0),10)||0,_e=parseInt(String(pr??0),10)||0,ma=$e?Ot+_e:zt("basement",At.basementSqFt,Fe.basementSqFt,i?.basementArea?.source==="User"?i.basementArea.value:void 0),pt=zt("quality",void 0,void 0,i?.quality?.source==="User"?i.quality.value:void 0,i?.quality?.source==="Derived"?i.quality.value:void 0)||"Q3",re=zt("condition",void 0,void 0,i?.condition?.source==="User"?i.condition.value:void 0,i?.condition?.source==="Derived"?i.condition.value:void 0)||"C3",qe=zt("design",At.style||null,Fe.style||null,i?.designStyle?.source==="User"?i.designStyle.value:void 0),Ze=typeof qe=="string"&&qe.includes(";")?qe.split(";")[0]:qe,It=typeof qe=="string"&&qe.includes(";")?parseInt(qe.split(";")[1])||1:At.stories??Fe.stories??1,Ne=zt("view",At.view||At.viewType,Fe.view||Fe.viewType),Ue=NJ(me),ct=Ue??zt("heatingCooling",At.heatingCooling||At.heating,Fe.heatingCooling||Fe.heating),xt=String(me.functionalUtility?.manualValue??"").split("|").map(Ka=>Ka.trim()).filter(Boolean),Na=xt.length?xt.join(", "):"None",la=String(me.porchPatioDeck?.manualValue??"").split("|").map(Ka=>Ka.trim()).filter(Boolean).length>0?void 0:zt("porchPatioDeck",At.porchPatioDeck||At.patioAndPorchFeatures,Fe.porchPatioDeck||Fe.patioAndPorchFeatures),fs=me.efficiencyRatingExists?.manualValue==="Yes",ps=me.greenCertificationExists?.manualValue==="Yes",Te=me.renewableEnergyExists?.manualValue==="Yes",at=String(me.efficiencyRatingName?.manualValue??"").trim(),yt=String(me.efficiencyRatingScore?.manualValue??"").trim(),nt=String(me.greenCertificationName?.manualValue??"").trim(),Wt=String(me.greenCertificationLevel?.manualValue??"").trim(),ts=String(me.renew
53ableEnergyType?.manualValue??"").trim(),gs=[];fs&&gs.push(`Efficiency: ${[at,yt].filter(Boolean).join(" ")||"Yes"}`),ps&&gs.push(`Green: ${[nt,Wt].filter(Boolean).join(" ")||"Yes"}`),Te&&gs.push(`Renewable: ${ts||"Yes"}`);const Va=gs.length?gs.join("; "):"None",Mr=String(me.pool?.manualValue??"").split("|").map(Ka=>Ka.trim()).filter(Boolean),xs=Mr.length>0?Mr.some(Ka=>Ka==="IngroundPool"||Ka==="IngroundSpa"):zt("pool",At.pool??At.poolYN,Fe.pool??Fe.poolYN),Sn=zt("floorLevel",At.floorLevel,Fe.floorLevel),ds=zt("hoa",At.hoa||At.hoaFee,Fe.hoa||Fe.hoaFee),Zt=zt("laundry",At.laundry||At.laundryFeatures,Fe.laundry||Fe.laundryFeatures),Os=(typeof ea=="number"?ea:parseInt(String(ea||0).replace(/[^0-9]/g,""))||0)/43560,qs={address:t,city:a||"",state:s||"",zip:r||"",latitude:p?.lat||0,longitude:p?.lng||0,gla:typeof it=="number"?it:parseInt(String(it||0).replace(/[^0-9]/g,""))||0,bedrooms:typeof Je=="number"?Je:parseInt(String(Je||0))||0,bathrooms:typeof Sa=="number"?Sa:parseFloat(String(Sa||0))||0,yearBuilt:typeof Qt=="number"?Qt:parseInt(String(Qt||0))||0,lotSizeAcres:Os,condition:re,quality:pt,basementSqft:typeof ma=="number"?ma:parseInt(String(ma||0).replace(/[^0-9]/g,""))||0,basementFinishedSqft:$e?Ot:n?.basementFinishedSqft||0,garageSpaces:typeof ir=="number"?ir:parseInt(String(ir||0))||0,propertyType:n?.propertyType||"SFR",isVerified:!0,verifiedAt:new Date().toISOString(),lastSalePrice:n?.lastSalePrice,lastSaleDate:n?.lastSaleDate,design:typeof Ze=="string"?Ze:void 0,stories:typeof It=="number"?It:parseInt(String(It||1))||1,view:typeof Ne=="string"?Ne:void 0,heatingCooling:typeof ct=="string"?ct:void 0,functionalUtility:typeof Na=="string"?Na:void 0,porchPatioDeck:typeof la=="string"?la:void 0,energyEfficient:typeof Va=="string"?Va:void 0,pool:xs===!0||xs==="true"||xs==="Yes",floorLevel:typeof Sn=="number"?Sn:Sn&&parseInt(String(Sn))||void 0,hoa:typeof ds=="number"?ds:ds&&parseFloat(String(ds).replace(/[^0-9.]/g,""))||void 0,laundry:typeof Zt=="string"?Zt:void 0},Ks={};for(const Ka of ut){const Ee=me[Ka.id]?.manualValue;Ee!=null&&String(Ee).trim()!==""&&(Ks[Ka.id]=String(Ee))}const Tn=(Ka,Ee,dt)=>{const ot=zt(Ka,Ee,dt);return ot==null||String(ot).trim()===""?void 0:Em(Ka,String(ot))?.value},Bn={heatingFuel:[At.heatingFuel||At.fuel||At.heating||At.heatingCooling,Fe.heatingFuel||Fe.fuel||Fe.heating||Fe.heatingCooling],heatingType:[At.heatingType||At.heating||At.heatingCooling,Fe.heatingType||Fe.heating||Fe.heatingCooling],cooling:[At.cooling||At.coolingType||At.airConditioning||At.heatingCooling,Fe.cooling||Fe.coolingType||Fe.airConditioning||Fe.heatingCooling],garageType:[At.garageType||At.carStorageType||At.parkingFeatures||At.parking,Fe.garageType||Fe.carStorageType||Fe.parkingFeatures||Fe.parking],garageAttachment:[At.garageAttachment||At.attachmentType||At.garageType||At.parkingFeatures,Fe.garageAttachment||Fe.attachmentType||Fe.garageType||Fe.parkingFeatures],basementType:[At.foundation||At.foundationType||At.basementType||At.basement,Fe.foundation||Fe.foundationType||Fe.basementType||Fe.basement],basementAccess:[At.basementAccess||At.belowGradeAccess||At.basement,Fe.basementAccess||Fe.belowGradeAccess||Fe.basement]};for(const[Ka,[Ee,dt]]of Object.entries(Bn)){const ot=dV[Ka];if(!ot)continue;const xa=Tn(Ka,Ee,dt);xa&&(Ks[ot]=xa)}Object.assign(Ks,TJ(me,D,At,Fe)),Object.assign(Ks,vJ(me)),Object.keys(Ks).length>0&&(qs.customFeatures=Ks),be(!0),Ve.current=!1,f?.(qs)},[me,At,Fe,i,H,D,f,t,a,s,r,p,n,ut]),St=o.useRef(Ce);St.current=Ce;const vt=o.useRef(ue);vt.current=ue;const Ve=o.useRef(!1),sa=o.useRef(!1);o.useEffect(()=>{if(!sa.current){sa.current=!0;return}Ve.current=!0},[me,D]),o.useEffect(()=>()=>{(!vt.current||Ve.current)&&St.current()},[]);const tt=o.useRef(F===!0);return o.useEffect(()=>{tt.current&&F===!1&&(!vt.current||Ve.current)&&St.current(),tt.current=F===!0},[F]),o.useEffect(()=>{if(A)return A(()=>{(!vt.current||Ve.current)&&St.current()}),()=>A(null)},[A]),o.useEffect(()=>{m({priorities:u?.priorities||[],weights:u?.weights||{},baselineSource:D,fieldSelections:me,baselineWeights:u?.baselineWeights,weightOverrides:u?.weightOverrides})},[D,me,m]),e.jsxs("div",{className:"h-full flex flex-col bg-slate-50 relative",children:[e.jsxs("div",{className:"h-[38px] px-4 flex items-center justify-between border-b border-slate-200 shrink-0 bg-white","data-testid":"header-bar",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("h1",{className:"text-[14px] font-semibold text-slate-800",children:"Subject Verify"}),(H!=null||de)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-[1px] h-4 bg-slate-200"}),e.jsx("div",{className:"flex items-center gap-1.5","data-testid":"els-badge",children:de?e.jsx("span",{className:"text-xs text-slate-400 animate-pulse",children:"ELS..."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:Q("w-2 h-2 rounded-full",(H||0)>=75?"bg-green-500":(H||0)>=50?"bg-amber-500":"bg-red-500")}),e.jsx("span",{className:"text-[11px] font-bold text-slate-700",children:"ELS"}),e.jsx("span",{className:Q("text-[11px] font-bold",(H||0)>=75?"text-green-600":(H||0)>=50?"text-amber-600":"text-red-600"),children:H}),e.jsx("span",{className:"text-[9px] text-slate-400",children:"/100"}),e.jsx("div",{className:"w-10 h-1.5 bg-slate-200 rounded-full overflow-hidden ml-0.5",children:e.jsx("div",{className:Q("h-full rounded-full",(H||0)>=75?"bg-green-500":(H||0)>=50?"bg-amber-500":"bg-red-500"),style:{width:`${H||0}%`}})})]})})]}),$>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-[1px] h-4 bg-slate-200"}),e.jsxs("button",{onClick:()=>fe(it=>it==="all"?"needsReview":"all"),className:Q("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors",se!=="all"?"bg-blue-50 text-blue-600 border border-blue-200":"bg-amber-50 text-amber-700 border border-amber-200"),"data-testid":"button-toggle-conflicts",children:[e.jsx(Ns,{className:"w-2.5 h-2.5"}),se!=="all"?"Show All":`${$} of ${V} need review`]})]}):V>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-[1px] h-4 bg-slate-200"}),e.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-emerald-50 text-emerald-700 border border-emerald-200","data-testid":"badge-all-verified",children:[e.jsx(kr,{className:"w-2.5 h-2.5"}),"All verified"]})]}),V>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-[1px] h-4 bg-slate-200"}),e.jsx("div",{className:"inline-flex rounded border border-slate-200 overflow-hidden","data-testid":"verify-filter-mode",children:[["all","All"],["needsReview","Needs review"],["unfilled","Unfilled"]].map(([it,Je],ht)=>e.jsx("button",{onClick:()=>fe(it),className:Q("px-1.5 py-0.5 text-[10px] font-medium transition-colors",ht>0&&"border-l border-slate-200",se===it?"bg-[#293757] text-white":"bg-white text-slate-500 hover:bg-slate-50"),"data-testid":`filter-mode-${it}`,children:Je},it))})]})]}),C&&G&&e.jsx("div",{className:"shrink-0",children:e.jsx(RI,{orderId:G,sectionId:"subjectProperty",label:"Subject"})})]}),e.jsx("div",{className:"flex-1 overflow-hidden flex",children:e.jsx("div",{className:"flex-1 overflow-auto border-r border-slate-200",style:{minWidth:0},children:e.jsxs("div",{className:"p-4 space-y-3 pb-[300px]",children:[N&&e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-slate-100 rounded-lg w-fit",children:[e.jsx("button",{onClick:()=>He("as-is"),className:Q("px-3 py-1 rounded-md text-xs font-medium transition-all",Be==="as-is"?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-700"),"data-testid":"tab-scenario-as-is",children:"As-Is"}),e.jsxs("button",{onClick:()=>He("after-repaired"),className:Q("px-3 py-1 rounded-md text-xs font-medium transition-all flex items-center gap-1",Be==="after-repaired"?"bg-amber-50 text-amber-900 shadow-sm border border-amber-200":"text-slate-500 hover:text-slate-700"),"data-testid":"tab-scenario-after-repaired",children:[e.jsx(m2,{className:"w-3 h-3"}),"After-Repaired"]})]}),(!N||Be==="as-is")&&e.jsxs(e.Fragment,{children:[e.jsx(uw,{activeFields:ae,listingDetails:At,propDetails:Fe,propertyData:i,subjectEls:H,subjectElsLoading:de,subjectQCLoading:T,fieldSelections:me,onFieldSourceChange:Oe,baselineSource:D==="public-record"?"public-record":"mls",filterMode:se,collapsibleSubRows:!0,subjectNormalizedGla:O,subjectGlaConfidence:E,subjectGlaNormNote:R,onConflictCountChange:W,csvSubjectValues:U,addedRows:ut,onAddedRowsChange:st,addedRowsHydrated:ua,inspectionImport:c,orderId:G,enableUad36:C,homeownerResponsibleExterior:Le}),$>0&&e.jsx("div",{className:"pt-2 border-t border-slate-200",children:e.jsxs("p",{className:"text-[10px] text-amber-600 text-center",children:[e.jsx(Ns,{className:"w-3 h-3 inline-block mr-0.5"}),$," of ",V," need review — resolve them first; any field still blank will be left empty when you proceed"]})}),$===0&&e.jsx("div",{className:"pt-2 border-t border-slate-200",children:e.jsxs("p",{className:"text-[10px] text-green-600 text-center flex items-center justify-center gap-1",children:[e.jsx(Bs,{className:"w-3 h-3"}),"All sources resolved — data will lock when you proceed"]})})]}),N&&Be==="after-repaired"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:Me,type:"file",accept:".pdf,image/jpeg,image/png,image/webp",className:"hidden",onChange:it=>{const Je=it.target.files?.[0];Je&&Ua(Je),it.target.value=""},"data-testid":"input-renovation-file"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold text-amber-700 uppercase tracking-wider",children:"After-Repaired Values"}),e.jsx("p",{className:"text-[10px] text-slate-500 mt-0.5",children:"Upload plans to auto-populate, or edit directly"})]}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>Me.current?.click(),disabled:Pe,className:"border-amber-300 text-amber-700 hover:bg-amber-50 text-xs h-7","data-testid":"button-upload-plans",children:Pe?e.jsxs(e.Fragment,{children:[e.jsx(za,{className:"w-3.5 h-3.5 mr-1 animate-spin"}),"Analyzing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Zx,{className:"w-3.5 h-3.5 mr-1"}),"Upload Plans"]})})]}),Re&&!Pe&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-500 bg-slate-50 px-2.5 py-1 rounded",children:[e.jsx(gn,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:Re})]}),Ie?.success&&Ie.summary&&e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-2.5",children:[e.jsxs("p",{className:"text-xs font-semibold text-amber-800 mb-1 flex items-center gap-1",children:[e.jsx(ul,{className:"w-3 h-3"}),"AI Summary"]}),e.jsx("p",{className:"text-xs text-amber-900 leading-relaxed whitespace-pre-line",children:Ie.summary}),Ie.totalCost&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1.5 font-medium",children:["Est. Cost: $",Ie.totalCost.toLocaleStr
53ing()]})]}),Ie?.error&&e.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-2.5 text-xs text-red-700",children:Ie.error}),e.jsx(uw,{activeFields:ae,listingDetails:At,propDetails:Fe,propertyData:i,subjectEls:H,subjectElsLoading:de,subjectQCLoading:T,fieldSelections:lt,onFieldSourceChange:ya,baselineSource:D==="public-record"?"public-record":"mls",showConflictsOnly:!1,prefilledManualValues:os,manualColumnLabel:"After-Repaired",subjectNormalizedGla:O,subjectGlaConfidence:E,subjectGlaNormNote:R,addedRows:ut,onAddedRowsChange:st,orderId:G,enableUad36:C,homeownerResponsibleExterior:Le})]})]})})})]})}function Bj(t){return Array.isArray(t?.degradedBranches)&&t.degradedBranches.includes("inspection")}async function AO(t,a={}){const s=a.retries??2,r=a.delayMs??(d=>1e3*(d+1)),n=a.sleep??(d=>new Promise(p=>setTimeout(p,d))),i=()=>a.isCancelled?.()===!0,l={inspection:null,conclusive:!1};let c=await t().catch(()=>null);for(let d=0;d<s;d++){if(i())return l;if(c?.inspection||c&&!Bj(c))break;if(console.warn("[Wizard] Inspection load degraded or failed — retrying",{attempt:d+1,degraded:Bj(c)}),await n(r(d)),i())return l;const p=await t().catch(()=>null);p&&(c=p)}return i()?l:c?.inspection?{inspection:c.inspection,conclusive:!0}:c&&!Bj(c)?{inspection:null,conclusive:!0}:l}function VM(t){if(!t||typeof t!="object")return!1;const a=t.aiPhotoRatings;return!a||typeof a!="object"?!1:Object.keys(a).length>0}function zj(t){if(!VM(t))return null;const a=t.aiPhotoRatings;return!a.condition&&!a.quality?null:a}function jO(t,a=new Date().toISOString()){return{condition:t.condition,qual
53ity:t.quality,computedAt:a}}function EJ(t){return{propertyData:{aiPhotoRatings:t}}}function TO(t,a,s){return{...t,condition:t.condition?.source==="User"||t.condition?.source==="Manual"?t.condition:{value:a.condition?.rating||"",source:"AI",isEdited:!1,alternatives:{},confidence:a.condition?.confidence,aiReasoning:a.condition?.reasoning},quality:t.quality?.source==="User"||t.quality?.source==="Manual"?t.quality:{value:a.quality?.rating||"",source:"AI",isEdited:!1,alternatives:{},confidence:a.quality?.confidence,aiReasoning:a.quality?.reasoning},aiPhotoRatings:s}}const wJ="overflow-hidden",PJ="overflow-y-auto",ite="overflow-y-auto";function OJ(t){return t?wJ:PJ}function LJ({orderId:t,onJumpToField:a,onLockConflict:s}){const{formData:r,setFormData:n,conditionality:i,hydrated:l}=YL(t,{onLockConflict:s}),c=o.useMemo(()=>OL(r,i),[r,i]),d=o.useCallback(h=>{n(h)},[n]),p=o.useCallback((h,f,v)=>{n(S=>{const N={...S,[h]:{...S[h],[f]:uV(v)}};for(const x of pV[`${h}.${f}`]??[])N[x.section]={...N[x.section],[x.field]:{value:x.transform?x.transform(v):v,confidence:"manual",source:"user",userEdited:!0}};return N})},[n]),u=o.useCallback((h,f)=>r[h]?.[f]?.value??"",[r]),m=e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Manage this order's documents. Open a PDF to pull individual pages or images into the Gallery, where you can assign them to the right report section."}),e.jsx(mV,{orderId:t,extractedPageKeys:LU(u),onExtracted:h=>hV(r,p,h),onAddImages:h=>OU(u,p,h.map(f=>({src:f.src,caption:f.caption||void 0,fileName:f.fileName,source:f.source,fullPage:f.fullPage})))})]});return e.jsx("div",{className:"h-full min-h-0 shrink-0 flex flex-col overflow-hidden bg-white","data-testid":"urar-wizard-right-panel-host","aria-busy":!l||void 0,children:e.jsx(fV,{orderId:t,formData:r,setFormData:d,updateField:p,conditionality:c,loaded:l,onJumpToField:a,documents:m,gallery:e.jsx(DU,{getFieldValue:u,updateField:p,approachScope:{useCostApproach:c.useCostApproach,useSiteValuation:c.useSiteValuation}})})})}const $M=Object.fromEntries(mC.map(t=>[t.id,t.label]));function qj(t){const a=t.weightOverrides&&t.boostCriteria?.length?Array.from(new Set(t.boostCriteria)).map(s=>({fieldId:s,weight:t.weightOverrides?.[s]??0})):(()=>{const s=Array.from(new Set(t.boostCriteria||[])),r=x$(t.baselineWeights,s);return[{fieldId:"proximity",weight:Math.round(r.baseline.proximity*100)},{fieldId:"gla",weight:Math.round(r.baseline.gla*100)},{fieldId:"els",weight:Math.round(r.baseline.els*100)},{fieldId:"bedsBaths",weight:Math.round(r.baseline.bedsBaths*100)},...s.filter(n=>!["proximity","gla","els","bedsBaths"].includes(n)).map(n=>({fieldId:n,weight:r.boosts[n]||0}))].sort((n,i)=>i.weight-n.weight)})();return kM(a.filter(s=>Qx.has(s.fieldId)).slice(0,z0).map((s,r)=>({fieldId:s.fieldId,label:$M[s.fieldId]||s.fieldId,weight:s.weight,rank:r+1,locked:!1})))}function DJ(t){const a=Object.entries(t).filter(([s])=>Qx.has(s)).map(([s,r])=>{const n=MM(r);return{fieldId:s,label:$M[s]||s,weight:n?.weight??0,rank:0,locked:n?.locked??!1}}).sort((s,r)=>r.weight-s.weight).slice(0,z0).map((s,r)=>({...s,rank:r+1}));return kM(a)}const hI=t=>{if(t==null||t==="")return null;if(typeof t=="number")return Number.isFinite(t)?t:null;const a=String(t).replace(/[^0-9.]/g,"");if(!a)return null;const s=Number(a);return Number.isFinite(s)?s:null},Yj=t=>{if(t==null)return;const a=String(t).trim();if(!a)return;const s=a.match(/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/),r=a.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/),n=s?{year:Number(s[1]),month:Number(s[2]),day:Number(s[3])}:r?{year:Number(r[3]),month:Number(r[1]),day:Number(r[2])}:null;if(n){const l=new Date(n.year,n.month-1,n.day);return l.getFullYear()!==n.year||l.getMonth()!==n.month-1||l.getDate()!==n.day?void 0:`${String(n.year).padStart(4,"0")}-${String(n.month).padStart(2,"0")}-${String(n.day).padStart(2,"0")}`}const i=new Date(a);if(Number.isFinite(i.getTime()))return`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")}`},kJ=t=>{const a=(t||[]).filter(d=>d.type==="Sale"&&d.date);if(a.length===0)return{transactionPrice:null,mostRecentSalePrice:null,mostRecentSaleDate:"",recordationDate:"",soldWithin12Months:null,soldWithin36Months:null};const r=[...a].sort((d,p)=>new Date(p.date).getTime()-new Date(d.date).getTime())[0],n=hI(r.price),i=new Date(r.date).getTime();let l=null,c=null;if(Number.isFinite(i)){const d=(Date.now()-i)/26298e5;l=d<=12,c=d<=36}return{transactionPrice:n,mostRecentSalePrice:n,mostRecentSaleDate:r.date,recordationDate:r.date,
53soldWithin12Months:l,soldWithin36Months:c}};function BM(...t){const a=r=>{for(const n of t){const i=n?.[r];if(!(i==null||String(i).trim()===""))return String(i).trim()}},s=r=>{for(const n of t){const i=n?.[r];if(i===!0||i===!1)return i;if(typeof i=="string"&&/^(yes|true)$/i.test(i.trim()))return!0;if(typeof i=="string"&&/^(no|false)$/i.test(i.trim()))return!1}};return{view:a("view"),quality:a("quality"),condition:a("condition"),pool:s("pool"),driveway:a("driveway")}}function MJ(t,...a){const s=n=>t?.gridSubjectOverrides?.[n]?.value,r=BM({condition:s("condition"),quality:s("quality")},{condition:t?.condition,quality:t?.quality},...a);return{condition:r.condition,quality:r.quality}}const IO=({propertyData:t,orderData:a,historyData:s,propMixData:r})=>{const n=t,i=r?.listingDetails||{},l=r?.propertyDetails||{},c=F=>{if(F==null||F==="")return;const A=typeof F=="number"?F:parseFloat(String(F).replace(/[^0-9.]/g,""));return Number.isFinite(A)?A:void 0},d=F=>F==null?void 0:Array.isArray(F)?F.filter(Boolean).join(", ")||void 0:String(F).trim()||void 0,p=d(i.status)||d(i.standardStatus),u=(p||"").toLowerCase(),m=p?/closed|sold|expired|withdrawn|cancel|inactive|off[\s-]?market|delete/.test(u)?!1:/\b(active|pending|contingent|new)\b|coming soon|under contract|for sale/.test(u)?!0:void 0:void 0,h=(()=>{const F=a.offeredForSale?.value;return F===!0||F===!1?F:void 0})(),f=d(a.offeredForSaleMlsNumber?.value),v=hI(a.offeredForSalePrice?.value)??void 0,S=Yj(a.offeredForSaleListDate?.value),N=d(a.offeredForSaleDataSource?.value),x=h!==void 0||f!==void 0||v!==void 0||S!==void 0||N!==void 0,y=d(i.exteriorFeatures),b=BM({view:n.view?.value||n.viewType?.value,quality:n.quality?.value,condition:n.condition?.value,pool:n.pool?.value,driveway:n.drivewaySurface?.value},{view:i.view,quality:i.quality,condition:i.condition||i.propertyCondition,pool:i.pool,driveway:i.driveway},{view:l.view,quality:l.quality,condition:l.condition||l.physicalCondition,pool:l.pool,driveway:l.driveway}),j=c(n.gla?.value)??c(n.grossLivingArea?.value)??c(i.squareFeet??i.livingArea??i.LivingArea??i.gla??i.sqft)??c(l.squareFeet??l.livingArea??l.LivingArea??l.gla??l.sqft),T=c(n.bedrooms?.value)??c(i.bedrooms??i.bedroomsTotal??i.BedroomsTotal)??c(l.bedrooms??l.bedroomsTotal??l.BedroomsTotal),O=c(n.fullBaths?.value)??c(i.fullBathrooms??i.fullBaths??i.bathroomsFull??i.BathroomsFull)??c(l.fullBathrooms??l.fullBaths??l.bathroomsFull??l.BathroomsFull),E=c(n.halfBaths?.value)??c(i.halfBathrooms??i.halfBaths??i.bathroomsHalf??i.BathroomsHalf)??c(l.halfBathrooms??l.halfBaths??l.bathroomsHalf??l.BathroomsHalf),G=c(n.bathrooms?.value)??c(i.bathrooms??i.BathroomsTotalInteger)??c(l.bathrooms??l.BathroomsTotalInteger)??(O!==void 0?O+(E??0)*.5:void 0),U=c(n.yearBuilt?.value)??c(i.yearBuilt??i.YearBuilt)??c(l.yearBuilt??l.YearBuilt),C=c(n.lotSize?.value)??c(i.lotSizeSquareFeet??i.LotSizeSquareFeet??i.lotSize)??c(l.lotSizeSquareFeet??l.LotSizeSquareFeet??l.lotSize);return{roofType:n.roofSurface?.value||n.roofType?.value||void 0,exteriorWall:n.exteriorWalls?.value||void 0,heating:n.heatingType?.value||void 0,cooling:n.coolingType?.value||void 0,basement:n.basementArea?.value||n.basementFinish?.value||void 0,foundation:n.foundationWalls?.value||void 0,garageType:n.garageType?.value||void 0,legalDescription:n.legalDescription?.value||void 0,parcelNumber:n.pinNumber?.value||void 0,county:n.county?.value||void 0,ownerName:a.owner?.value||void 0,floodZone:n.femaFloodZone?.value||void 0,assessedTaxes:hI(n.taxes?.value)??void 0,taxYear:n.taxYear?.value||void 0,...kJ(s),gla:j,beds:T,baths:G,yearBuilt:U,lotSize:C,stories:c(n.stories?.value)??c(l.stories),roomCount:c(n.totalRooms?.value)??c(l.roomCount),fireplaces:c(i.fireplace)??c(l.fireplaces),garageSpaces:c(n.garageCars?.value)??c(l.garageSpaces),numberOfUnits:c(n.numUnits?.value)??c(l.numberOfUnits),lotDimensions:d(n.lotDimensions?.value)||d(i.lotDimensions)||d(l.lotDimensions),viewType:b.view,quality:b.quality,pool:b.pool,patio:d(i.patioFeatures),porchDeck:y&&/porch|deck/i.test(y)?y:void 0,interiorFinish:d(i.interiorFeatures),floorCovering:d(i.flooring)||d(l.flooring),energyEfficiency:d(i.greenEnergyEfficient)||d(i.energyFeatures),lotShape:n.lotShape?.value||d(i.lotShape)||d(l.lotShape),driveway:b.driveway,fencing:d(i.fencing)||d(l.fencing),utilities:$$(n.waterType?.value||d(i.water),n.sanitarySewerType?.value||d(i.sewer))??void 0,listingStatus:p,listPrice:v??c(i.listPrice)??c(i.originalListPrice),currentlyListed:h??m,listDate:S||Yj(i.listDate)||Yj(i.listingContractDate),mlsNumber:f||d(i.listingId)||d(i.mlsNumber)||d(i.MlsListingNumber),listingDetails:N,listingSource:x?"Order":p?"MLS":void 0,offeredForSale:h,condition:b.condition}};function Hp(t){if(t==null||t==="")return;if(typeof t=="number")return Number.isFinite(t)&&t>0?t:void 0;const a=String(t).trim().match(/-?\d+(\.\d+)?/);if(!a)return;const s=parseFloat(a[0]);return Number.isFinite(s)&&s>0?s:void 0}function Ih(t){return t!=null&&Number.isFinite(t)&&t>0?t:void 0}function CO(t){const a=(t??"").trim();return a===""?void 0:a}function o0(t,a,s,r){for(const n of s)if(n!==void 0)return n;if(r!==void 0)return t.push(a),r}function FJ(t){const a=t.propmix&&!t.propmix.empty?t.propmix:null,
53s=[],r=o0(s,"bedrooms",[Hp(t.strBedsPerUnit),Hp(t.gridBeds),Ih(t.coreBeds)],Ih(a?.bedrooms)),n=o0(s,"bathrooms",[Hp(t.strBathsPerUnit),Hp(t.gridBaths),Ih(t.coreBaths)],Ih(a?.bathrooms)),i=o0(s,"gla",[Hp(t.gridGla),Ih(t.coreGla)],Ih(a?.gla)),l=o0(s,"yearBuilt",[Ih(t.coreYearBuilt)],Ih(a?.yearBuilt)),c=o0(s,"propertyType",[CO(t.corePropertyType)],CO(a?.propertyType));return{bedrooms:r,bathrooms:n,gla:i,yearBuilt:l,propertyType:c,propmixPrefilledFields:s}}const zM=o.createContext(void 0),qM=o.createContext(null);function ote(t){if(!t||t.length===0)return null;const a=t.find(n=>n.isCover&&n.photoUrl);if(a)return a.photoUrl;const s=t.find(n=>n.label.trim().toLowerCase()==="front view"&&n.photoUrl);if(s)return s.photoUrl;const r=t.find(n=>n.photoUrl);return r?r.photoUrl:null}function lte(t){if(typeof t=="number")return Number.isFinite(t)?t:null;if(typeof t=="string"){const a=Number(t.replace(/[$,]/g,""));return t.trim()!==""&&Number.isFinite(a)?a:null}if(t&&typeof t=="object"){const a=t.current0to3;if(typeof a=="number"&&Number.isFinite(a))return a;if(typeof a=="string"){const s=Number(a);if(a.trim()!==""&&Number.isFinite(s))return s}}return null}const _J=["Front View","Rear View","Street Scene","Kitchen","Bathroom","Living Room","Bedroom","Basement","Garage","Address/Mailbox"];function UJ(){return _J.map((t,a)=>({id:`slot-${a}-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,label:t,photoUrl:null}))}const VJ=[{key:"front",label:"Front View"},{key:"frontLeft",label:"Front Left"},{key:"frontRight",label:"Front Right"},{key:"addressVerification",label:"Address/Mailbox"},{key:"streetView",label:"Street Scene"},{key:"rear",label:"Rear View"},{key:"interior1",label:"Interior 1"},{key:"interior2",label:"Interior 2"},{key:"kitchen",label:"Kitchen"},{key:"bathroom",label:"Bathroom"}];function $J(t){if(Array.isArray(t.photoSlots)&&t.photoSlots.length>0)return t;const a=t.photoSlotAssignments;if(!(!!a&&Object.values(a).some(n=>typeof n=="string"&&n.length>0)))return t;const r=VJ.map(({key:n,label:i})=>({id:`legacy-${n}`,label:i,photoUrl:a[n]||null,autoAssigned:!1}));return{...t,photoSlots:r,photoAutoSortDone:!0}}const oN={clientName:"",clientFileId:"",intendedUser:"",intendedUse:"Lending or servicing decisions",inspectionType:"",inspectionDate:new Date().toISOString().split("T")[0],inspectorName:"",valuationPremise:"Current",propertyRights:"fee_simple",consideredApproaches:{sales:!0,income:!1,cost:!1},basisForCondition:"",borrowerName:"",propertyOwner:"",occupancyType:"",currentProjectedUse:"Single-Family Residential",previouslyAppraised:"",previouslyAppraisedDate:"",listingsPendingStatus:"",listingsPendingDetails:"",streetAccess:"public_road",ownerName:"",recordationDate:"",transactionPrice:null,soldWithin12Months:null,soldWithin36Months:null,mostRecentSaleDate:"",mostRecentSalePrice:null,assessedValues:[],saleHistory:[],currentlyListed:null,listPrice:null,subjectListDate:"",subjectConcessions:"",insurableValue:null,legalDescription:"",parcelNumber:"",county:"",assessedTaxes:null,taxYear:"",specialAssessmentAmount:null,propertyAge:null,siteArea:"",topography:"",userEditedAssessedValues:!1,escrow:null,walkScore:null,transitScore:null,bikeScore:null,freewayDistance:null,highwayProximity:"",airportName:"",airportCode:"",airportDistance:null,populationCity:null,populationMarket:null,vacancyRate:null,housingDensity:null,medianHouseholdIncome:null,ownerOccupiedPct:null,censusTractId:"",employmentStability:"",majorEmployers:"",economicOutlook:"",groceryCount:null,pharmacyCount:null,parksCount:null,entertainmentDining:"",trails:"",elementarySchoolCount:null,middleSchoolCount:null,highSchoolCount:null,schoolRadius:5,nearestSchoolName:"",nearestSchoolDistance:null,fireStationDistance:null,policeStationDistance:null,medicalFacilityDistance:null,publicInvestment:"",floodZone:"",neighborhoodNarrative:"",neighborhoodType:"",boundaryNorth:"",boundaryEast:"",boundarySouth:"",boundaryWest:"",predominantAge:"",predominantPrice:"",landUseResidential:null,landUseCommercial:null,transitHubDistance:null,primaryEmploymentCenter:"",employmentCenterDistance:null,cbdTravelTime:null,zonePo
53pulation:null,privateSchoolCount:null,driveTime5Mi:null,driveTime10Mi:null,driveTime20Mi:null,groceryCount5Mi:null,groceryCount10Mi:null,groceryCount20Mi:null,pharmacyCount5Mi:null,pharmacyCount10Mi:null,pharmacyCount20Mi:null,elementarySchoolCount05Mi:null,elementarySchoolCount15Mi:null,elementarySchoolCount25Mi:null,middleSchoolCount05Mi:null,middleSchoolCount15Mi:null,middleSchoolCount25Mi:null,highSchoolCount05Mi:null,highSchoolCount15Mi:null,highSchoolCount25Mi:null,privateSchoolCount05Mi:null,privateSchoolCount15Mi:null,privateSchoolCount25Mi:null,parksGreenSpace1Mi:"",parksGreenSpace25Mi:"",trailsPaths1Mi:"",trailsPaths25Mi:"",entertainmentDining1Mi:"",entertainmentDining25Mi:"",infrastructureProjects25Mi:"",infrastructureProjectType:"",locationType:"",builtUp:"",growthRate:"",propertyValues:"",demandSupply:"",typicalMarketingTime:"",overallTrend:"",monthsOfSupply:null,medianDom:null,absorptionRate:null,medianSalePrice:null,activeListings:null,marketLockedAt:"",marketConditionsNarrative:"",propertyCommentsNarrative:"",priceRangeMin:null,priceRangeMax:null,ageRangeMin:null,ageRangeMax:null,percentForeclosure:null,marketInventoryTrend:[],exposureTime:"",predominantOccupancy:"",marketMonthlySeries:[],multiYearPriceTrend:[],derivedLotShape:"",derivedLandUse:"",derivedExposureTime:"",derivedOccupancy:"",specialConditions:"",roofType:"",exteriorWall:"",heating:"",cooling:"",basement:"",foundation:"",pool:null,garageType:"",designStyle:"",garageSpaces:null,driveway:"",utilities:"",fencing:"",yard:"",stories:null,roomCount:null,fireplaces:null,patio:"",porchDeck:"",zoningClassification:"",zoningDescription:"",zoningCompliance:"",lotDimensions:"",viewType:"",interiorFinish:"",floorCovering:"",energyEfficiency:"",appliances:"",nuisances:"",landUseCompatibility:"",siteLocationType:"",numberOfUnits:null,effectiveAge:null,remainingEconomicLife:null,physicalCondition:"",zoningScreenshotUrl:"",photoSlotAssignments:{front:null,frontLeft:null,frontRight:null,addressVerification:null,streetView:null,rear:null,interior1:null,interior2:null,kitchen:null,bathroom:null},photoSlots:UJ(),uploadedPhotos:[],photoCategories:{},photoAutoSortDone:!1,highestBestUse:{asVacant:"Residential development consistent with neighborhood",asImproved:"Continued residential use as currently improved",legalPermissibility:"Current use is legally permissible under existing zoning",physicalPossibility:"The site is physically capable of supporting the current improvements",financialFeasibility:"Continued residential use is financially feasible",maximumProductivity:"Present use represents the maximum productive use of the site"},photoSource:"",compGridRows:[],evalCellValues:{},finishedAboveGrade:null,unfinishedAboveGrade:null,finishedBelowGrade:null,unfinishedBelowGrade:null,nonstandardFinishedAboveGrade:null,nonstandardFinishedBelowGrade:null,belowGradeExteriorAccess:"",showBelowGradeAreaRows:!1,showNonstandardFinishedAboveGrade:!1,showNonstandardFinishedBelowGrade:!1,compGridNotes:"",compGridCustomAdjLabel:"",customComparisonFactors:[],salesComparisonValue:null,incomeCapitalizationValue:null,marketValueOpinion:null,effectiveDate:new Date().toISOString().split("T")[0],reportDate:new Date().toISOString().split("T")[0],reconciliationNarrative:"",dataSourcesNarrative:"The preparer maintains a comprehensive database of county and public records for the subject area, in addition to market and property specific data developed with the assistance of local MLS data, county assessor records, and third-party property data services.",dataSourcesUsed:["MLS","Public Records","Tax Records"],adjustmentRangeLow:null,adjustmentRangeHigh:null,indicatedValueLow:null,indicatedValueHigh:null,ffeDeductions:null,qcReviewerName:"",qcReviewerDate:"",inspectorCompany:"",approachesAnalyzed:"",compGridSummary:"",valueRangeJustification:"",preparerName:"",preparerEmail:"",preparerPhone:"",preparerCompany:"",isLicensedAppraiser:!1,licenseNumber:"",licenseState:"",licenseExpiration:"",preparerQualifications:"",preparerExperience:"",signatureDataUrl:"",signatureTypedName:"",signedAt:null,assumptions:"",limitingConditions:"This evaluation is subject to the following limiting conditions: 1) The property is assumed to have clear and marketable title. 2) Information provided by third-party sources is assumed to be reliable. 3) No responsibility is assumed for legal matters. 4) The value opinion is subject to the assumption that there are no hidden or unapparent conditions affecting the property.",independenceStatement:"I certify that I have no present or prospective interest in the property that is the subject of this report, and I have no personal interest or bias with respect to the parties involved.",independenceAcknowledged:!1,extentOfAnalysis:"Sales Comparison Approach",annotations:[],companyAbout:"",supervisorName:"",supervisorLicense:"",fieldVerifications:{},marketChartImages:{}},cte=[{key:"report_setup",label:"Cover & Header Info",icon:"FileText"},{key:"subject_ownership",label:"Report Information & Ownership",icon:"Home"},{key:"neighborhood",label:"Neighborhood Data",icon:"MapPin"},{key:"market_conditions",label:"Market Area",icon:"TrendingUp"},{key:"site_improvements",label:"Site & Improvements",icon:"Layers"},{key:"photos",label:"Photos",icon:"Camera"},{key:"hbu",label:"Highest & Best Use",icon:"BarChart3"},{key:"comp_grid",label:"Sales Comparison",icon:"Grid3x3"},{key:"reconciliation",label:"Summary & Reconciliation",icon:"DollarSign"},{key:"certification",label:"Certification",icon:"Shield"}
53],FN={report_setup:["clientName","intendedUser","intendedUse","inspectionType","inspectionDate","inspectorName","valuationPremise","propertyRights","basisForCondition","consideredApproaches","insurableValue"],subject_ownership:["propertyOwner","occupancyType","currentProjectedUse","previouslyAppraised","previouslyAppraisedDate","listingsPendingStatus","listingsPendingDetails","streetAccess","ownerName","recordationDate","transactionPrice","soldWithin12Months","soldWithin36Months","mostRecentSaleDate","mostRecentSalePrice","assessedValues","currentlyListed","listPrice","subjectListDate","subjectConcessions","legalDescription","parcelNumber","county","assessedTaxes","taxYear","specialAssessmentAmount","propertyAge","siteArea","topography"],neighborhood:["walkScore","bikeScore","freewayDistance","highwayProximity","airportName","airportCode","airportDistance","populationCity","populationMarket","vacancyRate","housingDensity","medianHouseholdIncome","ownerOccupiedPct","censusTractId","employmentStability","majorEmployers","economicOutlook","groceryCount","pharmacyCount","parksCount","entertainmentDining","elementarySchoolCount","middleSchoolCount","highSchoolCount","schoolRadius","nearestSchoolName","nearestSchoolDistance","fireStationDistance","policeStationDistance","medicalFacilityDistance","floodZone","neighborhoodNarrative","neighborhoodType","boundaryNorth","boundaryEast","boundarySouth","boundaryWest","predominantAge","predominantPrice","landUseResidential","landUseCommercial","primaryEmploymentCenter","employmentCenterDistance","cbdTravelTime","zonePo
53pulation","privateSchoolCount","driveTime5Mi","driveTime10Mi","driveTime20Mi","groceryCount5Mi","groceryCount10Mi","groceryCount20Mi","pharmacyCount5Mi","pharmacyCount10Mi","pharmacyCount20Mi","elementarySchoolCount05Mi","elementarySchoolCount15Mi","elementarySchoolCount25Mi","middleSchoolCount05Mi","middleSchoolCount15Mi","middleSchoolCount25Mi","highSchoolCount05Mi","highSchoolCount15Mi","highSchoolCount25Mi","privateSchoolCount05Mi","privateSchoolCount15Mi","privateSchoolCount25Mi","parksGreenSpace1Mi","parksGreenSpace25Mi","entertainmentDining1Mi","entertainmentDining25Mi","infrastructureProjects25Mi","infrastructureProjectType"],market_conditions:["locationType","builtUp","growthRate","propertyValues","demandSupply","typicalMarketingTime","overallTrend","monthsOfSupply","medianDom","absorptionRate","medianSalePrice","activeListings","marketConditionsNarrative","propertyCommentsNarrative","priceRangeMin","priceRangeMax","ageRangeMin","ageRangeMax","percentForeclosure","marketLockedAt","exposureTime","predominantOccupancy"],site_improvements:["derivedLotShape","derivedLandUse","derivedExposureTime","derivedOccupancy","specialConditions","roofType","exteriorWall","heating","cooling","basement","foundation","pool","garageType","designStyle","garageSpaces","driveway","utilities","fencing","yard","stories","roomCount","fireplaces","patio","porchDeck","zoningClassification","zoningDescription","zoningCompliance","lotDimensions","viewType","interiorFinish","floorCovering","energyEfficiency","appliances","nuisances","landUseCompatibility","siteLocationType","numberOfUnits","effectiveAge","remainingEconomicLife","physicalCondition"],photos:["photoSource"],hbu:["highestBestUse"],comp_grid:["compGridRows","compGridNotes"],reconciliation:["salesComparisonValue","marketValueOpinion","effectiveDate","reportDate","reconciliationNarrative","dataSourcesNarrative","dataSourcesUsed"],certification:["preparerName","preparerEmail","preparerPhone","preparerCompany","isLicensedAppraiser","licenseNumber","licenseState","licenseExpiration","signatureDataUrl","independenceAcknowledged","extentOfAnalysis","supervisorName","supervisorLicense"]}
53,dte=["clientName","intendedUse","inspectionType","valuationPremise","propertyRights","basisForCondition","propertyOwner","occupancyType","legalDescription","parcelNumber","county","neighborhoodNarrative","neighborhoodType","floodZone","locationType","builtUp","growthRate","propertyValues","demandSupply","typicalMarketingTime","overallTrend","zoningClassification","zoningCompliance","marketValueOpinion","effectiveDate","reconciliationNarrative","dataSourcesNarrative","preparerName","preparerEmail","signatureDataUrl","independenceAcknowledged"];function ute(t,a){if(a===null||a===""||a===void 0||a===!1)return!0;if(t==="consideredApproaches"&&typeof a=="object"){const s=a;return!s.sales&&!s.income&&!s.cost}if(t==="highestBestUse"&&typeof a=="object"){const s=a;return!s.asVacant&&!s.asImproved}return Array.isArray(a)?a.length===0:!1}const Gj={currentStep:0,evalSubStep:0,activeSection:"report_setup",formData:oN,subjectProperty:null,compsGridData:null,marketData:null,selectedCompIds:[],templateId:"wizardstep",reportId:null,enrichmentLoaded:!1,enrichedAt:null,restoredFieldKeys:[]};function fC(){const t=o.useContext(qM);if(!t)throw new Error("useEvalWizardStore must be used within an EvalWizardProvider");return t}function pte(){return fC().actions}function BJ(t,a){if(t===a)return!0;if(t.length!==a.length)return!1;for(let s=0;s<t.length;s++)if(!Object.is(t[s],a[s]))return!1;return!0}function YM(t,a=Object.is){const s=fC(),r=o.useRef(null),n=()=>{const i=s.getSnapshot(),l=r.current;if(l&&l.snap===i)return l.value;const c=t(i),d=l&&a(l.value,c)?l.value:c;return r.current={snap:i,value:d},d};return o.useSyncExternalStore(s.subscribe,n,n)}function mte(t,a){const s=fC(),r=(a?.extraFields||[]).join(","),n=o.useMemo(()=>[...FN[t]||[],...a?.extraFields||[]],[t,r]),i=!!a?.watchAllFormData;YM(c=>{const d=c.state.formData,p=[];if(i)p.push(d);else for(const u of n)p.push(d[u]),p.push(d.fieldVerifications[u]);return p.push(c.state.subjectProperty,c.state.compsGridData,c.state.marketData,c.state.selectedCompIds,c.state.templateId,c.state.reportId,c.state.enrichmentLoaded,c.verificationFilter,c.isHydrated),p},BJ);const l=s.getSnapshot();return{state:l.state,needsAttentionFilter:l.verificationFilter!=="all",verificationFilter:l.verificationFilter,saveStatus:l.saveStatus,saveError:l.saveError,isHydrated:l.isHydrated,...s.actions}}function GM(t,a){if(t==="photoSlotAssignments"){const s=a.photoSlotAssignments,r=Object.keys(s),n=r.length,i=r.filter(l=>s[l]!==null&&s[l]!=="").length;return{subTotal:n,subVerified:i}}if(t==="photoSlots"){const s=a.photoSlots||[];return s.length===0?{subTotal:1,subVerified:0}:{subTotal:s.length,subVerified:s.filter(r=>!!r.photoUrl).length}}if(t==="highestBestUse"){const s=a.highestBestUse,r=Object.keys(s),n=r.length,i=r.filter(l=>s[l]!=="").length;return{subTotal:n,subVerified:i}}if(t==="compGridRows"){const s=a.compGridRows;if(s.length===0)return{subTotal:1,subVerified:0};const r=lN.length;let n=0;for(const i of lN)s.some((c,d)=>HJ(a,i,d))||n++;return{subTotal:r,subVerified:n}}if(t==="assessedValues"){const s=a.assessedValues;return s.length===0?{subTotal:1,subVerified:0}:{subTotal:s.length,subVerified:s.filter(r=>r.total>0).length}}return{subTotal:0,subVerified:0}}const lN=["rightsConveyed","financingConcessions","locationAdj","glaAdj","lotSizeAdj","ageAdj","conditionAdj","qualityAdj","viewAdj","heatingCoolingAdj","bedsAdj","bathsAdj","garageAdj","porchPatioDeckAdj","basementAdj","marketConditionsAdj","otherAdj"],gC=new Set(["photoSlotAssignments","photoSlots","highestBestUse","compGridRows","consideredApproaches","assessedValues","saleHistory"]);function zJ(t){return!!(t.supervisorName.trim()||t.supervisorLicense.trim())}function xC(t,a){return t==="previouslyAppraisedDate"?a.previouslyAppraised==="Yes":t==="inspectorName"?a.inspectionType!=="Desktop":t==="listingsPendingDetails"?a.listingsPendingStatus==="active_listing"||a.listingsPendingStatus==="pending_sale":t==="infrastructureProjectType"?a.infrastructureProjects25Mi==="Yes":t==="listPrice"||t==="subjectListDate"?a.currentlyListed===!0:t==="supervisorName"||t==="supervisorLicense"?zJ(a):!0}const qJ=new Set(["subjectConcessions","nuisances","landUseCompatibility","yard","fencing","previouslyAppraised","specialAssessmentAmount","appliances","specialConditions","insurableValue"]);function YJ(t,a){const s=FN[a]||[];let r=0,n=0,i=0;for(const l of s)if(xC(l,t)){if(gC.has(l)){const{subTotal:c,subVerified:d}=GM(l,t);r+=c,n+=d,d<c&&(i+=c-d);continue}r++,HM(t,l)?i++:n++}return{total:r,verified:n,needsAttention:i}}function GJ(t,a){return t==="conflict"?"conflicts":t==="prefilled_review"?a?"unconfirmed":"missing":t==="auto_verified"||t==="overridden"||t==="partner_locked"||a?"confirmed":"missing"}function cN(t,a,s){const r=t.fieldVerifications[a],n=s&&"value"in s?s.value:t[a],i=n!==null&&n!==""&&n!==void 0&&!(Array.isArray(n)&&n.length===0);return!i&&qJ.has(a)?"confirmed":GJ(r?.status,i)}function HM(t,a,s){if(!xC(a,t))return!1;const r=cN(t,a,s);return r==="missing"||r==="conflicts"}function HJ(t,a,s){const r=t.fieldVerifications[`compGrid_${a}_${s}`];return!!r&&(r.status==="prefilled_review"||r.status==="conflict")}function WM(t,a,s){const r=t.fieldVerifications[`compGrid_${a}_${s}`];if(!r)return"confirmed";if(r.status==="conflict")return"conflicts";if(r.status==="prefilled_review"){const n=t.compGridRows[s],i=n?n[a]:void 0;return i!=null&&i!==""?"unconfirmed":"missing"}return"confirmed"}function WJ(t,a){let s=!1,r=!1,n=!1;for(let i=0;i<t.compGridRows.length;i++){const l=WM(t,a,i);l==="conflicts"?s=!0:l==="missing"?r=!0:l==="unconfirmed"&&(n=!0)}return s?"conflicts":r?"missing":n?"unconfirmed":"confirmed"}function KJ(t){const a={confirmed:0,unconfirmed:0,missing:0,conflicts:0};if(t.compGridRows.length===0)return a.missing=1,a;
53for(const s of lN)a[WJ(t,s)]++;return a}function RO(t,a){const s={missing:0,conflicts:0,unconfirmed:0,confirmed:0};for(const r of a)if(xC(r,t)){if(gC.has(r)){if(r==="compGridRows"){const n=KJ(t);s.confirmed+=n.confirmed,s.unconfirmed+=n.unconfirmed,s.missing+=n.missing,s.conflicts+=n.conflicts}else{const{subTotal:n,subVerified:i}=GM(r,t);s.confirmed+=i,s.missing+=Math.max(0,n-i)}continue}s[cN(t,r)]++}return s}const EO=Object.values(FN).flat();function QJ(t){const a=Object.entries(t.fieldVerifications||{});let s=!1;const r={};for(const[n,i]of a)if(i?.status==="conflict"){s=!0;const l=i.conflictValues?.[0]?.source||(i.source?i.source.split(" vs ")[0]:"Manual");r[n]={status:"overridden",source:l,verifiedAt:new Date().toISOString()}}else r[n]=i;return s?{...t,fieldVerifications:r}:null}function _p(t){const a=JSON.stringify(t);return{payload:JSON.parse(a),serialized:a}}function wO(t){const a=t&&typeof t=="object"&&!Array.isArray(t)?t:{},s=Wz(T7($J(a))),r=Array.isArray(s.compGridRows)?s.compGridRows.map(n=>{const i=(l,c)=>{const d=kc(n.compId,l);return Yz(s.evalCellValues?.[d],c)};return hb({...n,salePrice:i("salePrice",n.salePrice),finishedAboveGrade:i("finishedAboveGrade",n.finishedAboveGrade),nonstandardFinishedAboveGrade:i("nonstandardFinishedAboveGrade",n.nonstandardFinishedAboveGrade)})}):oN.compGridRows;return{...oN,...s,compGridRows:r,fieldVerifications:{...s.fieldVerifications||{}}}}function Hj(t,a){return Object.is(t,a)?!0:JSON.stringify(t)===JSON.stringify(a)}function Wj(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ZJ(t,a,s){const r=[],n=(i,l,c,d)=>{if(Hj(l,i))return c;if(Hj(c,i)||Hj(l,c))return l;if(Wj(i)&&Wj(l)&&Wj(c)){const p={},u=new Set([...Object.keys(i),...Object.keys(l),...Object.keys(c)]);for(const m of u){const h=n(i[m],l[m],c[m],d?`${d}.${m}`:m);h!==void 0&&(p[m]=h)}return p}return r.push(d),l};return{merged:n(t,a,s,""),conflictPaths:r}}const l0=new Map;function Kj(t,a){let s=t.formData.compGridRows,r=t.formData.fieldVerifications,n=t.formData.evalCellValues,i=!1;const l=d=>{if(!d)return;const p=d.trim().toLowerCase().replace(/[\s_-]+/g,"");return p==="mls"?"mls":p==="publicrecord"||p==="publicrecords"?"publicRecord":p==="ai"||p==="aiderived"?"ai":p==="user"||p==="manual"?"manual":d.trim()},c=(d,p,u)=>{const h=["attachmentType","attachedDetached","AttachmentType","AttachedDetached","neighborhoodName","NeighborhoodName","location","locationComparison","locationType","siteLocationType","neighborhoodClassification","siteInfluence","SiteInfluenceType"].includes(p.fieldName)?l(p.source):void 0;return h?{...Mv(d,new Date().toISOString(),u),source:h,alternatives:p.alternatives?.map(f=>({source:f.source,value:f.value}))??u?.alternatives??[],manual:!1,editedAt:["location","locationComparison","locationType","siteLocationType","neighborhoodClassification","siteInfluence","SiteInfluenceType"].includes(p.fieldName)?new Date().toISOString():"property-lab-selection"}:Mv(d,new Date().toISOString(),u)};for(const d of a){if(wk.includes(d.fieldName)){const f=ty(s,d.identity),v=Number(d.value);if(f<0||!Number.isFinite(v))continue;const S=s[f],N=d.fieldName;if((S[N]??0)===v)continue;const x={...S,[N]:v},y=XI(x)+LN(t.formData.customComparisonFactors,x.compId),b=hb({...x,totalAdj:y});s=[...s],s[f]={...b,totalAdj:y,overallDirection:y>0?"positive":y<0?"negative":"neutral"},r===t.formData.fieldVerifications&&(r={...r}),r[`compGrid_${N}_${f}`]={status:"manual_entry",source:"Sales Grid"},i=!0;continue}if(d.identity.compId==="subject"){const f=d.fieldName==="garageCarport"?"garageParking":d.fieldName==="design"?"designStyle":d.fieldName==="NeighborhoodName"?"neighborhoodName":d.fieldName==="locationComparison"?"location":["siteLocationType","neighborhoodClassification"].includes(d.fieldName)?"locationType":d.fieldName==="SiteInfluenceType"?"siteInfluence":["attachedDetached","AttachedDetached","AttachmentType"].includes(d.fieldName)?"attachmentType":d.fieldName;if(!["heatingCooling","garageParking","porchPatioDeck","designStyle","VehicleStorageItems","baths","fullBathrooms","halfBathrooms","neighborhoodName","location","locationType","siteInfluence","attachmentType"].includes(f))continue;n===t.formData.evalCellValues&&(n={...n});const v=tf(f);if(n[v]=c(d.value===""?null:d.value,d,n[v]),f==="VehicleStorageItems")try{const S=JSON.parse(String(d.value??"[]"));if(Array.isArray(S)){const N=my(S,S.length===0),x=tf("garageParking");n[x]=c(N,d,n[x])}}catch{}r===t.formData.fieldVerifications&&(r={...r}),r[f]={status:"manual_entry",source:"Sales Grid"},i=!0;continue}const p=s.length===0,u=d.identity.mlsNumber||d.identity.compId||d.identity.snapshotId||d.identity.address,m=p&&u?[{c
53ompId:u,address:d.identity.address||"",saleDate:"",quality:"",condition:""}]:s,h=lq(m,d);if(h.acceptedFields.length!==0){!p&&h.rows!==s&&(s=h.rows),i=!0,r===t.formData.fieldVerifications&&(r={...r});for(const f of h.acceptedFields){if(p||(r[`compGrid_${f}_${h.rowIndex}`]={status:"manual_entry",source:"Sales Grid"}),f==="vehicleStorageItems"||f==="vehicleStorageExplicitNone")continue;n===t.formData.evalCellValues&&(n={...n});const v=h.rows[h.rowIndex],S=kc(v.compId,f),N=n[S],y=(f==="attachmentType"||f==="neighborhoodName")&&!!(N&&(N.manual||N.editedAt&&N.editedAt!=="property-lab-selection"));y&&(s=s.map((b,j)=>j===h.rowIndex?{...b,[f]:N.value==null?"":String(N.value)}:b)),n[S]=y?N:c(v[f]??null,d,N)}}}return i?{...t,formData:{...t.formData,compGridRows:s,fieldVerifications:r,evalCellValues:n}}:t}function JJ({children:t,orderId:a,onCompGridRowsChange:s,onSubjectVehicleStorageItemsChange:r,onRegisterCompGridFieldEdit:n,onCustomComparisonFactorsChange:i,onRegisterCustomComparisonFactorsSetter:l}){const c=!!(a&&l0.has(a)),[d,p]=o.useState(()=>c?l0.get(a):Gj),[u,m]=o.useState("all"),h=u!=="all",f=o.useCallback(Oe=>m(Oe?"missing":"all"),[]),[v,S]=o.useState("idle"),[N,x]=o.useState(null),y=o.useRef(null),[b,j]=o.useState(()=>!a||c),T=o.useRef(!1),O=o.useRef(!1),E=o.useRef([]),R=o.useMemo(()=>({state:d,verificationFilter:u,saveStatus:v,saveError:N,isHydrated:b}),[d,u,v,N,b]),G=o.useRef(R);G.current=R;const U=o.useRef(new Set);o.useEffect(()=>{U.current.forEach(Oe=>Oe())},[R]);const C=o.useRef(c?a:null),F=o.useRef(a||null),A=o.useRef(!a||c),M=o.useRef(null),B=o.useRef(null),oe=o.useRef(!1),ae=o.useRef(-1),D=o.useRef(0),_=o.useRef(0),$=3,z=o.useRef(null),V=o.useRef(null),le=o.useRef(-1),W=o.useRef(null),me=o.useRef(d.formData),Z=o.useRef(-1),pe=o.useRef([]),se=o.useRef(0),fe=o.useRef(a);fe.current!==a&&(fe.current=a,se.current+=1);const ue=o.useRef(d.formData),be=o.useRef(d.formData),H=o.useRef(0),ye=o.useRef(null);be.current!==d.formData&&(be.current=d.formData,ue.current=d.formData,H.current+=1),o.useEffect(()=>{if(!a){F.current=null,j(!0),A.current=!0;return}if(A.current&&C.current===a){F.current=a;return}const Oe=F.current;Oe&&Oe!==a&&l0.delete(Oe),A.current=!1,C.current=null,j(!1),z.current=null,V.current=null,le.current=-1,W.current=null,me.current=oN,Z.current=-1,B.current=null,_.current=0,E.current=[],oe.current=!1,ae.current=-1,M.current&&(clearTimeout(M.current),M.current=null),S("idle"),x(null),y.current=null,Oe!==a&&(pe.current.splice(0).forEach(Ce=>Ce(!1)),s?.([]),p(Gj)),F.current=a;const rt=a,$t=se.current,na=()=>fe.current===rt&&se.current===$t,zt=[2e3,5e3],Ua=async(Ce=0)=>{let St=!1;try{const vt=await fetch(`/api/eval/report/${rt}`,{credentials:"include"});if(!na())return;if(vt.ok){const Ve=await vt.json();if(!na())return;const sa=Ve?.draft;W.current=typeof sa?.updatedAt=="string"?sa.updatedAt:sa?.updatedAt instanceof Date?sa.updatedAt.toISOString():null;const tt=typeof Ve?.enrichedAt=="string"&&Ve.enrichedAt?Ve.enrichedAt:null;if(sa&&sa.payload&&typeof sa.payload=="object"){const it=wO(sa.payload),Je=QJ(it);me.current=Je??it,p(ht=>({...ht,formData:Je??it,enrichedAt:tt,restoredFieldKeys:Object.keys(sa.payload)}))}else tt&&p(it=>({...it,enrichedAt:tt}))}else vt.status>=500&&Ce<zt.length?St=!0:console.warn("[Eval Wizard] Draft load returned",vt.status)}catch(vt){if(!na())return;Ce<zt.length?St=!0:console.warn("[Eval Wizard] Failed to load draft:",vt)}if(St)return await new Promise(vt=>setTimeout(vt,zt[Ce])),na()?Ua(Ce+1):void 0;na()&&(j(!0),A.current=!0,C.current=rt)};Ua()},[s,a]);const de=o.useCallback(async(Oe,rt=H.current,$t=_p(Oe).serialized)=>{if(!a)return;const na=a,zt=se.current,Ua=()=>fe.current===na&&se.current===zt,Ce=W.current,St=Math.max(0,_.current-Date.now());if(St>0){B.current={formData:Oe,generation:rt,serialized:$t},M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{if(!Ua())return;const vt=B.current;B.current=null,vt&&de(vt.formData,vt.generation,vt.serialized)},St);return}if(oe.current){B.current={formData:Oe,generation:rt,serialized:$t};return}oe.current=!0,ae.current=rt,S("saving");try{const vt=await fetch(`/api/eval/report/${na}`,{method:"PUT",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:_p(Oe).payload,snapshotGeneration:rt,expectedUpdatedAt:Ce})});if(!Ua())return;if(!vt.ok){let it="",Je=null;try{const Kt=await vt.json();if(!Ua())return;Je=Kt,Kt&&typeof Kt.error=="string"&&(it=Kt.error)}catch{}if(!Ua())return;
53vt.status===409&&(typeof Je?.currentVersion=="string"||Je?.currentVersion===null)&&(W.current=Je.currentVersion);const ht=new Error(it||`Save failed (HTTP ${vt.status})`);if(ht.httpStatus=vt.status,vt.status===429){const Kt=vt.headers.get("Retry-After");if(Kt){const Sa=Number(Kt),Qt=Date.parse(Kt);ht.retryAfterMs=Number.isFinite(Sa)?Math.max(1e3,Sa*1e3):Number.isFinite(Qt)?Math.max(1e3,Qt-Date.now()):6e4}else ht.retryAfterMs=6e4}if(vt.status===409){const Kt=wO(Je?.currentDraft?.payload),{merged:Sa,conflictPaths:Qt}=ZJ(me.current,ue.current,Kt);if(me.current=Kt,M.current&&(clearTimeout(M.current),M.current=null),Qt.length===0){H.current+=1;const ea=H.current,tr=_p(Sa).serialized;ue.current=Sa,be.current=Sa,B.current={formData:Sa,generation:ea,serialized:tr},p(ir=>({...ir,formData:Sa})),ht.versionConflict=!0}else B.current=null,H.current+=1,Z.current=H.current,ue.current=Sa,be.current=Sa,p(ea=>({...ea,formData:Sa})),ht.mergeConflictPaths=Qt,ht.message=`Draft also changed in another session (${Qt.slice(0,3).join(", ")}). Review your edits, then choose overwrite.`}throw ht}const Ve=await vt.json();if(!Ua())return;const sa=Ve?.snapshotGeneration;typeof Ve?.updatedAt=="string"&&(W.current=Ve.updatedAt),V.current=$t,le.current=rt,me.current=Oe,Z.current=-1;const tt=F.current===na&&sa===rt&&rt===H.current&&B.current===null;F.current===na&&(D.current=0,_.current=0,y.current=null,x(null),tt?(S("saved"),ye.current&&clearTimeout(ye.current),ye.current=setTimeout(()=>{S(it=>it==="saved"?"idle":it)},2e3),pe.current.splice(0).forEach(it=>it(!0))):S("saving"))}catch(vt){if(!Ua())return;const Ve=vt?.httpStatus??null,sa=vt?.retryAfterMs??0;Ve===429&&(_.current=Math.max(_.current,Date.now()+sa));const tt=rt!==H.current||B.current!==null,it=vt?.mergeConflictPaths;if(F.current===na&&(!tt||it?.length)){const Je=vt?.versionConflict===!0,ht=vt?.message||"Save failed",Kt=!!it?.length||Ve!==null&&Ve>=400&&Ve<500&&Ve!==408&&Ve!==409&&Ve!==429;S("error"),y.current=Oe;const Sa=D.current;if(!Kt&&Sa<$){D.current=Sa+1;const Qt=Je?0:Math.max(sa,Math.min(3e4,5e3*Math.pow(2,Sa)));_.current=Date.now()+Qt,console.warn("[Eval Wizard] Save failed, retry scheduled",{attempt:Sa+1,backoffMs:Qt,httpStatus:Ve,error:ht}),x({kind:"retrying",status:Ve,message:ht}),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{F.current===na&&de(ue.current,H.current,_p(ue.current).serialized)},Qt)}else console.error("[Eval Wizard] Save failed, not retrying",{httpStatus:Ve,permanent:Kt,error:ht}),x({kind:it?.length?"conflict":"permanent",status:Ve,message:ht}),pe.current.splice(0).forEach(Qt=>Qt(!1))}}finally{if(!Ua())return;if(oe.current=!1,ae.current=-1,B.current&&F.current===na){const vt=B.current;B.current=null,z.current=vt.serialized;const Ve=Math.max(0,_.current-Date.now());Ve>0?(M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{F.current===na&&de(vt.formData,vt.generation,vt.serialized)},Ve)):de(vt.formData,vt.generation,vt.serialized)}else F.current!==na&&(B.current=null)}},[a]),ge=o.useCallback((Oe,rt)=>{D.current=0,M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{const{serialized:$t}=_p(Oe);if($t===z.current){$t===V.current&&rt===H.current&&S("saved");return}z.current=$t,de(Oe,rt,$t)},1e3)},[de]),Be=o.useCallback(()=>{if(!a)return;const Oe=ue.current||y.current;if(!Oe)return;D.current=0,_.current=0,M.current&&(clearTimeout(M.current),M.current=null),Z.current=-1;const{serialized:rt}=_p(Oe);de(Oe,H.current,rt)},[a,de]),He=o.useCallback(()=>{if(!a)return Promise.resolve(!0);if(!A.current||Z.current>=0)return Promise.resolve(!1);const Oe=ue.current,{serialized:rt}=_p(Oe);if(rt===V.current&&!oe.current)return Promise.resolve(!0);M.current&&(clearTimeout(M.current),M.current=null),x(null),S("saving");const $t=H.current;return oe.current?B.current={formData:Oe,generation:$t,serialized:rt}:(z.current=rt,de(Oe,$t,rt)),new Promise(na=>{pe.current.push(na)})},[a,de]);o.useEffect(()=>{if(b&&z.current===null){const{serialized:Oe}=_p(d.formData);z.current=Oe,V.current=Oe,le.current=H.current,me.current=d.formData}},[b,d.formData]),o.useEffect(()=>{if(!a)return;const Oe=rt=>{A.current&&H.current!==le.current&&(rt.preventDefault(),rt.returnValue="")};return window.addEventListener("beforeunload",Oe),()=>window.removeEventListener("beforeunload",Oe)},[a]),o.useEffect(()=>{if(!A.current||!a||z.current===null)return;const Oe=H.current;if(Oe!==le.current&&!(Z.current>
53=0)&&!(Oe===ae.current||Oe===B.current?.generation)){if(ye.current&&(clearTimeout(ye.current),ye.current=null),x(null),S("saving"),oe.current){const{serialized:rt}=_p(d.formData);B.current={formData:d.formData,generation:Oe,serialized:rt}}ge(d.formData,Oe)}},[d.formData,a,ge]),o.useEffect(()=>{a&&b&&l0.set(a,d)},[d,a,b]),o.useEffect(()=>()=>{if(M.current&&clearTimeout(M.current),ye.current&&clearTimeout(ye.current),a&&l0.delete(a),a&&A.current&&Z.current<0&&!oe.current&&ae.current===-1&&Date.now()>=_.current){const Oe=_p(ue.current);H.current!==le.current&&Oe.serialized!==V.current&&fetch(`/api/eval/report/${a}`,{method:"PUT",credentials:"include",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:Oe.payload,snapshotGeneration:H.current,expectedUpdatedAt:W.current})}).catch(()=>{})}},[a]);const Ie=o.useCallback(Oe=>{p(rt=>{const $t=typeof Oe=="function"?Oe(rt.formData):Oe;return{...rt,formData:{...rt.formData,...$t,...$t.fieldVerifications?{fieldVerifications:Object.fromEntries(Object.entries({...rt.formData.fieldVerifications,...$t.fieldVerifications}).filter(([,na])=>na!=null))}:{},...$t.evalCellValues?{evalCellValues:{...rt.formData.evalCellValues,...$t.evalCellValues}}:{}}}})},[]),ce=o.useCallback(Oe=>{const rt=G.current;if(!rt.isHydrated||Oe.identity.compId!=="subject"&&ty(rt.state.formData.compGridRows,Oe.identity)<0){E.current.push(Oe),rt.isHydrated&&rt.state.formData.compGridRows.length===0&&p($t=>Kj($t,[Oe]));return}p($t=>Kj($t,[Oe]))},[]),Pe=o.useCallback(Oe=>{const rt=Ok(Oe);N7(rt).valid&&p($t=>({...$t,formData:{...$t.formData,customComparisonFactors:rt,compGridRows:$t.formData.compGridRows.map(na=>{const zt=XI(na)+LN(rt,na.compId);return{...hb({...na,totalAdj:zt}),totalAdj:zt,overallDirection:zt>0?"positive":zt<0?"negative":"neutral"}})}}))},[]);o.useEffect(()=>{if(!b||E.current.length===0)return;const Oe=[],rt=[];for(const $t of E.current)$t.identity.compId==="subject"||ty(d.formData.compGridRows,$t.identity)>=0?Oe.push($t):rt.push($t);E.current=rt,Oe.length>0&&p($t=>Kj($t,Oe))},[b,d.formData.compGridRows]),o.useEffect(()=>(n?.(ce),()=>n?.(null)),[ce,n]),o.useEffect(()=>(l?.(Pe),()=>l?.(null)),[l,Pe]),o.useEffect(()=>{b&&s?.(d.formData.compGridRows)},[b,s,d.formData.compGridRows]),o.useEffect(()=>{if(!b)return;const Oe=d.formData.evalCellValues[tf("VehicleStorageItems")]?.value;if(typeof Oe!="string"){const rt=tf("garageParking"),$t=Object.prototype.hasOwnProperty.call(d.formData.evalCellValues,rt),na=d.formData.evalCellValues[rt]?.value;r?.([],!1,$t&&na!=null?String(na):"",$t);return}try{const rt=JSON.parse(Oe);r?.(Array.isArray(rt)?rt.slice(0,12):[],Array.isArray(rt)&&rt.length===0,void 0,!1)}catch{r?.([],!1,void 0,!1)}},[b,r,d.formData.evalCellValues]),o.useEffect(()=>{b&&i?.(d.formData.customComparisonFactors)},[b,i,d.formData.customComparisonFactors]),o.useEffect(()=>{if(a)return O.current=!0,nM(a,"eval",(Oe,rt)=>{T.current=!0,p($t=>{const na=Oe,zt=$t.formData.marketValueOpinion==null&&Oe!=null;return{...$t,formData:{...$t.formData,salesComparisonValue:na,...zt?{marketValueOpinion:Oe}:{},fieldVerifications:{...$t.formData.fieldVerifications,salesComparisonValue:{status:rt==="hydrate"?"prefilled_review":"manual_entry",source:"Sales Grid (Synchronized)"},...zt?{marketValueOpinion:{status:"prefilled_review",source:"Sales Comparison Approach (Suggested)"}}:{}}}}})})},[a]),o.useEffect(()=>{!a||!b||!O.current||(T.current=!0,JT(a,"eval",d.formData.salesComparisonValue))},[a,b]),o.useEffect(()=>{if(!(!a||!b||!O.current)){if(T.current){T.current=!1;return}lv(a,"eval",d.formData.salesComparisonValue)}},[a,b,d.formData.salesComparisonValue]);const We=o.useCallback(Oe=>{p(rt=>({...rt,subjectProperty:Oe}))},[]),Re=o.useCallback(Oe=>{p(rt=>({...rt,compsGridData:Oe}))},[]),ne=o.useCallback(Oe=>{p(rt=>({...rt,marketData:Oe}))},[]),Me=o.useCallback(Oe=>{p(rt=>({...rt,selectedCompIds:Oe}))},[]),lt=o.useCallback(Oe=>{p(rt=>({...rt,currentStep:Oe}))},[]),Tt=o.useCallback(Oe=>{p(rt=>({...rt,evalSubStep:Oe}))},[]),je=o.useCallback(Oe=>{p(rt=>({...rt,activeSection:Oe}))},[]),Le=o.useCallback(Oe=>{p(rt=>({...rt,reportId:Oe}))},[]),ut=o.useCallback(Oe=>{p(rt=>({...rt,templateId:Oe}))},[]),st=o.useCallback(Oe=>{p(rt=>({...rt,enrichmentLoaded:Oe}))},[]),Xt=o.useCallback((Oe,rt)=>{p($t=>({...$t,formData:{...$t.formData,fieldVerifications:{...$t.formData.fieldVerifications,[Oe]:rt}}}))},[]),ua=o.useCallback((Oe,rt,$t)=>{p(na=>({...na,formData:{...na.formData,[Oe]:rt,fieldVerifications:{...na.formData.fieldVerifications,[Oe]:{status:"overridden",source:$t,verifiedAt:new Date().toISOString()}}}}))},[]),Oa=o.useCallback(()=>{p(Gj)},[]),Xa=o.useCallback(Oe=>YJ(G.current.state.formData,Oe),[]),qa=o.useCallback(Oe=>cN(G.current.state.formData,Oe),[]),os=o.useCallback(()=>RO(G.current.state.formData,EO),[]),ya=o.useCallback(Oe=>RO(G.current.state.formData,FN[Oe]||[]),[]),At=o.useCallback(()=>{p(Oe=>{const rt={...Oe.formData.fieldVerifications};let $t=!1;for(const na of EO)if(!gC.has(na)&&cN(Oe.formData,na)==="unconfirmed"){const zt
53=Oe.formData.fieldVerifications[na];rt[na]={status:"auto_verified",source:zt?.source||"user",verifiedAt:new Date().toISOString()},$t=!0}for(const na of lN)for(let zt=0;zt<Oe.formData.compGridRows.length;zt++)if(WM(Oe.formData,na,zt)==="unconfirmed"){const Ua=`compGrid_${na}_${zt}`,Ce=Oe.formData.fieldVerifications[Ua];rt[Ua]={status:"auto_verified",source:Ce?.source||"user",verifiedAt:new Date().toISOString()},$t=!0}return $t?{...Oe,formData:{...Oe.formData,fieldVerifications:rt}}:Oe})},[]),Fe=o.useMemo(()=>({subscribe:Oe=>(U.current.add(Oe),()=>{U.current.delete(Oe)}),getSnapshot:()=>G.current,actions:{setNeedsAttentionFilter:f,setVerificationFilter:m,getFieldBucket:qa,getOverallBuckets:os,getSectionBuckets:ya,getSectionCompletion:Xa,confirmAllUnconfirmed:At,setFormData:Ie,setSubjectProperty:We,setCompsGridData:Re,setMarketData:ne,setSelectedCompIds:Me,setCurrentStep:lt,setEvalSubStep:Tt,setActiveSection:je,setReportId:Le,setTemplateId:ut,setEnrichmentLoaded:st,setFieldVerification:Xt,resolveConflict:ua,resetState:Oa,retrySave:Be,flushSave:He}}),[He,Be]);return e.jsx(qM.Provider,{value:Fe,children:e.jsx(zM.Provider,{value:{state:d,needsAttentionFilter:h,setNeedsAttentionFilter:f,verificationFilter:u,setVerificationFilter:m,getFieldBucket:qa,getOverallBuckets:os,getSectionBuckets:ya,confirmAllUnconfirmed:At,setFormData:Ie,setSubjectProperty:We,setCompsGridData:Re,setMarketData:ne,setSelectedCompIds:Me,setCurrentStep:lt,setEvalSubStep:Tt,setActiveSection:je,setReportId:Le,setTemplateId:ut,setEnrichmentLoaded:st,setFieldVerification:Xt,resolveConflict:ua,resetState:Oa,getSectionCompletion:Xa,saveStatus:v,saveError:N,retrySave:Be,flushSave:He,isHydrated:b},children:t})})}function hte(){const t=o.useContext(zM);if(!t)throw new Error("useEvalWizard must be used within an EvalWizardProvider");return t}function fte(t){return YM(a=>XJ(a.state.formData,t))}function XJ(t,a){let s=0;for(const{fieldKey:r}of a)HM(t,r)&&s++;return s}const _N=9,eX={location:"locationAdj",locationAdj:"locationAdj",gla:"glaAdj",glaAdj:"glaAdj",site:"lotSizeAdj",lotSizeAdj:"lotSizeAdj",age:"ageAdj",yearBuilt:"ageAdj",ageAdj:"ageAdj",condition:"conditionAdj",conditionAdj:"conditionAdj",quality:"qualityAdj",qualityCondition:"qualityAdj",qualityAdj:"qualityAdj",view:"viewAdj",viewAdj:"viewAdj",heating:"heatingCoolingAdj",heatingCooling:"heatingCoolingAdj",heatingCoolingAdj:"heatingCoolingAdj",aboveGrade:"bedsAdj",bedsAdj:"bedsAdj",bathsAdj:"bathsAdj",garage:"garageAdj",garageCarport:"garageAdj",garageParking:"garageAdj",garageAdj:"garageAdj",porchPatioDeck:"porchPatioDeckAdj",porchPatioDeckAdj:"porchPatioDeckAdj",basement:"basementAdj",basementAdj:"basementAdj",dateOfSale:"marketConditionsAdj",marketConditionsAdj:"marketConditionsAdj",otherAdj:"otherAdj"};function tX(t){return eX[t]??null}function mi(t,...a){for(const s of a){if(!Object.prototype.hasOwnProperty.call(t,s))continue;const r=Number(t[s]);return Number.isFinite(r)?r:0}return 0}function KM(t){const a=Object.prototype.hasOwnProperty.call(t,"otherAdj"),s=Object.prototype.hasOwnProperty.call(t,"qualityAdj")||Object.prototype.hasOwnProperty.call(t,"quality")||Object.prototype.hasOwnProperty.call(t,"conditionAdj")||Object.prototype.hasOwnProperty.call(t,"condition"),r=Object.prototype.hasOwnProperty.call(t,"bedsAdj")||Object.prototype.hasOwnProperty.call(t,"bedrooms")||Object.prototype.hasOwnProperty.call(t,"bathsAdj")||Object.prototype.hasOwnProperty.call(t,"bathrooms"),n=Object.prototype.hasOwnProperty.call(t,"saleType")||Object.prototype.hasOwnProperty.call(t,"concessions");return{locationAdj:mi(t,"locationAdj","location"),glaAdj:mi(t,"glaAdj","gla"),lotSizeAdj:mi(t,"lotSizeAdj","site"),ageAdj:mi(t,"ageAdj","age","yearBuilt"),conditionAdj:mi(t,"conditionAdj","condition"),qualityAdj:s?mi(t,"qualityAdj","quality"):mi(t,"qualityCondition"),viewAdj:mi(t,"viewAdj","view"),heatingCoolingAdj:mi(t,"heatingCoolingAdj","heatingCooling","heating"),bedsAdj:r?mi(t,"bedsAdj","bedrooms"):mi(t,"aboveGrade"),bathsAdj:mi(t,"bathsAdj","bathrooms"),garageAdj:mi(t,"garageAdj","garageParking","garageCarport","garage"),porchPatioDeckAdj:mi(t,"porchPatioDeckAdj","porchPatioDeck"),basementAdj:mi(t,"basementAdj","basement"),marketConditionsAdj:mi(t,"marketConditionsAdj","dateOfSale"),otherAdj:a?mi(t,"otherAdj"):mi(t,"porch")+mi(t,"pool")+mi(t,"design")+mi(t,"attachedDetached")+mi(t,"belowGrade")+mi(t,"functionalUtility")+mi(t,"energyEfficient")+mi(t,"leaseholdFeeSimple")+(n?mi(t,"saleType")+mi(t,"concessions"):mi(t,"financingConcessions"))}}function QM(t,a){const s=[t.compId,t.id,t.mlsNumber,mf(t)];for(const r of s)if(r&&a[r])return a[r]}function aX(t,a){const s=KM(a);return Object.entries(s).every(([r,n])=>
53Number(t[r]??0)===n)?t:{...t,...s}}function sX(t,a){let s=!1;const r=t.map(n=>{const i=XI(n)+LN(a,n.compId),l=hb({...n,totalAdj:i}),c=i>0?"positive":i<0?"negative":"neutral";return n.totalAdj===i&&n.salePricePerSf===l.salePricePerSf&&n.adjustedPrice===l.adjustedPrice&&n.adjustedPricePerSf===l.adjustedPricePerSf&&n.gla===l.gla&&n.overallDirection===c?n:(s=!0,{...l,overallDirection:c})});return s?r:t}function mf(t){return t.mlsNumber||t.compId||t.address}const md=t=>(t||"").toLowerCase().replace(/[^a-z0-9]/g,"");function ZM(t,a,s,r){const n=md(s.address);if(!n||a.filter(l=>md(l.address)===n).length!==1)return;const i=t.filter(l=>md(l.address)===n);return i.length===1&&i[0].compId!==r?i[0]:void 0}const bC=(t,a)=>t.cleanedFields?.find(s=>s.fieldKey===a)?.finalValue??null,Rl=(t,a)=>{const s=bC(t,a);return s==null?"":String(s)},c0=(t,a)=>{const s=Number(bC(t,a));return Number.isFinite(s)&&s!==0?s:null},JM=t=>{const a=t.cleanedFields?.find(s=>s.fieldKey==="attachmentType")??t.cleanedFields?.find(s=>s.fieldKey==="attachedDetached");return a?a.finalValue==null?"":String(a.finalValue):t.attachmentType==null?"":String(t.attachmentType)};function XM(t,a){if(t===null)return null;if(t===void 0||t==="")return;if(typeof t=="string"&&t.includes("|")){const r=t.trim().split("|");if(r.length!==3)return;const n=r[2].trim().split(".");if(n.length>2||n[0]==="")return;const i=a==="full"?n[0]:n[1]??"0",l=Number(i);return Number.isFinite(l)&&l>=0?l:void 0}const s=Number(String(t).replace(/[$,\s]/g,""));return Number.isFinite(s)&&s>=0?s:void 0}function dN(t,a){const s=a==="full"?["fullBathrooms","fullBaths","BathroomsFull"]:["halfBathrooms","halfBaths","BathroomsHalf"];return t.cleanedFields?.find(r=>s.includes(r.fieldKey))??t.cleanedFields?.find(r=>r.fieldKey==="aboveGrade")}function cb(t,a){const s=a==="full"?t.fullBathrooms:t.halfBathrooms;if(s!==void 0)return s??null;const r=dN(t,a),n=XM(r?.finalValue,a);return n===void 0?null:n}function rX(t,a){const s=dN(t,a);return s?b0(s).map(r=>({source:r.source,value:XM(r.value,a)})).filter(r=>r.value!==void 0):[]}const yC=t=>{const a=t,s=Lu("lotSize",bC(t,"lotSize")),r=Lu("lotSize",a.lotSize);return(typeof s=="number"?s:null)??(typeof r=="number"?r:null)},db=t=>{const a=t,s=["siteInfluence","SiteInfluenceType","location"].map(r=>t.cleanedFields?.find(n=>n.fieldKey===r)).find(Boolean);return s?s.finalValue==null?"":String(s.finalValue):String(a.siteInfluence??a.SiteInfluenceType??"")};function SC(t){const a=t;for(const s of["locationType","siteLocationType","neighborhoodClassification"]){const r=t.cleanedFields?.find(n=>n.fieldKey===s);if(r)return r.finalValue==null?"":String(r.finalValue);if(a[s]!==void 0)return String(a[s]??"")}return""}const sf=t=>t!=null&&String(t).trim()!=="",G0=(t,a)=>sf(t)&&sf(a)&&String(t).trim().toLowerCase()===String(a).trim().toLowerCase();function vC(t){return sf(t.siteInfluence)&&sf(t.location)&&G0(t.siteInfluence,t.location)}function nX(t,a,s=[]){const r=lk(t);let n=r;for(const i of a.slice(0,_N)){const l=mf(i),c=s.find(f=>f.compId===l)??(s.filter(f=>md(f.address)===md(i.address)).length===1?s.find(f=>md(f.address)===md(i.address)):void 0),d=kc(l,"siteInfluence"),p=n[d];if(!p||Hl(p))continue;const u=n[kc(l,"location")],m=c?vC(c):!1,h=u&&!Hl(u)&&G0(p.value,u.value);(m||h)&&(sf(u?.value)&&!G0(p.value,u.value)||!sf(u?.value)&&m&&!G0(p.value,c?.siteInfluence)||!sf(u?.value)&&!m||(n===r&&(n={...n}),delete n[d]))}return n}function gte(t,a,s){return t.map(r=>{const n=a.find(c=>mf(c)===r.compId)??(a.filter(c=>md(c.address)===md(r.address)).length===1?a.find(c=>md(c.address)===md(r.address)):void 0);if(!vC(r))return r;const i=s?.[kc(r.compId,"siteInfluence")];if(Hl(i))return r;if(sf(i?.value)&&!G0(i?.value,r.siteInfluence)){const c=n?db(n):String(i.value);return r.siteInfluence===c?r:{...r,siteInfluence:c}}const l=n?db(n):"";return r.siteInfluence===l?r:{...r,siteInfluence:l}})}const eF=t=>{const a=Rl(t,"designStyle")||Rl(t,"style")||Rl(t,"architecturalStyle")||Rl(t,"design");return gg(a)||a},NC=t=>{const a=t.cleanedFields?.find(s=>s.fieldKey==="neighborhoodName"||s.fieldKey==="NeighborhoodName");return a?.finalValue==null?"":String(a.finalValue)};
53function tF(t,a,s,r){const i=(s-t)*Math.PI/180,l=(r-a)*Math.PI/180,c=Math.sin(i/2)**2+Math.cos(t*Math.PI/180)*Math.cos(s*Math.PI/180)*Math.sin(l/2)**2;return Math.round(3958.8*2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))*100)/100}function iX(t,a,s){const r=mf(t),{locationAdj:n,glaAdj:i,lotSizeAdj:l,ageAdj:c,conditionAdj:d,qualityAdj:p,viewAdj:u,heatingCoolingAdj:m,bedsAdj:h,bathsAdj:f,garageAdj:v,porchPatioDeckAdj:S,basementAdj:N,marketConditionsAdj:x,otherAdj:y}=KM(QM(t,a)??{}),b=n+i+l+c+d+p+u+m+h+f+v+S+N+x+y,j=py(t.price),T=j!==null?j+b:null,O=[Rl(t,"basement"),Rl(t,"basementFinishedSf")?`${Rl(t,"basementFinishedSf")} SF Fin`:""].filter(Boolean).join(" / "),E=WI(t).values,R={finishedAboveGrade:E.finishedAboveGrade,nonstandardFinishedAboveGrade:E.nonstandardFinishedAboveGrade,gla:t.gla};return{compId:r,address:t.address,salePrice:j,salePricePerSf:ob(j,R),saleDate:t.saleDate||t.contractDate||"",proximity:s&&t.latitude&&t.longitude?tF(s.lat,s.lng,t.latitude,t.longitude):null,gla:aF(R),finishedAboveGrade:E.finishedAboveGrade,unfinishedAboveGrade:E.unfinishedAboveGrade,finishedBelowGrade:E.finishedBelowGrade,unfinishedBelowGrade:E.unfinishedBelowGrade,nonstandardFinishedAboveGrade:E.nonstandardFinishedAboveGrade,nonstandardFinishedBelowGrade:E.nonstandardFinishedBelowGrade,belowGradeExteriorAccess:String(E.belowGradeExteriorAccess??""),lotSize:yC(t),beds:t.beds||null,baths:t.baths||null,fullBathrooms:cb(t,"full"),halfBathrooms:cb(t,"half"),yearBuilt:c0(t,"yearBuilt"),condition:t.condition||"",quality:t.quality||"",designStyle:eF(t),neighborhoodName:NC(t),attachmentType:JM(t),locationType:SC(t),siteInfluence:db(t),totalRooms:c0(t,"totalRooms")??c0(t,"aboveGradeTotal"),view:t.viewComparison||t.view||"",heatingCooling:Rl(t,"heatingCooling"),rightsConveyed:"Fee Simple",financingConcessions:"None",listDate:t.listDate||"",listPrice:t.listPrice??null,listPricePerSf:t.listPrice&&t.gla?Math.round(t.listPrice/t.gla):null,listingStatus:t.listingStatus||"",dataSource:t.mlsNumber?`MLS #${t.mlsNumber}`:"MLS",locationAdj:n,glaAdj:i,lotSizeAdj:l,ageAdj:c,conditionAdj:d,qualityAdj:p,viewAdj:u,heatingCoolingAdj:m,bedsAdj:h,bathsAdj:f,garageAdj:v,porchPatioDeckAdj:S,basementAdj:N,marketConditionsAdj:x,otherAdj:y,totalAdj:b,adjustedPrice:T,adjustedPricePerSf:ob(T,R),overallDirection:b>0?"positive":b<0?"negative":"neutral",location:t.locationComparison||"",garageParking:t.vehicleStorageItems!==void 0?my(t.vehicleStorageItems,t.vehicleStorageExplicitNone):Rl(t,"garage")||(c0(t,"garageSpaces")!==null?`${c0(t,"garageSpaces")} Car Garage`:""),vehicleStorageItems:t.vehicleStorageItems,vehicleStorageExplicitNone:t.vehicleStorageExplicitNone,vehicleStorageUserEdited:!1,porchPatioDeck:Rl(t,"porchPatioDeck")||Rl(t,"porch")||Rl(t,"patio")||Rl(t,"deck"),basementFinished:O,marketConditionsDesc:"Market",stories:t.stories??null,photoUrl:sF(t)}}const aF=t=>GI(t);function sF(t){return t.photoUrl?t.photoUrl:Array.isArray(t.photos)&&t.photos.length>0&&t.photos[0]?t.photos[0]:null}function oX(t,a,s){const r=py(a.price),n=WI(a).values,i=n.finishedAboveGrade??a.gla??null,l=n.nonstandardFinishedAboveGrade,c={finishedAboveGrade:i,nonstandardFinishedAboveGrade:l,gla:a.gla},d=aF(c),p=s!=null&&a.latitude!=null&&a.longitude!=null?tF(s.lat,s.lng,a.latitude,a.longitude):t.proximity,u=t.vehicleStorageItems===void 0&&t.vehicleStorageExplicitNone===void 0&&!!t.garageParking?.trim(),m=t.vehicleStorageUserEdited!==!0&&!u,h=JSON.stringify(t.vehicleStorageItems)===JSON.stringify(a.vehicleStorageItems)?t.vehicleStorageItems:a.vehicleStorageItems,f=a.vehicleStorageItems!==void 0?my(a.vehicleStorageItems,a.vehicleStorageExplicitNone):"",v=vC(t),S={compId:mf(a),address:a.address,salePrice:r,salePricePerSf:ob(r,c),saleDate:a.saleDate||a.contractDate||"",proximity:p,gla:d,finishedAboveGrade:i,unfinishedAboveGrade:t.unfinishedAboveGrade??n.unfinishedAboveGrade,finishedBelowGrade:t.finishedBelowGrade??n.finishedBelowGrade,unfinishedBelowGrade:t.unfinishedBelowGrade??n.unfinishedBelowGrade,nonstandardFinishedAboveGrade:l,nonstandardFinishedBelowGrade:t.nonstandardFinishedBelowGrade??n.nonstandardFinishedBelowGrade,lotSize:t.lotSize??yC(a),belowGradeExteriorAccess:t.belowGradeExteriorAccess||String(n.belowGradeExteriorAccess??""),beds:a.beds||null,baths:a.baths||null,fullBathrooms:t.fullBathrooms??cb(a,"full"),halfBathrooms:t.halfBathrooms??cb(a,"half"),listDate:a.listDate||"",listPrice:a.listPrice??null,listPricePerSf:a.listPrice&&a.gla?Math.round(a.listPrice/a.gla):null,listingStatus:a.listingStatus||"",dataSource:a.mlsNumber?`MLS #${a.mlsNumber}`:t.dataSource||"MLS",heatingCooling:Rl(a,"heatingCooling")||t.heatingCooling,porchPatioDeck:t.porchPatioDeck||Rl(a,"porchPatioDeck")||Rl(a,"porch")||Rl(a,"patio")||Rl(a,"deck"),marketConditionsDesc:t.marketConditionsDesc||"Market",view:t.view||a.viewComparison||a.view||"",quality:t.quality||a.quality||"",condition:t.condition||a.condition||"",designStyle:t.designStyle||eF(a),neighborhoodName:t.neighborhoodName||NC(a),...m?{garageParking:f,vehicleStorageItems:h,vehicleStorageExplicitNone:a.vehicleStorageExplicitNone,vehicleStorageUserEdited:!1}:{},location:t.location||a.locationComparison||"",locationType:t.locationType??SC(a),siteInfluence:v?db(a):t.siteInfluence||db(
53a),attachmentType:t.attachmentType||JM(a)||"",stories:t.stories!==null&&t.stories!==void 0?t.stories:a.stories??null,photoUrl:sF(a)};let N=!1;for(const[y,b]of Object.entries(S))if(t[y]!==b){N=!0;break}if(!N)return t;const x={...t,...S};return x.adjustedPrice=x.salePrice?x.salePrice+(x.totalAdj||0):null,x.adjustedPricePerSf=ob(x.adjustedPrice,x),x}function lX(t,a,s=[]){const r=nX(t,a,s);let n=r;const i=(l,c)=>{JSON.stringify(n[l])!==JSON.stringify(c)&&(n===r&&(n={...r}),n[l]=c)};for(const l of a.slice(0,_N)){const c=mf(l),d=ZM(s,a,l,c);if(d){const f=`comp.${d.compId}.`;for(const[v,S]of Object.entries(r)){if(!v.startsWith(f))continue;const N=`comp.${c}.${v.slice(f.length)}`,x=r[N];(Hl(S)&&!Hl(x)||!df(x)&&df(S))&&i(N,S)}}const p=WI(l),u={salePrice:{value:l.price??null},saleDate:{value:l.saleDate||l.contractDate||""},finishedAboveGrade:{value:l.gla??null},gla:{value:l.gla??null},beds:{value:l.beds??null},baths:{value:l.baths??null},fullBathrooms:{value:cb(l,"full")},halfBathrooms:{value:cb(l,"half")},lotSize:{value:yC(l)},siteInfluence:{value:db(l)},location:{value:l.locationComparison??""},locationType:{value:SC(l)},neighborhoodName:{value:NC(l)}};for(const[f,v]of Object.entries(u)){const S=kc(c,f),N=f==="fullBathrooms"?dN(l,"full"):f==="halfBathrooms"?dN(l,"half"):void 0,x=y0(n[S],Lu(f,v.value),N?String(N.source):l.mlsNumber?`MLS #${l.mlsNumber}`:"MLS",N?N.fieldKey==="aboveGrade"?rX(l,f==="fullBathrooms"?"full":"half"):b0(N):[]),b=N?.comment==="Property Lab selected source"&&(!Hl(n[S])||n[S]?.editedAt==="property-lab-selection");i(S,b?{...x,value:v.value,source:String(N?.source||"manual"),manual:!1,editedAt:n[S]?.editedAt||"property-lab-selection"}:x)}for(const[f,v]of Object.entries(p.values)){const S=kc(c,f),N=p.fields[f];i(S,y0(n[S],v,N?String(N.source):l.mlsNumber?`MLS #${l.mlsNumber}`:"MLS",b0(N,f)))}const m=l.cleanedFields?.find(f=>f.fieldKey==="attachmentType")??l.cleanedFields?.find(f=>f.fieldKey==="attachedDetached"),h=m?m.finalValue:l.attachmentType??null;if(m||l.attachmentType!==void 0){const f=kc(c,"attachmentType"),v=y0(n[f],h,String(m?m.source:l.attachmentTypeSource||"Property Lab"),m?b0(m):[]),N=m?.comment==="Property Lab selected source"&&(!Hl(n[f])||n[f]?.editedAt==="property-lab-selection");i(f,N?{...v,value:h,source:String(m?.source||"manual"),manual:!1,editedAt:n[f]?.editedAt||"property-lab-selection"}:v)}for(const f of l.cleanedFields||[]){if(["location","SiteInfluenceType"].includes(f.fieldKey)&&l.cleanedFields.some(y=>y.fieldKey==="siteInfluence"||f.fieldKey==="location"&&y.fieldKey==="SiteInfluenceType"))continue;const v=f.fieldKey==="NeighborhoodName"?"neighborhoodName":f.fieldKey==="locationComparison"?"location":["siteLocationType","neighborhoodClassification"].includes(f.fieldKey)?"locationType":f.fieldKey==="location"||f.fieldKey==="SiteInfluenceType"||f.fieldKey==="siteInfluence"?"siteInfluence":f.fieldKey,S=kc(c,v),N=y0(n[S],Lu(v,f.finalValue),String(f.source),b0(f,v)),x=f.comment==="Property Lab selected source"&&(!Hl(n[S])||n[S]?.editedAt==="property-lab-selection");i(S,x?{...N,value:Lu(v,f.finalValue),source:String(f.source),manual:!1,editedAt:"property-lab-selection"}:N)}}return n}function xte(t,a,s=[]){const r={};for(const n of a.slice(0,_N)){const i=mf(n),l=ZM(s,a,n,i);l?.compId&&(r[l.compId]=i)}return j7(t,r)}function bte(t,a,s,r,n,i=[]){if(a.length===0)return{rows:t,added:[],removed:[],newRowIndices:[],changed:!1};const l=a.slice(0,_N),c=n?lX(n,l,t):void 0,d=new Map,p=new Map;for(const y of t){y.compId&&!d.has(y.compId)&&d.set(y.compId,y);const b=md(y.address);b&&p.set(b,[...p.get(b)||[],y])}const u=new Map;for(const y of l){const b=md(y.address);b&&u.set(b,(u.get(b)||0)+1)}const m=new Set,h=[],f=[],v=l.map((y,b)=>{const j=mf(y);let T=d.get(j);if(!T||m.has(T)){const E=md(y.address),R=E?p.get(E)||[]:[],G=u.get(E)===1&&R.length===1?R[0]:void 0;T=G&&!m.has(G)?G:void 0}if(!T)return h.push(y.address),f.push(b),PO(iX(y,s,r),c);m.add(T);const O=PO(oX(T,y,r),c);return aX(O,QM(y,s)??{})}),S=t.filter(y=>!m.has(y)).map(y=>y.address),N=sX(v,i),x=N.length!==t.length||N.some((y,b)=>y!==t[b]);return{rows:N,added:h,removed:S,newRowIndices:f,changed:x}}function PO(t,a){if(!a)return t;let s=t;for(const i of["saleDate","salePrice","gla","finishedAboveGrade","unfinishedAboveGrade","finishedBelowGrade","unfinishedBelowGrade","nonstandardFinishedAboveGrade","nonstandardFinishedBelowGrade","belowGradeExteriorAccess","beds","baths","fullBathrooms","halfBathrooms","lotSize","yearBuilt","listDate","listPrice","listingStatus","heatingCooling","marketConditionsDesc","view","quality","condition","designStyle","neighborhoodName","attachmentType","siteInfluence","location","locationType","totalRooms","stories","rightsConveyed","financingConcessions","garageParking","porchPatioDeck"]){const l=a[kc(t.compId,i)];df(l)&&s[i]!==l.value&&(s===t&&(s={...t}),s[i]=l.value)}const r=a[kc(t.compId,"finishedAboveGrade")];df(r)&&t.gla!==r.value&&(s===t&&(s={...t}),s.gla=typeof r.value=="number"?r.value:null);const n=hb(s);return s===t&&t.gla===n.gla&&t.salePricePerSf===n.salePricePerSf&&t.adjustedPrice===n.adjustedPrice&&t.adjustedPricePerSf===n.adjustedPricePerSf?t:n}function yte(t,a){const s={},r=["locationAdj","glaAdj","lotSizeAdj","ageAdj","conditionAdj","qualityAdj","viewAdj","heatingCoolingAdj","bedsAdj","bathsAdj","garageAdj","porchPatioDeckAdj","basementAdj","marketConditionsAdj","otherAdj"];for(const n of a){const i=t[n];if(i){i.rightsConveyed&&(s[`compGrid_rightsConveyed_${n}
53`]={status:"auto_verified",source:"Core"}),i.financingConcessions&&(s[`compGrid_financingConcessions_${n}`]={status:"auto_verified",source:"Core"});for(const l of r){const c=i[l]!==0;s[`compGrid_${l}_${n}`]=c?{status:"prefilled_review",source:"Core Grid"}:{status:"manual_entry",source:"user"}}}}return s}function OO(t){const a=t?.salesData||[],s=t?.propertyCards||[],r=s.length>0?s:a,n=t?.stats;if(r.length===0&&!n)return null;const i=oe=>{if(String(oe??"").trim()==="")return"sold";const ae=av(oe);return ae==="underContract"?"pending":ae},l=r.filter(oe=>i(oe.status)==="active").length,c=r.filter(oe=>i(oe.status)==="pending").length,d=r.filter(oe=>i(oe.status)==="sold").length,p=t?.lookbackMonths??t?.filters?.monthsBack??t?.filters?.dateRangePreset,u=typeof p=="number"&&p>0?p:12,m=d/Math.max(u,1),h=m>0?Math.round(l/m*10)/10:0,f=m>0&&d+l>0?Math.round(d/(d+l)*100):0,v=r.map(oe=>oe.price||oe.salePrice||0).filter(oe=>oe>0).sort((oe,ae)=>oe-ae),S=r.map(oe=>oe.dom??0).filter(oe=>oe>=0),N=oe=>oe.length>0?oe[Math.floor(oe.length/2)]:0,x=oe=>oe.length>0?oe.reduce((ae,D)=>ae+D,0)/oe.length:0,y=N(v),b=N(S),j=new Date().getFullYear(),T=n?.priceRange?.low||v[0]||0,O=n?.priceRange?.high||v[v.length-1]||0,E=n?.priceRange?.predominant||y,R=n?.ageRange?.high?j-n.ageRange.high:0,G=n?.ageRange?.low?j-n.ageRange.low:0,U=n?.ageRange?.predominant?j-n.ageRange.predominant:0,C=r.map(oe=>{const ae=oe.price||oe.salePrice||0,D=oe.sqft||oe.gla||0;return D>0&&ae>0?ae/D:0}).filter(oe=>oe>0),F=r.filter(oe=>oe.listPrice>0&&(oe.price||oe.salePrice)>0).map(oe=>(oe.price||oe.salePrice)/oe.listPrice),A=oe=>{if(oe?.distressedYN===!0||oe?.DistressedYN===!0)return!0;const ae=oe?.rawData??oe?.mlsData??oe,D=String(ae?.SpecialListingConditions??ae?.specialListingConditions??ae?.distressType??ae?.DistressType??ae?.saleType??ae?.SaleType??"").toLowerCase();return D.includes("reo")||D.includes("foreclos")||D.includes("short sale")||D.includes("bank owned")||D.includes("bank-owned")},M=r.filter(oe=>A(oe)).length,B=r.length>0?Math.round(M/r.length*1e3)/10:0;return{salesCount:r.length||t?.propertyCount||0,medianSoldPrice:y,avgSoldPrice:x(v),medianDOM:b,avgDOM:x(S),forSaleCount:l,pendingCount:c,absorptionRate:f,monthsOfSupply:h,soldToListRatio:F.length>0?x(F):0,pricePerSqFt:N(C),priceLow:T,priceHigh:O,ageLow:R,ageHigh:G,agePredominant:U,pricePredominant:E,percentForeclosure:B,landUse:n?.landUse||void 0}}function Ch(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){const a=Number(t);return Number.isFinite(a)?a:null}return null}function cX(t,a){const s=Ch(t.latitude),r=Ch(t.longitude);if(s!==null&&r!==null)return{coords:{lat:s,lng:r},source:"order",shouldPersist:!1};const i=a("subjectCoordinates")?.subjectCoordinates;if(i){const d=Ch(i.lat),p=Ch(i.lng);if(d!==null&&p!==null)return{coords:{lat:d,lng:p},source:"progress",shouldPersist:!0}}const l=t.propertyData?.propMixData?.propertyDetails?.coordinates;if(l){const d=Ch(l.lat),p=Ch(l.lng);if(d!==null&&p!==null)return{coords:{lat:d,lng:p},source:"propMix",shouldPersist:!0}}const c=t.propertyData?.addressInfo;if(c){const d=Ch(c.lat),p=Ch(c.lng);if(d!==null&&p!==null)return{coords:{lat:d,lng:p},source:"addressInfo",shouldPersist:!0}}return null}async function Qj(t,a,s,r={}){const{retryDelayMs:n=2e3,fetchImpl:i=fetch}=r,l=async()=>{try{const d=await i(`/api/v2/orders/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({latitude:String(a.lat),longitude:String(a.lng)})});return{ok:d.ok,status:d.status}}catch{return{ok:!1,status:"network"}}};let c=await l();return c.ok||(console.warn(`[Wizard] Coordinate persist (${s}) failed (status: ${c.status}) — retrying once`),await new Promise(d=>setTimeout(d,n)),c=await l()),c.ok?(console.log(`[Wizard] Persisted ${s} coordinates to order`),!0):(console.error(`[Wizard] Failed to persist ${s} coordinates (status: ${c.status}) — pin stays visible this session, but the next load will re-derive coordinates`),!1)}function dX(t,a,s){const r=t[s];if(!r)return null;const n=a.indexOf(r);return n<0||n===s?null:n}const uX=o.lazy(()=>ri(()=>import("./StepLeaseSummary-B7v0zP5O.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12])).then(t=>({default:t.StepLeaseSummary}))),pX=o.lazy(()=>ri(()=>import("./StepAgencyEligibility-Bly9mtpY.js"),__vite__mapDeps([13,1,2,3,4,5,8,9,10,11])).then(t=>({default:t.StepAgencyEligibility}))),mX=o.lazy(()=>ri(()=>import("./StepCalculator-hHoP8msT.js"),__vite__mapDeps([14,1,2,3,4,5,15,16,7,17,8,9,10,11,12])).then(t=>({default:t.StepCalculator}))),hX=o.lazy(()=>ri(()=>import("./StepRightsAdjustment-CGwrn6hP.js"),__vite__mapDeps([18,1,2,3,4,5,19,16,17,8,9,10,11,12,7])).then(t=>({default:t.StepRightsAdjustment}))),fX=o.lazy(()=>ri(()=>import("./StepAddendumPreview-CKjd1bBk.js"),__vite__mapDeps([20,1,2,3,4,5,21,16,15,22,17,8,9,10,11,12,7])).then(t=>({default:t.StepAddendumPreview}))),gX=o.lazy(()=>ri(()=>import("./StrReportDataModal-C4svxdQm.js"),__vite__mapDeps([23,1,2,3,4,5,24,25,9,26,21,27,28,6,29,30,31,32,22,33,34,35,36,37,15,38,39,40,41,42,43,16,44,45,46,47,48,49,50,10,51,52,53,54,55,56,19,7,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,17,80,81,82])).then(t=>({default:t.StrReportDataModal}))),LO=o.lazy(()=>ri(()=>import("./StepStrWelcome-WYalB1vW.js"),__vite__mapDeps([83,1,2,3,4,5,6,25,84,82,79,56,19,29,26,7,22,53,55,54,57,50,38,49,85,40,86])).then(t=>({default:t.StepStrWelcome}))),xX=o.lazy(()=>ri(()=>import("./StepStrLegality-D49rn5pp.js"),__vite__mapDeps([87,1,2,3,4,5,82,79,56,19,29,25,26,7,22,53,55,54,57,86])).then(t=>({default:t.StepStrLegality}))),bX=o.lazy(()=>ri(()=>import("./StepStrMarket-D_OKIm8o.js"),__vite__mapDeps([88,1,2,3,89,4,5,82,79,56,19,29,25,26,7,22,53,55,54,57])).then(t=>({default:t.StepStrMarket}))),yX=o.lazy(()=>ri(()=>import("./StepStrMarketData-IQtWjKMZ.js"),__vite__mapDeps([90,1,2,3,4,5,30,54,82,79,56,19,29,25,26,7,22,53,55,57,52,35,36,34,91,47,21,9,50,38])).then(t=>({default:t.StepStrMarketData}))),SX=o.lazy(()=>ri(()=>import("./StepStrIncome-oNWC9Quo.js"),__vite__mapDeps([92,1,2,3,4,5,73,89,82,79,56,19,29,25,26,7,22,53,55,54,57,93])).then(t=>({default:t.StepStrIncome}))),vX=o.lazy(()=>ri(()=>import("./StepStrCertifyExport-C8MB-hxo.js"),__vite__mapDeps([94,1,2,3,4,5,25,82,79,56,19,29,26,7,22,53,55,54,57,86,93,95,85,40])).then(t=>({default:t.StepStrCertifyExport}))),NX=o.lazy(()=>ri(()=>import("./EvalWizardRevamped-DeNMlGyn.js"),__vite__mapDeps([96,1,2,3,4,5,97,6,30,19,95,61,22,42,43,16,44,45,46,47,48,49,50,38,39,10,15,51,31,29,25,28,32,24,9,26,21,27,33,34,35,36,37,52,53,54,55,56,7,57,58,59,60,62,63,64,65,66,67,68,69,70,71,72,41,73,74,75,76,77,78,79,17,80,81,82,40])).then(t=>({default:t.EvalWizardRevamped}))),AX=o.lazy(()=>ri(()=>import("./EvalReportPanel-BNlZJCi1.js"),__vite__mapDeps([98,1,2,3,26,4,5,97,6,30,19,95,61,24,25,9,21,27,28,29,31,32,22,33,34,35,36,37,15,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,7,57,58,59,60,62,63,64,65,66,67,68,69,70,71,72,41,73,74,75,76,77,78,79,17,80,81,82,40])).then(t=>({default:t.EvalReportPanel}))),jX=o.lazy(()=>ri(()=>import("./StepOrder36-DAt5s_0Q.js").then(t=>t.b),__vite__mapDeps([62,1,2,3,28,4,5,25,6,29,30,31,32,24,9,26,21,27,22,33,34,35,36,37,15,63,64,65,66,67,68,69,61,70]))),TX=o.lazy(()=>ri(()=>import("./StepAtAGlance36-Bj97DrDl.js"),__vite__mapDeps([99,1,2,3,4,5,24,25,9,26,21,27,28,6,29,30,31,32,22,33,34,35,36,37,15,100,
53101,102,103,76,104,105,106,66,67,107,61,65,62,63,64,68,69,70,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,19,7,57,58,59,60,71,72,41,73,74,75,77,78,79,17,80,81,82,40]))),IX=o.lazy(()=>ri(()=>import("./StepAssignment36-CoB2Tf-q.js"),__vite__mapDeps([108,1,2,3,4,5,24,25,9,26,21,27,28,6,29,30,31,32,22,33,34,35,36,37,15,64,65,66,67,68,69,62,63,61,70,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,19,7,57,58,59,60,71,72,41,73,74,75,76,77,78,79,17,80,81,82,40]))),CX=o.lazy(()=>ri(()=>import("./StepSite36-BQtwh67M.js"),__vite__mapDeps([109,1,2,3,15,4,5,24,25,9,26,21,27,28,6,29,30,31,32,22,33,34,35,36,37,110,66,70,74,67,62,63,64,65,68,69,61]))),RX=o.lazy(()=>ri(()=>import("./StepImprovements36-CoP0qibK.js"),__vite__mapDeps([111,1,2,3,15,4,5,25,28,6,29,30,31,32,24,9,26,21,27,22,33,34,35,36,37,112,113,107,66,102,67,62,63,64,65,68,69,61,70,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,19,7,57,58,59,60,71,72,41,73,74,75,76,77,78,79,17,80,81,82,40]))),EX=o.lazy(()=>ri(()=>import("./StepSubjectProperty36-DWD5YQHK.js"),__vite__mapDeps([114,1,2,3,15,4,5,24,25,9,26,21,27,28,6,29,30,31,32,22,33,34,35,36,37,103,76,104,101,115,66,116,117,118,105,106,62,63,64,65,67,68,69,61,70,109,110,74,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,19,7,57,58,59,60,71,72,41,73,75,77,78,79,17,80,81,82,40]))),wX=o.lazy(()=>ri(()=>import("./StepSalesContract36-C3HLUB_T.js"),__vite__mapDeps([119,1,2,3,4,5,24,25,9,26,21,27,28,6,29,30,31,32,22,33,34,35,36,37,15,120,67,62,63,64,65,66,68,69,61,70,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,19,7,57,58,59,60,71,72,41,73,74,75,76,77,78,79,17,80,81,82,40]))),PX=o.lazy(()=>ri(()=>import("./StepProjectInformation36-DZ0kG0J9.js"),__vite__mapDeps([121,1,2,3,15,4,5,24,25,9,26,21,27,28,6,29,30,31,32,22,33,34,35,36,37,122,70,113,76,66,123,67,62,63,64,65,68,69,61,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,19,7,57,58,59,60,71,72,41,73,74,75,77,78,79,17,80,81,82,40]))),OX=k2(()=>ri(()=>import("./StepMarket36-Bp8J4Z4G.js"),__vite__mapDeps([124,1,2,3,4,5,24,25,9,26,21,27,28,6,29,30,31,32,22,33,34,35,36,37,15,125,66,123,62,63,64,65,67,68,69,61,70,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,19,7,57,58,59,60,71,72,41,73,74,75,76,77,78,79,17,80,81,82,40]))),LX=o.lazy(()=>ri(()=>import("./StepCostApproach36-Dw4N7OjR.js"),__vite__mapDeps([126,1,2,3,4,5,24,25,9,26,21,27,28,6,29,30,31,32,22,33,34,35,36,37,15,127,107,61,101,113,66,77,67,70,62,63,64,65,68,69,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,19,7,57,58,59,60,71,72,41,73,74,75,76,78,79,17,80,81,82,40]))),DX=o.lazy(()=>ri(()=>import("./StepListingSaleHistory36-CybzeJ_m.js"),__vite__mapDeps([128,1,2,3,15,4,5,28,25,6,29,30,31,32,24,9,26,21,27,22,33,34,35,36,37,129,66,67,62,63,64,65,68,69,61,70,42,43,16,44,45,46,47,48,49,50,38,39,10,51,52,53,54,55,56,19,7,57,58,59,60,71,72,41,73,74,75,76,77,78,79,17,80,81,82,40]))),DO=o$(),kX={Address:Wl,Order:sT,Assignment:sT,"Subject Property":Fo,Site:N2,Improvements:Hh,"Sales Contract":gn,"Project Information":JR,Market:gv,"Subject & Site":Fo,"STR Subject":hv,"Subject Verify":fN,"Property Lab":v2,"Sales Grid":tT,"Lease Summary":S2,"Agency Check":JR,"Rights Calculator":Bx,"Rights Adjust":AI,Addendum:y2,"STR Analysis":Ql,Evaluation:b2,Review:x2},MX=t=>kX[t]??fv;function FX({orderId:t,hydrationPending:a,recentlySaved:s,railCollapsed:r}){const{pendingCount:n,lastSaveFailed:i,lastFailureStatus:l}=cL(t),c=pk({hydrationPending:a,pendingSaveCount:n,lastSaveFailed:t&&!Xf(t)?!1:i,recentlySaved:s});if(r){const u=c==="idle"?"All changes saved":c==="saved"?"Saved":c==="loading"?"Loading…":c==="saving"?"Saving…":"Save failed";return e.jsx("div",{className:"border-t border-white/10 flex justify-center py-1.5",children:e.jsx("span",{title:u,className:"w-8 h-8 flex items-center justify-center",children:c==="error"?e.jsx(Ns,{className:"w-3 h-3 text-red-400"}):c==="saved"||c==="idle"?e.jsx(Bs,{className:"w-3 h-3 text-white/40"}):e.jsx(za,{className:"w-3 h-3 text-white/40 animate-spin"})})})}if(c==="idle")return e.jsx("div",{className:"border-t border-white/10 px-3 py-1.5",children:e.jsx("span",{className:"text-[11px] text-white/30",children:"All changes saved"})});const d=c==="error"?mk(l):KI[c],p=c==="error"?"text-red-400":c==="saved"?"text-emerald-400":"text-white/50";return e.jsx("div",{className:"border-t border-white/10 px-3 py-1.5",children:e.jsxs("span",{className:`flex items-center gap-1 text-[11px] ${p}`,children:[c==="saved"?e.jsx(Bs,{className:"w-3 h-3"}):c==="error"?e.jsx(Ns,{className:"w-3 h-3"}):e.jsx(za,{className:"w-3 h-3 animate-spin"}),d]})})}const _X=35e3;
53function UX(){const[t,a]=o.useState(!1);return o.useEffect(()=>{const s=setTimeout(()=>a(!0),_X);return()=>clearTimeout(s)},[]),e.jsxs("div",{className:"flex flex-col items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(za,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{"data-testid":"text-hydration-overlay-message",children:t?"Still loading — your connection may be slow. Hang tight or reload.":"Loading your saved work…"})]}),t&&e.jsxs(De,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),"data-testid":"button-hydration-overlay-reload",children:[e.jsx(bg,{className:"h-3.5 w-3.5 mr-1.5"}),"Reload"]})]})}const Zj=4,d0=()=>{const t=new Date().toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"numeric"});return{...fz,effectiveDate:{value:t,source:"Derived",isEdited:!1,alternatives:{}}}},VX={leaseholdAssignmentId:null,currentStep:0,leaseTerms:null,discountRateSetup:null,calculationType:"PVGroundRent",incomeCapCalculation:null,pvCalculation:null,compAdjustments:[],reportFragments:{lease_summary:"",methodology:"",rights_adjustment:"",reconciliation:""},finalLeaseholdValue:null,uploadedPdfInfo:null},kO=t=>typeof t=="number"?`$${t.toLocaleString()}`:typeof t=="string"?t.startsWith("$")?t:`$${t}`:"",tp=(t,a,s)=>{const r=s||(p=>p!=null&&p!==""?String(p):""),n=r(t),i=r(a),l={};return n&&(l.mls=n),i&&(l.public_record=i),{value:n||i||"",source:n?"MLS":i?"PublicRecord":"Derived",isEdited:!1,alternatives:l}},$X=t=>{const a={...t},s=new Set(["mls","pr","publicrecord","propmix","echo"]),r=new Set(["mls","pr","publicrecord","propmix","echo"]);for(const[n,i]of Object.entries(t)){if(!i||typeof i!="object"||!("value"in i)||!("source"in i))continue;const l=i,c=String(l.source??"").replace(/[\s_-]/g,"").toLowerCase(),d=l.alternatives,p=Object.keys(d??{}).some(m=>r.has(m.replace(/[\s_-]/g,"").toLowerCase()));!(s.has(c)||c==="derived"&&p)||l.isEdited||l.source==="User"||l.isConfirmed||(a[n]={...l,value:"",source:"Derived",isEdited:!1,isConfirmed:!1,alternatives:{}})}return a},mv=(t,a,s={})=>{if(s.replacePriorUnapprovedProviderFacts)return mv(t,$X(a));const r=t.propertyDetails||{},n=t.listingDetails||{};console.log("[PropMix HOA Debug]",{associationFee:n.associationFee,associationFeeFrequency:n.associationFeeFrequency,AssociationFee:n.AssociationFee,AssociationFeeFrequency:n.AssociationFeeFrequency,hoaFee:n.hoaFee,hoaFees:n.hoaFees,allMlsKeys:Object.keys(n).filter(x=>x.toLowerCase().includes("assoc")||x.toLowerCase().includes("hoa"))});const i=n.associationFee??n.AssociationFee??n.hoaFee??null,l=n.associationFeeFrequency??n.AssociationFeeFrequency??null,d=(x=>{if(x==null||x===""||x===0)return"";const y=typeof x=="number"?x:parseFloat(String(x).replace(/[$,\s]/g,""));return isNaN(y)||y===0?"":`$${y.toLocaleString()}`})(i),p=d?{value:d,source:"MLS",isEdited:!1,alternatives:{mls:d}}:a.hoaFees,u=l?{value:String(l),source:"MLS",isEdited:!1,alternatives:{mls:String(l)}}:a.hoaFeeFrequency,m=a.pud?.value,h=m===!0||m==="Yes"||m==="yes"?"Yes":"",f={...a.pud,value:h},v=(x,y,b)=>{const j=tp(x,y,b);return j.value?j:void 0},S=(x,y)=>{if(x==null||x===""||x===0)return"";const b=typeof x=="number"?x:parseFloat(String(x).replace(/,/g,""));return isNaN(b)?"":b>43560?`${(b>43560?b/43560:b).toFixed(2)} ac`:`${b.toLocaleString()} sf`},N={...a,neighborhoodName:tp(n.neighborhood,r.neighborhood),pinNumber:tp(n.apn,r.apn),legalDescription:tp(n.legalDescription,r.legalDescription),taxYear:tp(n.taxYear,r.taxYear,x=>x!=null?String(x):""),taxes:tp(n.taxes,r.taxes,kO),assessedValue:v(n.taxAssessedValue,r.taxAssessedValue,kO)??a.assessedValue,yearBuilt:tp(n.yearBuilt,r.yearBuilt,x=>x!=null?String(x):""),zoningClassification:tp(n.zoning,r.zoningCode),zoningDescription:tp(null,r.zoningDescription),pud:f,hoaFees:p,hoaFeeFrequency:u,zoningCompliance:a.zoningCompliance,highestBestUse:a.highe
53stBestUse,county:v(n.county,r.county)??a.county,censusTract:v(n.censusTract??n.CensusTract,r.censusTract)??a.censusTract,mapReference:(()=>{const x=r.subdivision||r.LegalSubdivisionName||n.subdivision,y=r.township||r.Township,b=[x,y].filter(Boolean);if(b.length>0){const j=b.join(", ");return{value:j,source:"PR",isEdited:!1,alternatives:{pr:j}}}if(r.coordinates?.lat&&r.coordinates?.lng){const j=`${r.coordinates.lat.toFixed(4)}, ${r.coordinates.lng.toFixed(4)}`;return{value:j,source:"PR",isEdited:!1,alternatives:{pr:j}}}return a.mapReference})(),specialAssessments:v(n.specialAssessments,null)??a.specialAssessments,lotSize:v(n.lotSizeSquareFeet??n.LotSizeSquareFeet??n.lotSize,r.lotSizeSquareFeet??r.LotSizeSquareFeet??r.lotSize,x=>S(x))??a.lotSize,lotDimensions:(()=>{const x=v(n.lotDimensions??n.LotSizeDimensions,r.lotDimensions??r.LotSizeDimensions);if(x)return x;const y=a.lotDimensions?.value,b=String(y??"").trim().toLowerCase();if(y&&b.length>0&&!["","—","-","n/a","na","none","unknown"].includes(b))return a.lotDimensions;const j=n.lotSizeSquareFeet??n.LotSizeSquareFeet??n.lotSize??r.lotSizeSquareFeet??r.LotSizeSquareFeet??r.lotSize;if(j){const T=parseFloat(String(j).replace(/[$,\s]/g,""));if(!isNaN(T)&&T>0){const O=Math.round(Math.sqrt(T/1.33)),E=Math.round(Math.sqrt(T*1.33));return{value:`${O} x ${E}`,source:"Derived",isEdited:!1,alternatives:{derived:`~${Math.round(T).toLocaleString()} sf`}}}}})(),lotShape:(()=>{const x=n.lotShape??n.LotShape;if(x)return{value:gD("derivedLotShape",x)??String(x),source:"MLS",isEdited:!1,alternatives:{mls:String(x)}};const y=n.lotDimensions??n.LotSizeDimensions??r.lotDimensions??r.LotSizeDimensions;if(y){const j=String(y).toUpperCase().split(/[X×x\s]+/).filter(T=>/^\d+/.test(T));if(j.length===2)return{value:"Rectangular",source:"Derived",isEdited:!1,alternatives:{}};if(j.length>=3)return{value:"Irregular",source:"Derived",isEdited:!1,alternatives:{}}}return a.lotShape??{value:"Rectangular",source:"Derived",isEdited:!1,alternatives:{}}})(),view:(()=>{const x=n.view??n.View;return x?{value:String(x),source:"MLS",isEdited:!1,alternatives:{mls:String(x)}}:a.view})(),electricityType:(()=>{const x=n.electricity??n.Electric??n.Electricity;if(x){const y=String(x).toLowerCase();return{value:y.includes("public")||y.includes("municipal")||y.includes("commercial")?"Public":"Other",source:"MLS",isEdited:!1,alternatives:{mls:String(x)}}}return a.electricityType})(),gasType:(()=>{const x=n.gas??n.Gas??n.NaturalGas,y=n.heating??n.Heating;if(x){const b=String(x).toLowerCase(),j=b.includes("public")||b.includes("natural")||b.includes("municipal");return b.includes("none")||b.includes("no gas")||b==="electric"?a.gasType??{value:"Other",source:"MLS",isEdited:!1,alternatives:{mls:String(x)}}:{value:j?"Public":"Other",source:"MLS",isEdited:!1,alternatives:{mls:String(x)}}}if(y){const b=String(y).toLowerCase();if(b.includes("gas")||b.includes("natural gas"))return{value:"Public",source:"MLS",isEdited:!1,alternatives:{mls:`Gas (from heating: ${y})`}}}return a.gasType})(),waterType:(()=>{const x=n.water??n.Water??n.WaterSource;if(x){const y=String(x).toLowerCase();return{value:y.includes("public")||y.includes("municipal")||y.includes("city")||y.includes("community")?"Public":"Other",source:"MLS",isEdited:!1,alternatives:{mls:String(x)}}}return a.waterType})(),sanitarySewerType:(()=>{const x=n.sewer??n.Sewer??n.SewerDescription;if(x){const y=String(x).toLowerCase(),b=y.includes("public")||y.includes("municipal")||y.includes("city")||y.includes("community")||y.includes("sewer");return{value:y.includes("septic")||y.includes("private")||y.includes("cesspool")?"Other":b?"Public":"Other",source:"MLS",isEdited:!1,alternatives:{mls:String(x)}}}return a.sanitarySewerType})(),streetType:(()=>{const x=n.streetType??n.StreetType??n.RoadSurface??n.roadType;if(x){const y=String(x).toLowerCase();return{value:y.includes("private")||y.includes("easement")||y.includes("unpaved")?"Private":"Public",source:"MLS",isEdited:!1,alternatives:{mls:String(x)}}}return a.streetType})(),stories:v(n.stories??n.Stories??n.storiesTotal,r.stories??r.Stories,x=>x!=null?String(x):"")??a.stories,designStyle:v(n.architecturalStyle??n.ArchitecturalStyle??n.style,r.architecturalStyle??r.style)??a.designStyle,totalRooms:v(n.roomsTotal??n.RoomsTotal??n.totalRooms,r.roomsTotal??r.RoomsTotal??r.totalRooms,x=>x!=null?String(x):"")??a.totalRooms,bedrooms:v(n.bedroomsTotal??n.BedroomsTotal??n.bedrooms,r.bedroomsTotal??r.BedroomsTotal??r.bedrooms,x=>x!=null?String(x):"")??a.bedrooms,fullBaths:v(n.bathroomsFull??n.BathroomsFull??n.fullBaths,r.bathroomsFull??r.BathroomsFull??r.fullBaths,x=>x!=null?String(x):"")??a.fullBaths,halfBaths:v(n.bathroomsHalf??n.BathroomsHalf??n.halfBaths,r.bathroomsHalf??r.BathroomsHalf??r.halfBaths,x=>x!=null?String(x):"")??a.halfBaths,bathrooms:(()=>{const x=n.bathrooms??n.BathroomsTotalInteger,y=r.bathrooms;if(x!=null||y!=null)return tp(x,y,T=>T!=null?String(T):"");const b=parseFloat(String(n.bathroomsFull??n.BathroomsFull??r.bathroomsFull??r.BathroomsFull??"")),j=parseFloat(String(n.bathroomsHalf??n.BathroomsHalf??r.bathroomsHalf??r.BathroomsHalf??""));if(!isNaN(b)){const T=b+(isNaN(j)?0:j*.5);return{value:String(T),source:"MLS",isEdited:!1,alternatives:{mls:String(T)}}}return a.bathrooms})(),gla:v(n.squareFeet??n.livingArea??n.LivingArea??n.gla??n.sqft,r.squareFeet??r.livingArea??r.LivingArea??r.gla??r.sqft,x=>x!=null?String(x):"")??a.gla,basementArea:v(n.basementArea??n.BasementArea??n.basementSqFt,r.basementArea??r.BasementArea??r.basementSqFt,x=>x!=null?String(x):"")??a.basementArea,basementFinish:cx("basement",n.basementFinishedArea??n.basementDescription,r.basementFinishedArea??r.basementDescription)??a.basementFinish,heatingType:v(n.heating??n.Heating??n.heatingType,r.heating??r.Heating??r.heatingType)??a.heatingType,heatingFuel:v(n.heatingFuel??n.HeatingFuel,r.heatingFuel??r.HeatingFuel)??a.heatingFuel,coolingType:v(n.cooling??n.Cooling??n.coolingType,r.cooling??r.Cooling??r.coolingType)??a.coolingType,garageType:cx("garageType",n.garageType??n.GarageType??n.parkingType,r.garageType??r.GarageType??r.parkingType)??a.garageType,roofSurface:cx("roofType",n.roofType??n.RoofType??n.roof,r.roofType??r.RoofType)??a.roofSurface,exteriorWalls:cx("exteriorWall",n.construction??n.constructionMaterials??n.exteriorMaterial,r.construction??r.exteriorMaterial)??a.exteriorWalls,foundationWalls:cx("foundation",n.foundation??n.Foundation,r.foundation??r.Foundation)??a.foundationWalls,drivewaySurface:cx("driveway",n.driveway??n.Driveway??n.drivewaySurface,r.driveway??r.Driveway)??a.drivewaySurface,garageCars:v(n.garageSpaces??n.GarageSpaces??n.parkingSpaces,r.garageSpaces??r.GarageSpaces??r.parkingSpaces,x=>x!=null?String(x):"")??a.garageCars,propertyType:(()=>{const x=r.propertyType??n.propertyType??n.propertySubType;if(x){const y=String(x).toLowerCase(),b=y.includes("coop")||y.includes("cooperative")||y.includes("condo")?"Condo/Co-op":y.includes("manufactured")||y.includes("mobile")?"Manufactured":y.includes("duplex")||y.includes("triplex")||y.includes("quad")||y.includes("2-4")||y.includes("multi")||y.includes("apartment")?"2-4 Unit":y.includes("pud")?"PUD":y.includes("single")||y.includes("detached")||y.includes("sfr")||y.includes("townhouse")||y.includes("row")?"Single Family":"";if(b){const j=r.propertyType?"PR":"MLS";return{value:b,source:j,isEdited:!1,alternatives:{[j.toLowerCase()]:String(x)}}}}return a.propertyType})(),numUnits:(()=>{const x=n.numberOfUnitsTotal??n.NumberOfUnitsTotal??n.unitsTotal??n.numberOfUnits,y=r.numberOfUnitsTotal??r.NumberOfUnitsTotal??r.numberOfUnits??r.NumberOfUnits??r.numUnits??r.unitCount,b=x??y;if(b!=null&&b!=="")return{value:String(b),source:x!=null?"MLS":"PR",isEdited:!1,alternatives:{}};const j=r.propertyType??n.propertyType??n.propertySubType??"",T=String(j).toLowerCase();return T&&!T.includes("duplex")&&!T.includes("triplex")&&!T.includes("quad")&&!T.includes("2-4")&&!T.includes("multi")&&!T.includes("apartment")&&!T.includes("multi-family")?{value:"1",source:"Derived",isEdited:!1,alternatives:{}}:a.numUnits})(),aduIndicator:(()=>{const x=n.accessoryDwellingUnitYN??n.AccessoryDwellingUnit??r.aduIndicator;return x===!0||String(x).toLowerCase()==="yes"||String(x).toLowerCase()==="true"?{value:"Yes",source:"MLS",isEdited:!1,alternatives:{mls:String(x)}}:x===!1||String(x).toLowerCase()==="no"||String(x).toLowerCase()==="false"?{value:"No",source:"MLS",isEdited:!1,alternatives:{mls:String(x)}}:a.aduIndicator})(),estateType:(()=>{const x=a.estateType;return x?.isEdited||x?.source==="User"?x:String(r.ownership??n.ownership??"").toLowerCase().includes("leasehold")?{value:"Leasehold",source:r.ownership?"PR":"MLS",isEdited:!1,alternatives:{}}:x?.value&&x.source!=="Default"&&x.source!=="Derived"?x:a.estateType})(),attachmentType:(()=>{const x=n.propertySubType??n.PropertySubType??r.propertyType??n.style??n.architecturalStyle;if(x){const y=String(x).toLowerCase(),b=y.includes("semi-detached")||y.includes("semi detached")||y.includes("duplex side")?"Semi-Detached":y.includes("townhouse")||y.includes("town house")||y.includes("row")?"Row/Townhouse":y.includes("end unit")||y.includes("end-unit")?"End Unit":y.includes("detached")||y.includes("single family")||y.includes("sfr")?"Detached":y.includes("attached")?"Attached":"";if(b){const j=n.propertySubType?"MLS":"PR";return{value:b,source:j,isEdited:!1,alternatives:{[j.toLowerCase()]:String(x)}}}}return a.attachmentType})(),numParcels:(()=>{const x=r.apn??n.apn;return x&&!String(x).includes(",")&&!String(x).includes(";")&&!String(x).includes("|")?{value:"1",source:"Derived",isEdited:!1,alternatives:{pr:"1 APN: "+String(x)}}:a.numParcels})(),allRightsAppraised:a.allRightsAppraised,mlsData:n??a.mlsData};for(const[x,y]of Object.entries(a))y&&typeof y=="object"&&(y.isEdited||y.source==="User"||y.isConfirmed===!0)&&(N[x]=y);return N},BX=(t,a,s)=>{const r=t.propertyDetails||{},n=t.listingDetails||{};return{...s,subjectAddress:s.subjectAddress?.isEdited||s.subjectAddress?.source==="User"?s.subjectAddress:{value:String(a.fullAddress),source:"Derived",isEdited:!1,alternatives:{derived:String(a.fullAddress)}},owner:s.owner?.isEdited||s.owner?.source==="User"?s.owner:tp(n.owner,r.owner)}},MO=(t,a)=>{const s=t.listingDetails||{},r=t.propertyDetails||{},n=[],i={};if(a&&Array.isArray(a))for(const h of a)h.mlsNumber&&(i[String(h.mlsNumber)]=h);console.log("[PropMix History Debug]",{listingHistory:s.listingHistory,deedHistory:s.deedHistory,prDeedHistory:r.deedHistory,prLastSale:{price:r.lastSalePrice,date:r.lastSaleDate},mlsSold:{price:s.soldPrice,date:s.soldDate},mlsList:{price:s.listPrice,date:s.listDate,id:s.listingId}});const l=h=>{if(!h)return"";try{return new Date(h).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"numeric"})}catch{return String(h)}},c=h=>{if(h==null||h===""||h===0)return"";const f=typeof h=="number"?h:parseFloat(String(h).replace(/[,$]/g,""));
53return isNaN(f)?String(h):`$${f.toLocaleString()}`},d=(h,f)=>({mlsNumber:h,photos:s.photos||[],listPrice:s.listPrice?parseFloat(String(s.listPrice).replace(/[,$]/g,"")):void 0,soldPrice:s.soldPrice?parseFloat(String(s.soldPrice).replace(/[,$]/g,"")):void 0,listDate:s.listDate,soldDate:s.soldDate,status:s.status||s.standardStatus,daysOnMarket:s.daysOnMarket||s.dom,description:s.publicRemarks||s.remarks,bedrooms:s.bedrooms||r.bedrooms,bathrooms:s.bathrooms||r.bathrooms,squareFeet:s.squareFeet||s.livingArea||r.squareFeet||r.livingArea,yearBuilt:s.yearBuilt||r.yearBuilt,lotSize:s.lotSize||r.lotSize,style:s.style||s.propertySubType||r.style,garage:s.garage,garageSpaces:s.garageSpaces,basement:s.basement,heating:s.heating,cooling:s.cooling,construction:s.construction||s.constructionMaterials,roofType:s.roofType||s.roof,pool:s.pool,fireplace:s.fireplace||s.fireplaces,...f}),p=(h,f)=>{if(h)return i[String(h)]||d(h,f)};if(r.lastSalePrice&&r.lastSaleDate&&n.push({id:"pr-last-sale",date:l(r.lastSaleDate),price:c(r.lastSalePrice),type:"Sale",source:"Public Record"}),s.soldPrice&&s.soldDate){const h=l(s.soldDate),f=r.lastSaleDate?l(r.lastSaleDate):"",v=s.listingId;h!==f&&n.push({id:"mls-sale",date:h,price:c(s.soldPrice),type:"Sale",source:v?`MLS #${v}`:"MLS",mlsNumber:v,listingSheet:p(v)})}if(s.listPrice&&s.listDate){const h=s.listingId;n.push({id:"mls-listing",date:l(s.listDate),price:c(s.listPrice),type:"Listing",source:h?`MLS #${h}`:"MLS",mlsNumber:h,listingSheet:p(h)})}const u=s.listingHistory||[];Array.isArray(u)&&u.forEach((h,f)=>{const v=l(h.listDate||h.date||h.ListDate),S=c(h.listPrice||h.price||h.ListPrice),N=h.mlsNumber||h.MlsListingNumber||h.MLSNumber;if(v||S){const x={};h.listPrice&&(x.listPrice=parseFloat(String(h.listPrice).replace(/[,$]/g,""))),(h.soldPrice||h.SoldPrice)&&(x.soldPrice=parseFloat(String(h.soldPrice||h.SoldPrice).replace(/[,$]/g,""))),(h.listDate||h.ListDate)&&(x.listDate=h.listDate||h.ListDate),n.push({id:`listing-${f}`,date:v,price:S,type:"Listing",source:N?`MLS #${N}`:"MLS",mlsNumber:N,listingSheet:p(N,x)})}});const m=s.deedHistory||r.deedHistory||[];return Array.isArray(m)&&m.forEach((h,f)=>{const v=l(h.saleDate||h.recordingDate||h.date||h.SaleDate),S=c(h.salePrice||h.amount||h.price||h.SalePrice);(v||S)&&n.push({id:`deed-${f}`,date:v,price:S,type:"Sale",source:"Public Record"})}),n.sort((h,f)=>{const v=new Date(h.date).getTime()||0;return(new Date(f.date).getTime()||0)-v}),n};function zX(t,a,s=[]){const r=t?.listingDetails||{},n=t?.propertyDetails||{},i=a?.propertyType,c=(t&&["MLS","PR","PublicRecord"].includes(String(i?.source))?i?.value:void 0)||r.propertyType||r.propertySubType||n.propertyType||n.propertySubType,d=i&&(i.source==="User"||i.isEdited===!0||i.isConfirmed===!0)?i.value:void 0,p=String(d||c||"Unknown"),u=n.buildingAreaTotal??n.BuildingAreaTotal??n.areaSemanticProvenance?.buildingAreaTotal??void 0,m=r.buildingAreaTotal??r.BuildingAreaTotal??void 0,h=n.numberOfUnitsTotal??n.NumberOfUnitsTotal??n.numberOfUnits??void 0,f=r.numberOfUnitsTotal??r.NumberOfUnitsTotal??r.numberOfUnits??void 0,v=s.filter(j=>{const O=(j.candidate?.reasons??[]).some(E=>/conflict|returned-(?:address|unit)|unit[-_ ]scope/i.test(E));return j.candidate?.disposition!=="conflict"&&!j.candidate?.scopeConflict&&!j.conflictWarning&&!O}).filter(j=>j.candidate?.unitCount!=null||j.candidate?.propertySubType).map(j=>({value:j.candidate?.unitCount??(/four[\s-]?plex|quad[\s-]?plex/i.test(j.candidate?.propertySubType||"")?4:/triplex/i.test(j.candidate?.propertySubType||"")?3:/duplex/i.test(j.candidate?.propertySubType||"")?2:0),source:"mls",label:[j.displayLabel||(j.mlsNumber?`MLS #${j.mlsNumber}`:void 0),j.date,j.listingStatus].filter(Boolean).join(" · ")||void 0})).filter(j=>j.value>0),S=f??h,N=f!=null?"mls":h!=null?"public-record":void 0,x={buildingAreaTotal:m,BuildingAreaTotal:m,numberOfUnitsTotal:f,NumberOfUnitsTotal:f,propertyType:r.propertyType||r.propertySubType||void 0,unitBreakdown:r.unitBreakdown,unitMix:r.unitMix},y={buildingAreaTotal:u,BuildingAreaTotal:u,numberOfUnitsTotal:h,NumberOfUnitsTotal:h,propertyType:n.propertyType||n.propertySubType||void 0},b=DI({propertyType:p,unitCount:S,unitCountSource:N,unitCountAlternatives:v,buildingAreaSqft:m??u,buildingAreaSource:m!=null?"mls":u!=null?"public-record":void 0,mlsData:x,publicRecordData:y});return{propertyType:p,unitCount:S,unitCountSource:N,unitCountAlternatives:v,unitCountConflict:b.unitCountConflict??!1,buildingAreaSqft:m??u,buildingAreaSource:m!=null?"mls":u!=null?"public-record":void 0,unitBreakdown:r.unitBreakdown,unitMix:r.unitMix,publicRecordData:y,mlsData:x}}function qX(){return e.jsx("div",{className:"flex items-center justify-center py-24","data-testid":"step-chunk-loader",children:e.jsx(za,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}function YX({externalStep:t,onStateChange:a}){const{state:s,goToStep:r,isHydrated:n}=U$(),i=s.currentStep,l=o.useRef(null);o.useEffect(()=>{t!==null&&t!==i&&(n?(r(t),l.current=null):l.current=t)},[t,n]),o.useEffect(()=>{n&&l.current!==null&&(r(l.current),l.current=null)},[n]),o.useEffect(()=>{a?.(s)},[s,a]);const c=()=>{switch(i){case 0:return e.jsx(LO,{});case 1:return e.jsx(xX,{});case 2:return e.jsx(bX,{});case 3:return e.jsx(yX,{});case 4:return e.jsx(SX,{});case 5:return e.jsx(vX,{});default:return e.jsx(LO,{})}};return e.jsx("div",{className:"h-full overflow-auto bg-[#EDE8E4]",children:e.jsx("div",{className:"max-w-7xl mx-auto px-6 py-4",children:c()})})}
53function GX(){const[t,a]=o.useState(0),[s,r]=o.useState(void 0),[n,i]=o.useState(void 0),[l,c]=o.useState(void 0),[d,p]=o.useState(new Set),u=o.useRef(new Set),{toast:m}=hc(),{profile:h,initialized:f,isAuthenticated:v,isPlatformAdmin:S,isImpersonating:N}=ly(),x=iL(),[,y]=bI(),b=o.useMemo(()=>new URLSearchParams(x).get("orderId"),[x]),j=o.useRef(b);j.current=b;const T=o.useMemo(()=>{const X=new URLSearchParams(x).get("newOrder")==="true";return!b||X},[x,b]),O=o.useMemo(()=>b?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(b):!1,[b]),{data:E,isLoading:R}=Vr({queryKey:b?kx(b):["order","disabled"],queryFn:()=>JS(b,{slim:!0}),enabled:!!b&&O,staleTime:mL}),{data:G,isLoading:U}=Vr({queryKey:b?ZS(b):["/api/v2/orders","disabled"],queryFn:()=>kA(b),enabled:!!b&&O,staleTime:M2}),C=fq(G,E),F=gq(G),A=xq(C,R,U),M=Ow(F,U);o.useEffect(()=>{console.log("[Wizard] full-load phase:",M,{orderId:b})},[M,b]);const B=o.useCallback(P=>{if(!b||P.length===0)return;const X=xe=>!xe?.order||!Array.isArray(xe.progress)?xe:{...xe,progress:ij(xe.progress,P)};fi.setQueryData(kx(b),X),fi.setQueryData(ZS(b),X)},[b]),{omittedFetchState:oe,omittedFetchStateRef:ae,omittedFetchPending:D,omittedStepKeys:_,fetchedOmittedRowsRef:$,omittedFetchPendingKeys:z}=Vq({orderId:b,progressEntries:C?.progress,mergeRowsIntoCaches:B}),V=Tq(M),le=o.useRef(!1);o.useEffect(()=>{!le.current&&!V&&z.size===0&&(le.current=!0)},[V,z]);const W=o.useCallback((P,X)=>le.current?!1:V||Lw(P,X,z),[V,z]),me=Lw("property_lab",!1,z),Z=Eq(z),pe=o.useRef(null);o.useEffect(()=>{oe!=="failed"||!b||pe.current!==b&&(pe.current=b,m({title:"Couldn't load part of your saved work",description:"The connection stalled while restoring this order's saved snapshots. Your saved data is safe on the server — reload the page to try again.",variant:"destructive"}))},[oe,b,m]);const[se,fe]=o.useState(d0()),[ue,be]=o.useState([]),[H,ye]=o.useState(ux),[de,ge]=o.useState("Owner"),[Be,He]=o.useState([]),[Ie,ce]=o.useState([]),[Pe,We]=o.useState({}),[Re,ne]=o.useState(null),Me=o.useRef(null),lt=o.useRef(null),Tt=o.useRef(null),je=o.useRef(null),[Le,ut]=o.useState(!1),[st,Xt]=o.useState(!1),[ua,Oa]=o.useState("system"),[Xa,qa]=o.useState(!1),[os,ya]=o.useState(!1),[At,Fe]=o.useState(!1),[Oe,rt]=o.useState(!1),[$t,na]=o.useState({}),[zt,Ua]=o.useState(!1),[Ce,St]=o.useState(null),[vt,Ve]=o.useState(!1),[sa,tt]=o.useState(!1),it=o.useRef(null),[Je,ht]=o.useState(void 0),[Kt,Sa]=o.useState([]),[Qt,ea]=o.useState([]),[tr,ir]=o.useState({}),zs=o.useRef({}),[,pr]=o.useState({}),$e=o.useRef(null),[Ot,_e]=o.useState(Zz),ma=o.useMemo(()=>Iw(Ot),[Ot]),[pt,re]=o.useState(GV),[qe,Ze]=o.useState([]),[It,Ne]=o.useState([]),[Ue,ct]=o.useState([]),[xt,Na]=o.useState(!1),[qt,la]=o.useState(""),[fs,ps]=o.useState(!1),[Te,at]=o.useState({explicitNone:!1}),yt=o.useCallback(P=>{at(X=>JSON.stringify(X)===JSON.stringify(P)?X:P)},[]),nt=o.useCallback((P,X,xe="",Ye=!1)=>{ct(ke=>JSON.stringify(ke)===JSON.stringify(P)?ke:P),Na(ke=>ke===X?ke:X),la(ke=>ke===xe?ke:xe),ps(ke=>ke===Ye?ke:Ye)},[]),[Wt,ts]=o.useState([]),gs=o.useRef(null),Va=o.useRef(null),Mr=o.useCallback(P=>{Ne(X=>X===P?X:P)},[]),xs=o.useCallback(P=>{gs.current=P},[]),Sn=o.useCallback(P=>{Va.current=P},[]),ds=o.useCallback(P=>{ts(P)},[]),[Zt,Rs]=o.useState(""),[Os,qs]=o.useState(null),[Ks,Tn]=o.useState({}),[Bn,Ka]=o.useState({}),[Ee,dt]=o.useState(null),[ot,xa]=o.useState({priorities:[],weights:{},baselineSource:"mls"}),[rs,Gs]=o.useState(null),bs=HE.find(P=>P.id==="balanced"),ba=qj(bs),[ln,zn]=o.useState(ba),fd=o.useRef(ln);fd.current=ln;const go=o.useCallback(P=>{zn(P);const{priorities:X,weightOverrides:xe}=BS(P);xa(Ye=>({...Ye,weightOverrides:xe,priorities:X}))},[]),[Zd,Mu]=o.useState(null),[hp,qn]=o.useState(null),[gd,Bi]=o.useState(null);o.useEffect(()=>{!b||b===hp||(qn(b),DA(b).catch(()=>null).then(P=>{if(!P)return;const X=P?.boostWeights||P?.order?.boostWeights;if(X&&typeof X=="object"){const xe=X;if(Object.entries(xe).length>0){Bi({orderId:b,hasSavedWeights:!0});const ke=DJ(xe);zn(ke);const{priorities:jt,weightOverrides:Et}=BS(ke),ka={};for(const[Yt,ha]of Object.entries(xe)){if(!Qx.has(Yt))continue;const Rt=MM(ha);Rt&&(ka[Yt]=Rt.weight)}xa(Yt=>({...Yt,weights:ka,weightOverrides:Et,priorities:jt}))}else Bi({orderId:b,hasSavedWeights:!1}),zn([...ba]),xa(ke=>({...ke,priorities:[],weights:{},weightOverrides:void 0}))}else Bi({orderId:b,hasSavedWeights:!1}),zn([...ba]),xa(xe=>({...xe,priorities:[],weights:{},weightOverrides:void 0}))}).catch(()=>Bi({orderId:b,hasSavedWeights:!1})))},[b]);const xd=o.useRef(null);o.useEffect(()=>{h?.id&&b&&gd?.orderId===b&&!gd.hasSavedWeights&&ot.priorities.length===0&&fetch(`/api/profile/${h.id}/defaults`).then(P=>P.ok?P.json():null).then(P=>{if(P?.defaults?.defaultWeightPresetId){const xe=[...HE,...P.defaults.weightPresets||[]].find(Ye=>Ye.id===P.defaults.defaultWeightPresetId);if(xe){const Ye={...xe,boostCriteria:(xe.boostCriteria||[]).filter(Et=>Qx.has(Et)||["proximity","gla","els","bedsBaths"].includes(Et)),weightOverrides:xe.weightOverrides?Object.fromEntries(Object.entries(xe.weightOverrides).filter(([Et])=>Qx.has(Et)||["proximity","gla","els","bedsBaths"].includes(Et))):null};xd.current=Ye;
53const ke=qj(Ye),jt=BS(ke);xa(Et=>({...Et,priorities:jt.priorities,baselineWeights:Ye.baselineWeights,weightOverrides:jt.weightOverrides})),zn(ke)}}}).catch(()=>{})},[h?.id,b,gd,ot.priorities.length]);const[Jp,hf]=o.useState(!1),[_c,bd]=o.useState(!1),[In,Yn]=o.useState(null),[Qa,Xi]=o.useState([]),[Ri,yd]=o.useState(null),[Zo,Tg]=o.useState({}),[Xp,ni]=o.useState({analysis:null,uploadedFileName:null}),[ki,fp]=o.useState(!1),[Ol,$m]=o.useState(!1),Jd=o.useRef(!1),[Ig,Cg]=o.useState(null),Sd=o.useCallback(()=>Cg(null),[]),[ml,Rg]=o.useState([]),[hl,ff]=o.useState({}),[vd,gf]=o.useState({asIs:"",afterRepaired:"",commentary:""}),Gn=o.useRef(null),[zi,em]=o.useState(null),[Bm,xb]=o.useState(!1),[gc,zm]=o.useState(!1),[Nd,Fu]=o.useState("library"),[Uc,Xd]=o.useState([]),[eu,qm]=o.useState([]),[Eg,Ym]=o.useState(!1),[gy,Vc]=o.useState(null),[tm,tu]=o.useState(!1),[ii,Gm]=o.useState(null),[eo,Wr]=o.useState(!1),[$c,Bc]=o.useState(!1),[_u,xf]=o.useState(!1),[No,gp]=o.useState(!1),xp=o.useRef(!1),[wg,Pg]=o.useState(!1),[qi,Jo]=o.useState(()=>$q()),[Ll,oi]=o.useState(()=>typeof window<"u"&&window.matchMedia?.("(max-width: 1023px)").matches===!0);o.useEffect(()=>{if(typeof window>"u"||!window.matchMedia)return;const P=window.matchMedia("(max-width: 1023px)"),X=()=>oi(P.matches);return X(),P.addEventListener?.("change",X),()=>P.removeEventListener?.("change",X)},[]);const[zc,am]=o.useState(!1),xo=o.useRef(null),Yi=o.useCallback(()=>{xo.current&&(clearTimeout(xo.current),xo.current=null)},[]);o.useEffect(()=>()=>{xo.current&&clearTimeout(xo.current)},[]);const Og=o.useCallback(()=>{Yi(),Jo(P=>(P&&(xo.current=setTimeout(()=>am(!0),250)),P))},[Yi]),Xo=o.useCallback(()=>{Yi(),xo.current=setTimeout(()=>am(!1),300)},[Yi]),Lg=o.useCallback(()=>{Yi(),am(!1),Jo(P=>{const X=!P;return Bq(X),X})},[Yi]),[au,Tr]=o.useState("idle"),Fr=o.useRef(null),Zl=o.useRef(new Set),qc=o.useRef(!1),bf=o.useRef(null),sm=o.useRef(null),rm=o.useRef(t),nm=o.useRef(!1),[Dg,yf]=o.useState(!1),el=o.useRef(null),[Jn,Yc]=o.useState(void 0),[vn,su]=o.useState(void 0),[Ei,Gc]=o.useState(void 0),[$r,Mi]=o.useState(VX),[tl,to]=o.useState("Fannie"),[Ao,Gi]=o.useState({isAnalyzing:!1}),li=o.useRef(null),fl=o.useRef(!0),im=o.useRef(""),Ad=o.useRef("");o.useEffect(()=>(fl.current=!0,()=>{fl.current=!1,li.current&&(li.current.abort(),li.current=null)}),[]);const[gl,Nn]=o.useState(null),_o=o.useRef(new Set),[mr,Jl]=o.useState([]);o.useEffect(()=>{const P={},X=(_s,et)=>{et?.value!==null&&et?.value!==void 0&&et?.value!==""&&(P[_s]=typeof et.value=="boolean"?et.value:String(et.value))},xe=(_s,et)=>{et&&(P[_s]=et)};xe("subject.address",se.subjectAddress?.value),xe("subject.city",vn),xe("subject.state",Jn),xe("subject.zipCode",Ei),X("subject.county",H.county),X("subject.censusTract",H.censusTract),X("subject.mapReference",H.mapReference),X("subject.specialAssessments",H.specialAssessments),X("orderData.borrower.value",se.borrower),X("orderData.lender.value",se.lender),xe("orderData.lenderAddress.value",se.lenderAddress?.value),X("subject.owner",se.owner),X("subject.legalDescription",H.legalDescription),X("subject.pinNumber",H.pinNumber),X("subject.taxYear",H.taxYear),X("subject.taxes",H.taxes),X("subject.neighborhoodName",H.neighborhoodName),X("subject.hoaFees",H.hoaFees),xe("subject.hoaPerMonth",H.hoaFeeFrequency?.value==="Monthly"?"true":""),xe("subject.hoaPerYear",(()=>{const _s=H.hoaFeeFrequency?.value;return _s==="Annually"||_s==="Annual"||_s==="Yearly"?"true":""})());const Ye=H.pud?.value;P["subject.isPud"]=Ye==="Yes"||Ye==="1"||Ye===1||Ye===!0,P["subject.propertyRightsFeeSimple"]=!0,P["subject.propertyRightsLeasehold"]=null,P["subject.propertyRightsOther"]=null;const ke=se.assignmentType?.value,jt=ke==="Purchase Transaction"||ke==="Purchase",Et=ke==="Refinance Transaction"||ke==="Refinance";P["subject.assignmentPurchase"]=jt?!0:null,P["subject.assignmentRefinance"]=Et?!0:null,P["subject.assignmentOther"]=!jt&&!Et&&ke?!0:null,ke==="Other"&&xe("subject.assignmentOtherDescribe",se.assignmentTypeOtherDescription?.value);const ka=se.offeredForSale?.value;if(P["subject.offeredForSaleYes"]=ka===!0?!0:null,P["subject.offeredForSaleNo"]=ka===!1?!0:null,xe("subject.offeringDataSources",se.offeredForSaleDataSource?.value),!se.offeredForSaleDataSource?.value){const _s=[];(H.county?.source==="PR"||H.legalDescription?.source==="PR")&&_s.push("Public Records"),(H.c
53ounty?.source==="MLS"||H.neighborhoodName?.source==="MLS")&&_s.push("MLS"),H.taxes?.value&&_s.push("County Tax Records"),_s.length>0&&xe("subject.offeringDataSources",_s.join(", "))}const Yt=ke==="Purchase Transaction"||ke==="Purchase",ha=ke==="Refinance Transaction"||ke==="Refinance",Rt=!Yt&&!ha&&!!ke;if(P["contract.isPurchase"]=Yt?!0:null,P["contract.isRefinance"]=ha||Rt?!0:null,Yt){xe("contract.contractPrice",se.contractPrice?.value),xe("contract.contractDate",se.contractDate?.value);const _s=se.contractAnalyzed?.value;P["contract.didAnalyzeContract"]=_s===!0?!0:null,P["contract.didNotAnalyzeContract"]=_s===!1?!0:null,xe("contract.contractAnalysisExplanation",se.contractAnalysisExplanation?.value),P["contract.isSellerOwner"]=se.sellerOwnerOfRecord?.value===!0?!0:null,xe("contract.sellerOwnerDataSource",se.sellerOwnerDataSource?.value)}else(ha||Rt)&&(P["contract.contractPrice"]=null,P["contract.contractDate"]=null,P["contract.sellerName"]=null,P["contract.isSellerOwner"]=null,P["contract.sellerOwnerDataSource"]=null,P["contract.didAnalyzeContract"]=null,P["contract.didNotAnalyzeContract"]=!0,P["contract.contractAnalysisExplanation"]="Not applicable — refinance transaction");X("site.area",H.lotSize),X("site.dimensions",H.lotDimensions),X("site.shape",H.lotShape),X("site.view",H.view),X("site.zoningClassification",H.zoningClassification),X("site.zoningDescription",H.zoningDescription);const Bt=H.zoningCompliance?.value;Bt==="Legal"&&(P["site.zoningLegal"]=!0),Bt==="Legal Nonconforming"&&(P["site.zoningLegalNonConforming"]=!0),Bt==="Illegal"&&(P["site.zoningIllegal"]=!0);const Jt=H.highestBestUse?.value;Jt===!0&&(P["site.highestBestUseYes"]=!0),Jt===!1&&(P["site.highestBestUseNo"]=!0,X("site.highestBestUseNoDescribe",H.highestBestUseDescription)),X("site.femaFloodZone",H.femaFloodZone),X("site.femaMapNumber",H.femaMapNumber),X("site.femaMapDate",H.femaMapDate);const gt=H.femaFloodZone?.value||H.femaFloodZone;if(typeof gt=="string"&&gt){const _s=gt.startsWith("A")||gt.startsWith("V");P["site.femaFloodHazardYes"]=_s?!0:null,P["site.femaFloodHazardNo"]=_s?null:!0}const Ra=H.electricityType?.value;Ra&&(P["site.electricityPublic"]=Ra==="Public"?!0:null,P["site.electricityOther"]=Ra==="Other"?!0:null);const fa=H.gasType?.value;fa&&(P["site.gasPublic"]=fa==="Public"?!0:null,P["site.gasOther"]=fa==="Other"?
53!0:null);const Is=H.waterType?.value;Is&&(P["site.waterPublic"]=Is==="Public"?!0:null,P["site.waterOther"]=Is==="Other"?!0:null);const cs=H.sanitarySewerType?.value;cs&&(P["site.sanitarySewerPublic"]=cs==="Public"?!0:null,P["site.sanitarySewerOther"]=cs==="Other"?!0:null);const br=H.streetType?.value;br&&(P["site.streetPublic"]=br==="Public"?!0:null,P["site.streetPrivate"]=br==="Private"?!0:null),!tr["site.adverseConditionsYes"]&&!tr["site.adverseConditionsNo"]&&(P["site.adverseConditionsNo"]=!0),X("improvements.yearBuilt",H.yearBuilt),X("improvements.effectiveAge",H.effectiveAge),X("improvements.designStyle",H.designStyle),X("improvements.gla",H.gla),X("improvements.bedrooms",H.bedrooms),X("improvements.bathrooms",H.bathrooms),X("improvements.totalRooms",H.totalRooms),X("improvements.condition",H.condition),X("improvements.quality",H.quality),X("improvements.heatingType",H.heatingType),X("improvements.coolingType",H.coolingType),X("improvements.garageCarport",H.garageType),X("improvements.garageCars",H.garageCars),X("improvements.drivewaySurface",H.drivewaySurface),X("improvements.basementArea",H.basementArea),X("improvements.basementPercentFinished",H.basementFinish),X("improvements.foundation",H.foundationWalls),X("improvements.exteriorWalls",H.exteriorWalls),X("improvements.roofSurface",H.roofSurface),X("improvements.guttersDownspouts",H.guttersDownspouts),X("improvements.windowType",H.windowType),X("improvements.stormSash",H.stormSash),X("improvements.screens",H.screens),X("improvements.interiorFloors",H.interiorFloors),X("improvements.interiorWalls",H.interiorWalls),X("improvements.trimFinish",H.trimFinish),X("improvements.bathFloor",H.bathFloor),X("improvements.bathWainscot",H.bathWainscot),xe("appraiser.name",se.appraiser?.value),xe("appraiser.company",se.appraiserCompany?.value),xe("appraiser.licenseNumber",se.appraiserLicense?.value),xe("appraiser.licenseExpiration",se.appraiserLicenseExpiration?.value),xe("appraiser.licenseState",se.appraiserLicenseState?.value);const zr=JSON.stringify(P);zr!==im.current&&(im.current=zr,ir(_s=>({..._s,...P})))},[se,H,vn,Jn,Ei]);const[bp,Uu]=o.useState(null),[ru,yp]=o.useState(!1),jd=o.useCallback(async(P,X)=>{yp(!0);try{const Ye=await(await fetch(`/api/fema/floodzone?lat=${P.lat}&lng=${P.lng}`)).json();if(Ye.success&&Ye.floodZone){yf(!0);const ke=Ye.panelLookupStatus||null;Uu(ke);const jt=w6(Ye);jt&&We(Et=>{const ka=Et.inSFHA;return P6(ka)?Et:{...Et,inSFHA:{value:jt,source:"FEMA",confirmed:!1,flaggedBad:!1}}}),ye(Et=>{const ka=Et.femaFloodZone?.isEdited,Yt={...Et};return(!ka||X?.force)&&(Yt.femaFloodZone={value:Ye.floodZone,source:"FEMA",isEdited:!1,alternatives:{}}),Ye.femaMapNumber&&(!Et.femaMapNumber?.value||X?.force)&&(Yt.femaMapNumber={value:Ye.femaMapNumber,source:"FEMA",isEdited:!1,alternatives:{}}),Ye.femaMapDate&&(!Et.femaMapDate?.value||X?.force)&&(Yt.femaMapDate={value:Ye.femaMapDate,source:"FEMA",isEdited:!1,alternatives:{}}),Yt})}}catch(xe){console.error("[FEMA] Fetch error in WizardPage:",xe),Uu("provider_error")}finally{yp(!1)}},[]),Uo=Os?.lat,xl=Os?.lng,om=o.useCallback(()=>{if(Uo==null||xl==null)return;const P={lat:Uo,lng:xl},X=`${Uo.toFixed(5)},${xl.toFixed(5)}`;el.current=X,jd(P,{force:!0})},[Uo,xl,jd]);o.useEffect(()=>{if(Uo==null||xl==null)return;const P={lat:Uo,lng:xl},X=`${Uo.toFixed(5)},${xl.toFixed(5)}`,xe=!!H.femaFloodZone?.value,Ye=!!H.femaMapNumber?.value&&!!H.femaMap
53Date?.value;if(el.current!==X){if(!el.current&&xe&&Ye){el.current=X,yf(!0);return}el.current=X,jd(P)}},[Uo,xl,H.femaFloodZone?.value,H.femaMapNumber?.value,H.femaMapDate?.value,jd]),o.useEffect(()=>{const P=Ot.neighborhoodGrid,X=Ot.marketStats;if(!P&&!X)return;const xe={};if(P)xe["neighborhood.locationUrban"]=P.location==="Urban"?!0:null,xe["neighborhood.locationSuburban"]=P.location==="Suburban"?!0:null,xe["neighborhood.locationRural"]=P.location==="Rural"?!0:null,xe["neighborhood.builtUpOver75"]=P.builtUp==="Over75"?!0:null,xe["neighborhood.builtUp25to75"]=P.builtUp==="25to75"?!0:null,xe["neighborhood.builtUpUnder25"]=P.builtUp==="Under25"?!0:null,xe["neighborhood.growthRapid"]=P.growth==="Rapid"?!0:null,xe["neighborhood.growthStable"]=P.growth==="Stable"?!0:null,xe["neighborhood.growthSlow"]=P.growth==="Slow"?!0:null,xe["neighborhood.propertyValuesIncreasing"]=P.propertyValues==="Increasing"?!0:null,xe["neighborhood.propertyValuesStable"]=P.propertyValues==="Stable"?!0:null,xe["neighborhood.propertyValuesDeclining"]=P.propertyValues==="Declining"?!0:null,xe["neighborhood.demandSupplyShortage"]=P.demandSupply==="Shortage"?!0:null,xe["neighborhood.demandSupplyInBalance"]=P.demandSupply==="InBalance"?!0:null,xe["neighborhood.demandSupplyOverSupply"]=P.demandSupply==="OverSupply"?!0:null,xe["neighborhood.marketingTimeUnder3"]=P.marketingTime==="Under3Months"||P.marketingTime==="Under3"?!0:null,xe["neighborhood.marketingTime3to6"]=P.marketingTime==="3to6Months"||P.marketingTime==="3to6"?!0:null,xe["neighborhood.marketingTimeOver6"]=P.marketingTime==="Over6Months"||P.marketingTime==="Over6"?!0:null,P.priceLow&&(xe["neighborhood.priceLow"]=String(Math.round(P.priceLow/1e3))),P.priceHigh&&(xe["neighborhood.priceHigh"]=String(Math.round(P.priceHigh/1e3))),P.pricePredominant&&(xe["neighborhood.pricePredominant"]=String(Math.round(P.pricePredominant/1e3))),P.ageLow!=null&&(xe["neighborhood.ageLow"]=String(P.ageLow)),P.ageHigh!=null&&(xe["neighborhood.ageHigh"]=String(P.ageHigh)),P.agePredominant!=null&&(xe["neighborhood.agePredominant"]=String(P.agePredominant)),P.landUseOneUnit!=null&&(xe["neighborhood.landUseOneUnit"]=String(P.landUseOneUnit)),P.landUseTwoToFour!=null&&(xe["neighborhood.landUse2to4"]=String(P.landUseTwoToFour)),P.landUseMultiFamily!=null&&(xe["neighborhood.landUseMultiFamily"]=String(P.landUseMultiFamily)),P.landUseCommercial!=null&&(xe["neighborhood.landUseCommercial"]=String(P.landUseCommercial)),P.landUseOther!=null&&(xe["neighborhood.landUseOther"]=String(P.landUseOther)),P.neighborhoodBoundaries&&(xe["neighborhood.boundaries"]=P.neighborhoodBoundaries),P.neighborhoodDescription&&(xe["neighborhood.description"]=P.neighborhoodDescription),P.marketConditions&&(xe["neighborhood.marketConditions"]=P.marketConditions);else if(X){const Ye=X.inventoryAnalysis?.trend||"Stable";xe["neighborhood.propertyValuesIncreasing"]=Ye==="Increasing"?!0:null,xe["neighborhood.propertyValuesStable"]=Ye==="Stable"?!0:null,xe["neighborhood.propertyValuesDeclining"]=Ye==="Declining"?!0:null;const ke=X.monthsOfSupply;xe["neighborhood.demandSupplyShortage"]=ke<4?!0:null,xe["neighborhood.demandSupplyInBalance"]=ke>=4&&ke<=7?!0:null,xe["neighborhood.demandSupplyOverSupply"]=ke>7?!0:null;const jt=X.medianDOM;xe["neighborhood.marketingTimeUnder3"]=jt<90?!0:null,xe["neighborhood.marketingTime3to6"]=jt>=90&&jt<=180?!0:null,xe["neighborhood.marketingTimeOver6"]=jt>180?!0:null,X.priceLow&&(xe["neighborhood.priceLow"]=String(Math.round(X.priceLow/1e3))),X.priceHigh&&(xe["neighborhood.priceHigh"]=String(Math.round(X.priceHigh/1e3))),X.pricePredominant&&(xe["neighborhood.pricePredominant"]=String(Math.round(X.pricePredominant/1e3))),X.ageLow!=null&&(xe["neighborhood.ageLow"]=String(X.ageLow)),X.ageHigh!=null&&(xe["neighborhood.ageHigh"]=String(X.ageHigh)),X.agePredominant!=null&&(xe["neighborhood.agePredominant"]=String(X.agePredominant)),X.landUse&&(xe["neighborhood.landUseOneUnit"]=String(X.landUse.oneUnit),xe["neighborhood.landUse2to4"]=String(X.landUse.twoToFourUnit),xe["neighborhood.landUseMultiFamily"]=String(X.landUse.multiFamily),xe["neighborhood.landUseCommercial"]=String(X.landUse.commercial),xe["neighborhood.landUseOther"]=String(X.landUse.other))}if(Object.keys(xe).length>0){const Ye=JSON.stringify(xe);if(Ye===Ad.current)return;Ad.current=Ye,ir(ke=>({...ke,...xe}))}},[Ot]),o.useEffect(()=>{if(!xp.current&&b&&!T&&st&&se?.subjectAddress){const P=`subjectCardAutoOpened_${b}`;if(sessionStorage.getItem(P)){xp.current=!0;return}sessionStorage.setItem(P,"1"),xp.current=!0,gp(!0)}},[b,T,st,se?.subjectAddress]),o.useEffect(()=>{if(!st||!se?.subjectAddress?.value)return;const P=H.censusTract;if(P?.value&&P.value!=="")return;const X=`${se.subjectAddress?.value||""}${vn?`, ${vn}`:""}${Jn?`, ${Jn}`:""} ${Ei||""}`.trim();if(!X)return;let xe=!1;return fetch(`/api/census/geocode?onelineaddress=${encodeURIComponent(X)}`).then(Ye=>
53Ye.json()).then(Ye=>{xe||Ye.success&&Ye.censusTract?.tract&&(console.log("[Wizard] Census tract from Census Bureau:",Ye.censusTract.tract),ye(ke=>({...ke,censusTract:{value:Ye.censusTract.tract,source:"Census",isEdited:!1,alternatives:{}}})))}).catch(Ye=>console.warn("[Wizard] Census tract lookup failed:",Ye)),()=>{xe=!0}},[st,se?.subjectAddress?.value,vn,Jn,Ei,H.censusTract?.value]);const[Br,nu]=o.useState({}),[lm,xc]=o.useState(null),[cm,Hc]=o.useState(!1),[Hi,Sp]=o.useState(null),iu=(()=>{const P=Hi?.listingDetails||{},X=P.publicRemarks||P.description||"";return typeof X=="string"?X:""})(),vp=!!se?.aiConditionRating||!!se?.aiConditionSignals||!!se?.aiQualitySignals||!!se?.aiRecentUpdates,{data:Np}=W2(iu,!vp,{debounceMs:300}),ao=Np??null,[Zs,al]=o.useState([]),[Fi,Td]=o.useState(null),[Vu,Ap]=o.useState(null),[Hm,js]=o.useState(null),[bo,Wm]=o.useState(!1),[ou,Xl]=o.useState(null),Id=o.useRef(null),$u=o.useRef(!1),Km=o.useRef(!1),{enablePropertyLab:Qm,enableDemoMode:Sf,wizardSteps:Zm,stepIndices:kg,setEnableLeasehold:dm}=uL(),Vo=o.useMemo(()=>Zs.includes("leasehold")||Zs.includes("land_lease"),[Zs]);o.useEffect(()=>{Vo&&ir(P=>({...P,"subject.propertyRightsFeeSimple":void 0,"subject.propertyRightsLeasehold":!0}))},[Vo]);const xr=o.useMemo(()=>Zs.includes("str"),[Zs]),Ir=o.useMemo(()=>Zs.includes("eval"),[Zs]),[Mg,lu]=o.useState("wizardstep"),[ec,Jm]=o.useState([]),[Ma,Xn]=o.useState(!1),Bu=o.useMemo(()=>Zs.includes("tdcx_express"),[Zs]),Ea=o.useMemo(()=>nD({addOns:Zs,productType:C?.order?.productType,appId:C?.order?.appId}),[Zs,C?.order?.productType,C?.order?.appId]),so=o.useMemo(()=>{if(pt?.selectedUsed&&pt.selectedUsed.length>0){const P=[...pt.cleanedComps||[],...qe];return nj(pt.selectedUsed,P,Ir&&!Ea)}return qe},[qe,pt?.selectedUsed,pt?.cleanedComps,Ir,Ea]);o.useEffect(()=>{so.length!==0&&ir(P=>{const X=BY(P,so,{subjectCoords:Os});return X===P?P:X})},[so,Os]);const Xm=/^Comp\d+(PriorSalesOrTransfersIndicator|SaleHistoryDataSource|SaleHistory\d+_)/;o.useEffect(()=>{if(!Ea||!b||b==="new")return;let P=!1;return fetch(`/api/uad36/prefill/${encodeURIComponent(b)}?skipExternal=true`,{credentials:"include"}).then(X=>X.ok?X.json():null).then(X=>{if(P)return;const xe=X?.sections?.salesComparison;if(!xe||typeof xe!="object")return;const Ye=zs.current,ke={};for(const[Et,ka]of Object.entries(xe))Xm.test(Et)&&!(Et in Ye)&&(ke[Et]=ka);if(Object.keys(ke).length===0)return;const jt={...Ye,...ke};zs.current=jt,pr(jt)}).catch(()=>{}),()=>{P=!0}},[b,Ea]),o.useCallback(P=>{const X=zs.current[P];if(X!=null)return typeof X=="object"&&"value"in X?X.value:X},[]),o.useCallback(P=>{const X=zs.current[P];if(!(!X||typeof X!="object"))return X.source},[]),o.useCallback((P,X)=>{if(!b||b==="new"||!Xf(b))return;const xe={value:X,source:"user",confidence:"manual",userEdited:!0};zs.current={...zs.current,[P]:xe},pr(Ye=>({...Ye,[P]:xe})),$e.current&&clearTimeout($e.current),$e.current=setTimeout(()=>{if(!Xf(b))return;const Ye=zs.current;fetch(`/api/uad36/patch-section/${encodeURIComponent(b)}`,{method:"PATCH",headers:{"Content-Type":"application/json",...ho(b)},credentials:"include",body:JSON.stringify({sectionKey:"salesComparison",sectionData:Ye})}).catch(ke=>console.error("[WizardPage] sale history autosave failed",ke))},1200)},[b]);const zu=S&&!N&&Ea,jo=!Ea,$a=o.useMemo(()=>Zs.includes("as_is_after_repaired"),[Zs]),{isLockOwner:ci,isLockAcquiring:um,presenceRoster:Wc,showInactivityWarning:yo,showLockReleasedModal:Kr,lockReleasedAdminForced:cu,adminForcedNotification:bb,sessionExpiredBanner:bc,keepEditing:Cd,releaseFromWarning:Fg,claimLock:_g,declineLock:eh,lockedBy:jp,lockAcquireError:ei,adminForceBreak:Ug,isAdmin:Vg,releaseLock:tc}=gV(Ea?b:null),du=Ea&&!ci&&!um,uu=o.useMemo(()=>Ea?"3.6":Ir?"eval":xr?"str":String(H.propertyType?.value??"").toLowerCase().includes("condo")?"1073":"1004",[Ea,Ir,xr,H.propertyType?.value]),yc=o.useMemo(()=>{const P=new Set(["netAdjustment","grossAdjustment","adjustedSalePrice"]),X=(ke,jt)=>{const Et=Ks[ke];if(!Et)return jt;let ka=0;for(const[Yt,ha]of Object.entries(Et)){if(P.has(Yt))continue;const Rt=typeof ha=="number"?ha:Number(ha);Number.isFinite(Rt)&&(ka+=Rt)}return jt+ka},xe=Object.keys(hl).length>0,Ye=ke=>{const jt=[];for(const Yt of qe){const ha=hl[Yt.compId];if(!(ke==="as-is"?!xe||!ha||ha==="as-is"||ha==="both":ha==="after-repaired"||ha==="both"))continue;const Bt=typeof Yt.price=="number"?Yt.price:Number(Yt.price);!Number.isFinite(Bt)||Bt<=0||jt.push(X(Yt.compId,Bt))}if(jt.length===0)return null;const Et=Math.min(...jt),ka=Math.max(...jt);return{low:Et,high:ka,mid:Math.round((Et+ka)/2)}};return{asIs:Ye("as-is"),afterRepaired:Ye("after-repaired")}},[qe,hl,Ks]),wi=o.useCallback(P=>{const X=new Set(["netAdjustment","grossAdjustment","adjustedSalePrice"]),xe=Object.keys(hl).length>0,Ye=[];for(const ke of qe){const jt=hl[ke.compId];if(!(P==="as-is"?!xe||!jt||jt==="as-is"||jt==="both":jt==="after-repaired"||jt==="both"))continue;
53const ka=typeof ke.price=="number"?ke.price:Number(ke.price),Yt=Ks[ke.compId];let ha=null;if(Number.isFinite(ka)){let Bt=0;if(Yt)for(const[Jt,gt]of Object.entries(Yt)){if(X.has(Jt))continue;const Ra=typeof gt=="number"?gt:Number(gt);Number.isFinite(Ra)&&(Bt+=Ra)}ha=ka+Bt}const Rt=!!ke.saleDate||/sold|closed/i.test(ke.listingStatus||"");Ye.push({address:ke.address,status:Rt?"Sold":"Active",price:ka,adjustedPrice:ha,saleDate:ke.saleDate??null,listDate:ke.listDate??null,gla:ke.gla??null,beds:ke.beds??null,baths:ke.baths??null,photoUrl:ke.photoUrl??(ke.photos&&ke.photos.length>0?ke.photos[0]:null)})}return Ye},[qe,hl,Ks]),Rd=o.useMemo(()=>o6({appId:C?.order?.appId,addOns:Zs,productType:C?.order?.productType}),[C?.order?.appId,C?.order?.productType,Zs]),[$g,qu]=o.useState(null),bl=o.useRef(null),Yu=o.useRef(null),pm=!A&&Re===b;o.useEffect(()=>{const P=MT[Rd],X=P?.strictnessRank??0;if(!pm){bl.current=null,Yu.current=null;return}const xe=bl.current,Ye=xe===null||xe.key!==Rd||xe.rank!==X,ke=Yu.current!==xr;if(b&&(Ye||ke)){const jt=`profileBannerShown_${b}`;if(!sessionStorage.getItem(jt)){if(xe!==null&&X>xe.rank){sessionStorage.setItem(jt,"1");const Et=MT[xe.key],ka=Et?FT(Et):[],Yt=FT(P),ha=gt=>gt.reduce((Ra,fa)=>Ra+fa.fields.filter(Is=>Is.required).length,0),Rt=Math.max(0,ha(Yt)-ha(ka)),Bt=Rt>0?` — ${Rt} new required field${Rt!==1?"s":""} added`:"",Jt=`Products updated — Step Two now shows ${P.label} fields${Bt}. Previously entered values are preserved.`;qu(gt=>gt===Jt?gt:Jt)}else if(xe!==null&&Yu.current===!1&&xr){sessionStorage.setItem(jt,"1");const Et='STR add-on activated — a dedicated "STR Subject Data" step (Step 2a) has been added to the wizard.';qu(ka=>ka===Et?ka:Et)}}}bl.current={key:Rd,rank:X},Yu.current=xr},[Rd,xr,pm]);const[Us,Kc]=o.useState([]),[yb,Pi]=o.useState(!1),Lr=o.useRef(null);o.useEffect(()=>{if(!xr||Uo==null||xl==null||!Re||Re!==b)return;const P=`${Re}-${Uo}-${xl}`;if(Lr.current===P)return;(async()=>{Pi(!0);try{const xe=new URLSearchParams({lat:Uo.toString(),lng:xl.toString(),radiusMiles:"5"}),Ye=await fetch(`/api/str/comps?${xe}`);if(Ye.ok){const ke=await Ye.json();ke.success&&ke.comps?.length>0?(console.log(`[STR] Fetched ${ke.comps.length} STR rental comps from database`),Kc(ke.comps),Lr.current=P):(console.log("[STR] No STR rental comps found in database, falling back to Property Lab comps"),Kc([]),Lr.current=P)}}catch(xe){console.error("[STR] Error fetching STR comps:",xe)}finally{Pi(!1)}})()},[xr,Uo,xl,Re,b]);const Qc=o.useMemo(()=>{if(!xr||!Re||Re!==b)return null;const P=se.subjectAddress?.value||"",X=ke=>ke?.value??ke??void 0,xe=H,Ye=FJ({strBedsPerUnit:X(xe.strBedsPerUnit),strBathsPerUnit:X(xe.strBathsPerUnit),gridBeds:typeof xe.beds=="object"?void 0:xe.beds,gridBaths:typeof xe.baths=="object"?void 0:xe.baths,gridGla:typeof xe.gla=="object"?void 0:xe.gla,coreBeds:Br.beds??Hp(X(xe.bedrooms))??null,coreBaths:Br.baths??Hp(X(xe.bathrooms))??null,coreGla:Br.gla??Hp(X(xe.grossLivingArea))??null,coreYearBuilt:Br.yearBuilt??Hp(X(xe.yearBuilt))??null,corePropertyType:Br.propertyType||X(xe.propertyType)||null,propmix:xe.strPropmixSubjectFacts??null});return{address:P,city:vn||"",state:Jn||"",zip:Ei||"",county:X(xe.county)||void 0,parcelNumber:X(xe.pinNumber)||X(xe.parcelNumber)||void 0,propertyType:Ye.propertyType,bedrooms:Ye.bedrooms,bathrooms:Ye.bathrooms,gla:Ye.gla,guestCapacity:Br.guestCapacity??Hp(xe.guestCapacity)??void 0,yearBuilt:Ye.yearBuilt,propmixPrefilledFields:Ye.propmixPrefilledFields.length>0?Ye.propmixPrefilledFields:void 0,totalRooms:X(xe.totalRooms)?Number(X(xe.totalRooms)):void 0,condition:X(xe.condition)||Br.condition||void 0,zoning:X(xe.zoningClassification)||void 0,zoningType:X(xe.zoningDescription)||void 0,zoningCompliance:X(xe.zoningCompliance)||void 0,parking:X(xe.garageType)||void 0,garageCars:X(xe.garageCars)?Number(X(xe.garageCars)):void 0,laundry:X(xe.laundry)||void 0,patioYardBalcony:X(xe.patioYardBalcony)||X(xe.patio)||void 0,pool:X(xe.pool)||void 0,adu:X(xe.adu)||void 0,annualTaxes:(()=>{const ke=X(xe.taxes);if(ke)return typeof ke=="number"?`$${ke.toLocaleString()}`:String(ke)})(),lenderClient:se.lender?.value||se.client?.value||void 0,borrower:se.borrower?.value||void 0,dataSource:"C
53ore",latitude:Os?.lat??void 0,longitude:Os?.lng??void 0,photoUrl:mr?.[0]||void 0,photos:mr?.length>0?mr:void 0,_sourceOrderId:Re||void 0}},[xr,se,Br,vn,Jn,Ei,mr,Re,b,Os,H]),Dl=o.useMemo(()=>{if(!xr)return{comps:[],_sourceOrderId:void 0};if(!Re||Re!==b)return{comps:[],_sourceOrderId:void 0};const P=Yt=>(Yt||"").toLowerCase().replace(/[^a-z0-9]/g,""),X=(Yt,ha,Rt,Bt)=>{const Jt=cs=>cs*(Math.PI/180),Ra=Jt(Rt-Yt),fa=Jt(Bt-ha),Is=Math.sin(Ra/2)**2+Math.cos(Jt(Yt))*Math.cos(Jt(Rt))*Math.sin(fa/2)**2;return 3959*2*Math.atan2(Math.sqrt(Is),Math.sqrt(1-Is))},xe=Os?.lat,Ye=Os?.lng,ke=(Yt,ha)=>{if(xe&&Ye&&Yt&&ha)return Math.round(X(xe,Ye,Yt,ha)*100)/100},jt=qe.map(Yt=>({norm:P(Yt.address||""),lat:parseFloat(Yt.latitude||Yt.lat)||void 0,lng:parseFloat(Yt.longitude||Yt.lng||Yt.lon)||void 0})),Et=(Yt,ha,Rt)=>{if(qe.length===0)return!0;const Bt=P(Yt);for(const Jt of jt){if(Jt.norm===Bt)return!0;const gt=Jt.norm.length<Bt.length?Jt.norm:Bt,Ra=Jt.norm.length<Bt.length?Bt:Jt.norm;if(gt.length>10&&Ra.startsWith(gt)||gt.length>10&&Ra.includes(gt)||ha&&Rt&&Jt.lat&&Jt.lng&&Math.abs(ha-Jt.lat)<.001&&Math.abs(Rt-Jt.lng)<.001)return!0}return!1};if(Us.length>0){const Yt=Us.map((Rt,Bt)=>{const Jt=parseFloat(Rt.strAverageDailyRate)||0,gt=Rt.strOccupancyRate?parseFloat(Rt.strOccupancyRate)>1?parseFloat(Rt.strOccupancyRate)/100:parseFloat(Rt.strOccupancyRate):0,Ra=Rt.photoUrl||Rt.primaryPhotoUrl||Rt.imageUrl,fa=Rt.photos||(Ra?[Ra]:void 0),Is=parseFloat(Rt.latitude)||void 0,cs=parseFloat(Rt.longitude)||void 0,br=Et(Rt.address||"",Is,cs);return{id:Rt.id||`str-rental-${Bt}`,sourceName:Rt.strSource||"Airbnb",addressAssumed:Rt.address||"",lat:Is,lng:cs,distanceMiles:ke(Is,cs),bedrooms:Rt.bedrooms||0,bathrooms:Rt.bathrooms||0,gla:Rt.prLivingArea||Rt.mlsTotalLivingArea||0,yearBuilt:Rt.yearBuilt||void 0,propertyType:Rt.strRentalType||"EntireHome",nightlyRateBase:Jt,occupancyRate:gt,monthlyRevenue:Jt*gt*30,annualRevenue:parseFloat(Rt.strGrossRevenue12mo)||Jt*gt*365,photoUrl:Ra,photos:fa,strAverageDailyRate:Jt,strOccupancyRate:parseFloat(Rt.strOccupancyRate)||0,strProvider:Rt.strSource,strProviderId:Rt.
53strProviderId,strListingName:Rt.strListingName,strRating:parseFloat(Rt.strRating)||void 0,strReviewCount:parseInt(Rt.strReviewCount)||void 0,strGrossRevenue12mo:parseFloat(Rt.strGrossRevenue12mo)||void 0,strGuestCapacity:parseInt(Rt.strGuestCapacity)||void 0,strRentalType:Rt.strRentalType,strCleaningFee:parseFloat(Rt.strCleaningFee)||void 0,strPlatformFee:parseFloat(Rt.strPlatformFee)||void 0,dataAsOf:Rt.dataAsOf??null,lastReviewDate:Rt.lastReviewDate??null,selected:br}}),ha=Yt.filter(Rt=>Rt.selected).length;return console.log(`[STR] Using ${Yt.length} STR rental comps from database (${ha} grid-selected, ${qe.length} cleanedComps)`),ha===0&&qe.length>0&&(console.warn("[STR] Address match failed! cleanedComps addrs:",jt.map(Rt=>Rt.norm.substring(0,40))),console.warn("[STR] strRentalComps addrs:",Yt.map(Rt=>P(Rt.addressAssumed).substring(0,40)))),{comps:Yt,_sourceOrderId:Re||void 0}}return qe.length===0?{comps:[],_sourceOrderId:Re}:{comps:qe.map((Yt,ha)=>{const Rt=br=>Yt.cleanedFields?.find(_s=>_s.fieldKey===br)?.finalValue,Bt=Yt,Jt=Bt.strAverageDailyRate||0,gt=Bt.strOccupancyRate?Bt.strOccupancyRate>1?Bt.strOccupancyRate/100:Bt.strOccupancyRate:0,Ra=Bt.photoUrl||(Bt.photos?.length>0?typeof Bt.photos[0]=="string"?Bt.photos[0]:Bt.photos[0]?.url:void 0)||(Bt.photoUrls?.length>0?Bt.photoUrls[0]:void 0)||Bt.primaryPhotoUrl||Bt.imageUrl||Bt.thumbnail,fa=Bt.photos||Bt.photoUrls||(Ra?[Ra]:void 0),Is=parseFloat(Bt.latitude)||parseFloat(Bt.lat)||void 0,cs=parseFloat(Bt.longitude)||parseFloat(Bt.lng)||parseFloat(Bt.lon)||void 0;return{id:Yt.compId||`str-comp-${ha}`,sourceName:Bt.strSource||Bt.strProvider||"PropMix",addressAssumed:Yt.address||"",distanceMiles:ke(Is,cs),bedrooms:Yt.beds||Rt("beds")||0,bathrooms:Yt.baths||Rt("baths")||0,gla:Yt.gla||Rt("gla")||0,yearBuilt:Rt("yearBuilt")||void 0,nightlyRateBase:Jt,occupancyRate:gt,photoUrl:Ra,photos:fa,strAverageDailyRate:Jt,strOccupancyRate:Bt.strOccupancyRate||0,strProvider:Bt.strProvider||Bt.strSource,strProviderId:Bt.strProviderId,strListingName:Bt.strListingName,strRating:Bt.strRating,strReviewCount:Bt.strReviewCount,strGrossRevenue12mo:Bt.strGrossRevenue12mo,strGrossMonthlyIncome:Bt.strGrossMonthlyIncome,strComparability:Bt.strComparability,editedStrAverageDailyRate:Bt.editedStrAverageDailyRate,editedStrOccupancyRate:Bt.editedStrOccupancyRate,dataAsOf:Bt.dataAsOf??null,lastReviewDate:Bt.lastReviewDate??null,selected:!0}}),_sourceOrderId:Re||void 0}},[xr,Us,qe,Re,b,Os]),$o={PropMix:"Verified Data",Mashvisor:"Verified Data",Airbtics:"Verified Data",AirDNA:"Verified Data",InsideAirbnb:"Airbnb",VRBO:"Vrbo"},Sc=o.useMemo(()=>{if(!(!xr||Us.length===0))return Us.map((P,X)=>{const xe=parseFloat(P.strAverageDailyRate)||0,Ye=P.strOccupancyRate?parseFloat(P.strOccupancyRate)>1?parseFloat(P.strOccupancyRate)/100:parseFloat(P.strOccupancyRate):0,ke=P.strSource||"",jt=$o[ke]||ke||"Verified Data",Et=P.photoUrl||P.primaryPhotoUrl||P.imageUrl;return{id:P.id||`str-map-${X}`,address:P.address||"",lat:parseFloat(P.latitude)||void 0,lng:parseFloat(P.longitude)||void 0,nightlyRate:xe,occupancyRate:Ye,annualRevenue:parseFloat(P.strGrossRevenue12mo)||xe*Ye*365||void 0,bedrooms:P.bedrooms||void 0,bathrooms:P.bathrooms||void 0,gla:P.prLivingArea||P.mlsTotalLivingArea||void 0,platform:jt,rentalType:P.strRentalType||void 0,photoUrl:Et,photos:P.photos||(Et?[Et]:void 0),rating:parseFloat(P.strRating)||void 0,reviewCount:parseInt(P.strReviewCount)||void 0,listingName:P.strListingName||void 0}})},[xr,Us]),Wi=Qm&&!Bu,ti=AN(b??void 0,Ea),sl=Wi&&(!Ea||ti.useSalesComparison!==!1||ti.useIncomeApproach||ti.useRentalApproach),Ed=Ea&&(ti.approaches.useCostApproach.checked||ti.approaches.useSiteValuation.checked),Tp=ti.approaches.useCostApproach.checked?"Cost Approach":"Site Valuation",[Ip,Cp]=o.useState({exists:null,reviewed:null});o.useEffect(()=>{Cp({exists:null,reviewed:null})},[b]),o.useEffect(()=>{const P=X=>{const xe=X.detail;xe.orderId===b&&(xe.field==="SalesContractExistsIndicator"?Cp(Ye=>({...Ye,exists:xe.value===!0})):xe.field==="SalesContractReviewedIndicator"&&Cp(Ye=>({...Ye,reviewed:xe.value===!0})))};return window.addEventListener("uad36-sc-gate-change",P),()=>window.removeEventListener("uad36-sc-gate-change",P)},[b]);const ro=ti.uad36Sections?.salesContract?.SalesContractExistsIndicator?.value,vf=ti.uad36Sections?.salesContract?.SalesContractReviewedIndicator?.value,pu=Ip.exists!==null?Ip.exists:ro===!0||ro==="true",mu=Ip.reviewed!==null?Ip.reviewed:vf===!0||vf==="true",hu=Ea&&pu&&mu,[th,as]=o.use
53State({inProject:null,pud:null});o.useEffect(()=>{as({inProject:null,pud:null})},[b]),o.useEffect(()=>{const P=X=>{const xe=X.detail;xe.orderId===b&&(xe.field==="PropertyInProjectIndicator"?as(Ye=>({...Ye,inProject:xe.value===!0||xe.value==="true"})):xe.field==="PUDIndicator"&&as(Ye=>({...Ye,pud:xe.value===!0||xe.value==="true"})))};return window.addEventListener("uad36-pi-gate-change",P),()=>window.removeEventListener("uad36-pi-gate-change",P)},[b]);const mm=ti.uad36Sections?.subjectProperty?.PropertyInProjectIndicator?.value,fu=ti.uad36Sections?.subjectProperty?.PUDIndicator?.value,hm=th.inProject!==null?th.inProject:mm===!0||mm==="true",Fn=th.pud!==null?th.pud:fu===!0||fu==="true",Zc=Ea&&(hm||Fn),fm=ti.uad36Sections?.subjectListing?.ListedWithinPreviousYearIndicator?.value,gm=ti.uad36Sections?.priorSaleTransferHistory?.PriorSalesOrTransfersIndicator?.value,wn=Ea&&(fm===!0||fm==="true"||gm===!0||gm==="true"),no=(!xr||Vo)&&!Ea&&!Ir,Pn=o.useMemo(()=>{const P=[];return T&&P.push("Address"),Ea&&(P.push("At A Glance"),P.push("Assignment"),P.push("Subject Property"),P.push("Site"),P.push("Improvements")),hu&&P.push("Sales Contract"),Zc&&P.push("Project Information"),wn&&P.push("Listing & Sale History"),Ea&&P.push("Market"),Ed&&P.push(Tp),P.push("Order"),P.push("Subject & Site"),xr&&P.push("STR Subject"),Wi&&(P.push("Subject Verify"),P.push("Property Lab"),sl&&P.push("Sales Grid")),Vo&&(P.push("Lease Summary"),P.push("Agency Check"),P.push("Rights Calculator"),P.push("Rights Adjust"),P.push("Addendum")),xr&&P.push("STR Analysis"),Ir&&P.push("Evaluation"),no&&P.push("Review"),P},[T,Ea,zu,Wi,sl,Ed,Tp,hu,Zc,wn,Vo,xr,Ir,no]),ca=o.useMemo(()=>{let P=0;const X={};return T?X.ADDRESS=P++:X.ADDRESS=-1,X.AT_A_GLANCE_36=Ea?P++:-1,X.ASSIGNMENT_36=Ea?P++:-1,X.SUBJECT_PROPERTY_36=Ea?P++:-1,X.SITE_36=Ea?P++:-1,X.IMPROVEMENTS_36=Ea?P++:-1,X.SALES_CONTRACT_36=hu?P++:-1,X.PROJECT_INFORMATION_36=Zc?P++:-1,X.LISTING_SALE_HISTORY_36=wn?P++:-1,X.MARKET_36=Ea?P++:-1,X.COST_APPROACH_36=Ed?P++:-1,X.ORDER=P++,X.ORDER_36=zu?X.ORDER:-1,X.SUBJECT_SITE=P++,X.STR_SUBJECT=xr?P++:-1,X.COMP_INTENT=Wi?P++:-1,X.PROPERTY_LAB=Wi?P++:-1,X.SALES_GRID=sl?P++:-1,Vo?(X.LEASE_SUMMARY=P++,X.AGENCY_CHECK=P++,X.CALCULATOR=P++,X.RIGHTS_ADJUST=P++,X.ADDENDUM=P++):(X.LEASE_SUMMARY=-1,X.AGENCY_CHECK=-1,X.CALCULATOR=-1,X.RIGHTS_ADJUST=-1,X.ADDENDUM=-1),xr?X.STR=P++:X.STR=-1,Ir?X.EVAL=P++:X.EVAL=-1,X.REVIEW=no?P:-1,X},[T,Ea,zu,Wi,sl,Ed,hu,Zc,wn,Vo,xr,Ir,no]),pn=o.useMemo(()=>{const P=[];return T&&P.push("address_entry"),Ea&&(P.push("at_a_glance_36"),P.push("assignment_36"),P.push("subject_property_36"),P.push("site_36"),P.push("improvements_36")),hu&&P.push("sales_contract_36"),Zc&&P.push("project_information_36"),wn&&P.push("listing_sale_history_36"),Ea&&P.push("market_36"),Ed&&P.push("cost_approach_36"),P.push("order_snapshot"),P.push("subject_site"),xr&&P.push("str_subject"),Wi&&(P.push("comp_intent"),P.push("property_lab"),sl&&P.push("sales_grid")),Vo&&P.push("lease_summary","agency_check","calculator","rights_adjust","addendum"),xr&&P.push("str_analysis"),Ir&&P.push("eval"),no&&P.push("review"),P},[T,Ea,zu,Wi,sl,Ed,hu,Zc,wn,Vo,xr,Ir,no]),io=Pn.length,Rp=o.useRef(t);Rp.current=t;const ah=o.useRef(pn);o.useEffect(()=>{const P=ah.current;if(ah.current=pn,P===pn)return;const X=dX(P,pn,Rp.current);X!==null&&a(X)},[pn]);const ac=ca.REVIEW,sc=o.useMemo(()=>D6(ca),[ca]),Bg=Ea&&sc.some(P=>P.stepIndex===t),Sb=o.useMemo(()=>{const P=Array.isArray(ti.subjectBuildings)?ti.subjectBuildings:[],X=(Ye,ke)=>ti.uad36Sections[Ye]?.[ke]?.value,xe=X("scopeOfWork","GovernmentAgencyAppraisalType")||null;return _6([...L6,...xV,...bV(P,{governmentAgencyAppraisalIndicator:xe==="FHA"||xe==="USDA"||xe==="VA",attachmentType:X("subjectProperty","AttachmentType")||null,homeownerResponsibleForExteriorMaintenance:X("subjectProperty","HomeownerResponsibleForExteriorMaintenanceIndicator")??null,costApproachIndicator:ti.approaches.useCostApproach.checked}),...yV(),...SV(UL)],sc)},[ti.approaches.useCostApproach.checked,ti.subjectBuildings,ti.uad36Sections,sc]),yl=o.useRef(0),zg=o.useCallback((P,X,xe)=>{const Ye=xe.routeSectionId??P,ke=UT(Ye)??P,jt=sc.find(Et=>Et.sectionId===ke);if(!(!jt||jt.stepIndex===-1)){if(xe.kind==="heading"){a(jt.stepIndex),window.scrollTo(0,0);const Et=xe.element;Et&&setTimeout(()=>Et.scrollIntoView({behavior:"smooth",block:"center"}),250);return}yl.current+=1,c({sectionId:Ye,fieldName:X,nonce:yl.current,ownerSectionId:jt.sectionId}),a(jt.stepIndex),window.scrollTo(0,0)}},[sc]),Gu=o.useCallback(()=>U6(sc),[sc]);o.useEffect(()=>{if(pn.length>0&&t>=pn.length){const P=pn.length-1;console.warn(`[Wizard] currentStep ${t} exceeds stepKeyMap length ${pn.length}, clamping to ${P}`),a(P)}},[pn.length,t]),o.useEffect(()=>{Pg(!1)},[t]),o.useEffect(()=>{if(!u.current.has(t)){const P=new Set(u.current);P.add(t),u.current=P,p(P)}},[t]),o.useEffect(()=>{const P=ca.COMP_INTENT>=0&&t===ca.COMP_INTENT,X=ca.COMP_INTENT>=0&&rm.current===ca.COMP_INTENT;P&&!X&&tu(!0),rm.current=t,nm.current=!0},[t,ca.COMP_INTENT]);const sh=Vo,gu=xr,{status:rl,isLoading:Hu,isReady:Nf,isComplete:_i}=Jz({subjectAddress:se.subjectAddress?.value||null,subjectLat:Os?.lat??null,subjectLng:Os?.lng??null,enabled:!!Os&&!!se.subjectAddress?.value&&!gu}),[Af,oo]=o.useState(null),[Wu,Qr]=o.useState(!O),hr=o.useMemo(()=>{const P=localStorage.getItem("vault_selected_products");if(P)try{const X=JSON.parse(P);if(Array.isArray(X)&&X.length>0)return X.filter(xe=>{const Ye=DO.getProduct(xe);return Ye&&Ye.isAvailable})}catch{localStorage.removeItem("vault_selected_products")}return[]},[]),Hn=o.useCallback(P=>{if(P.length===0)return;const X=P[0],xe=DO.getProduct(X);if(xe){oo(xe),localStorage.setItem("vault_selected_product",X),localStorage.setItem("vault_selected_products",JSON.stringify(P));const Ye=[];P.includes("land_lease")&&Ye.push("land_lease"),P.includes("energy_vault")&&Ye.push("energy_vault"),P.includes("str")&&Ye.push("str"),P.includes("eval")&&(Ye.push("eval"),fetch("/api/eval/templates").then(jt=>jt.json()).then(jt=>{jt.success&&jt.templates?.length>0&&(Jm(jt.templates),jt.templates.length===1?lu(jt.templates[0].templateKey):Xn(!0))}).catch(()=>{})),P.includes("tdcx_express")&&Ye.push("tdcx_express"),P.includes("as_is_after_repaired")&&Ye.push("as_is_after_repaired"),P.includes("form_uad36")&&Ye.push("form_uad36"),al(Ye);const ke=P.includes("land_lease");dm(ke)}Qr(!1),a(0)},[dm]);o.useEffect(()=>{if(Sf&&!st){const P=Ye=>({value:Ye,source:"User",isEdited:!1,alternatives:{echo:Ye,public_record:Ye}}),X={...ux,neighborhoodName:P("Lincoln Park"),yearBuilt:P("2005"),taxes:P("$8,500"),zoningClassification:P("R-3"),zoningDescription:P("Single Family Residential")},xe={...d0(),subjectAddress:P("123 Demo Street, Chicago, IL 60601"),loanNumber:P("DEMO-12345"),
53client:P("Demo Bank"),lender:P("Demo Lender"),borrower:P("John Demo"),form:P("1004"),purpose:P("Purchase")};ye(X),fe(xe),Xt(!0),qs({lat:41.9219,lng:-87.6512}),xc({mlsNumber:"DEMO123456",listPrice:45e4,listDate:"11/01/2024",status:"Active"}),nu({gla:2200,beds:4,baths:2.5,yearBuilt:2005,lotSize:5e3,basement:"Full",garageSpaces:2})}},[Sf,st]);const rh=o.useCallback(P=>{switch(P){case"prefer_mls":return["mls"];case"prefer_public_record":return["public_record"];case"prefer_echo":return["echo"];default:return[]}},[]),xm=o.useCallback((P,X)=>{if(X==="system")return P;const xe=rh(X);if(xe.length===0)return P;const Ye={...P};return["neighborhoodName","pinNumber","legalDescription","taxYear","taxes","yearBuilt","hoaFees","pud","zoningClassification","zoningDescription","zoningCompliance","highestBestUse"].forEach(jt=>{const Et=Ye[jt];if(Et&&!Et.isEdited&&Et.alternatives){const ka=Et.alternatives;let Yt;for(const ha of xe){const Rt=ka[ha];if(Rt!=null&&Rt!==""){Yt=Rt;break}}Yt!==void 0&&Yt!==Et.value&&(Ye[jt]={...Et,value:Yt,source:X==="prefer_echo"?"Echo":X==="prefer_mls"?"MLS":"PublicRecord"})}}),Ye},[rh]);o.useCallback((P,X)=>{Oa(P),P!=="system"&&ye(xe=>xm(xe,P)),X?.rememberForFuture&&(localStorage.setItem("sourcePreference",P),m({title:"Preference Saved",description:`Source preference set to "${P.replace("_"," ")}" for future assignments.`})),console.log("Source preference changed:",{preference:P,rememberForFuture:X?.rememberForFuture})},[m,xm]);const nh=o.useCallback(()=>{let P=0;return["neighborhoodName","pinNumber","legalDescription","taxYear","taxes","yearBuilt","hoaFees","pud","zoningClassification","zoningDescription","zoningCompliance","highestBestUse"].forEach(xe=>{const Ye=H[xe];Ye&&!Ye.isEdited&&Kz(Ye.alternatives||{},String(Ye.value),Ye.isEdited)==="mismatch"&&P++}),P},[H]),jf=o.useMemo(()=>{const P=pa=>pa&&typeof pa=="object"&&"value"in pa?pa.value:pa,X=pa=>{const Gt=String(pa??"").replace(/[^0-9.]/g,""),hs=parseFloat(Gt);return Number.isFinite(hs)&&hs>=0?hs:void 0},xe=IO({propertyData:H,orderData:se,historyData:Be,propMixData:Hi}),Ye=X(H.gla?.value)??X(H.grossLivingArea?.value)??xe.gla??Br.gla,ke=X(H.bedrooms?.value)??xe.beds??Br.beds,jt=H.fullBaths?.value,Et=H.halfBaths?.value,ka=X(jt),Yt=X(Et),ha=ka!==void 0||Yt!==void 0,Jt=(ka??0)+(Yt??0)*.5,gt=ha?Jt:X(H.bathrooms?.value)??xe.baths??Br.baths,Ra=String(H.yearBuilt?.value??"").replace(/[^0-9]/g,""),fa=Ra?parseInt(Ra,10):NaN,Is=Number.isFinite(fa)&&fa>1800?fa:xe.yearBuilt??Br.yearBuilt,cs=String(H.lotSize?.value??""),br=/ac/i.test(cs),zr=X(cs),_s=zr?br?Math.round(zr*43560):zr:xe.lotSize??Br.lotSize,et=MJ(Ri,{condition:H.condition?.value,quality:H.quality?.value}
53,{condition:xe.condition,quality:xe.quality});return{gla:Ye,beds:ke,baths:gt,fullBathrooms:ka,halfBathrooms:Yt,yearBuilt:Is,lotSize:_s,view:H.view?.value||xe.viewType,condition:et.condition,quality:et.quality,designStyle:String(H.designStyle?.value??""),attachmentType:String(P(H.attachmentType)??Br.attachmentType??""),location:"",siteInfluence:String(P(H.location)??P(H.siteInfluence)??P(H.siteInfluenceType)??P(H.SiteInfluenceType)??Br.siteInfluence??Br.location??""),totalRooms:X(P(H.totalRooms))??X(P(H.aboveGradeTotal))??Br.totalRooms,garageParking:fs?qt:my(Ue.length>0||xt?Ue:Te.items??[],xt||Ue.length===0&&Te.explicitNone),pool:xe.pool,driveway:xe.driveway,physicalCondition:xe.condition}},[H,se,Be,Hi,Br,Ri,Ue,xt,Te,fs,qt]),Tf=o.useMemo(()=>qz(H),[H]),Jc=o.useMemo(()=>{const P=(X,xe="Derived")=>({value:X!=null?String(X):"",source:xe,isEdited:!1,alternatives:X!=null?{[xe.toLowerCase().replace(" ","_")]:String(X)}:{}});return{...H,gla:H.gla||(Br.gla?P(Br.gla,"MLS"):void 0),bedrooms:H.bedrooms||(Br.beds?P(Br.beds,"MLS"):void 0),lotSize:H.lotSize||(Br.lotSize?P(`${Br.lotSize.toLocaleString()} sf`,"MLS"):void 0),garageCars:H.garageCars||(Br.garageSpaces?P(Br.garageSpaces,"MLS"):void 0),fullBaths:H.fullBaths||(Br.baths?P(Math.floor(Br.baths),"MLS"):void 0),halfBaths:H.halfBaths||(Br.baths&&Br.baths%1>0?P(Math.round(Br.baths%1*2),"MLS"):void 0)}},[H,Br]),J=o.useCallback(P=>{!b||!O||Lh(b,EJ(P)).catch(X=>{console.warn("[AI Photo Analysis] Failed to persist aiPhotoRatings marker:",X)})},[b,O]),he=async(P,X)=>{const xe=mv(P,H),Ye=MO(P,P.allListingSheets);ye(Bt=>mv(P,Bt)),fe(Bt=>BX(P,X,Bt)),He(Ye),Xt(!0);const ke=P.propertyDetails||{},jt=P.listingDetails||{};if(Sp({listingDetails:jt,propertyDetails:ke}),jt.listingId||jt.listPrice||jt.status?(Hc(!1),xc({mlsNumber:jt.listingId||jt.mlsNumber,listPrice:jt.listPrice,listDate:jt.listDate||"",status:jt.status,salePrice:jt.salePrice||jt.closePrice||jt.soldPrice,saleDate:jt.soldDate||jt.closeDate?new Date(jt.soldDate||jt.closeDate).toLocaleDateString():""})):Hc(!0),b&&O){const Bt=ke.coordinates?.lat||X?.lat,Jt=ke.coordinates?.lng||X?.lng;fetch(`/api/v2/orders/${b}`,{method:"PATCH",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({propertyData:{propMixData:P,addressInfo:X},latitude:Bt?String(Bt):null,longitude:Jt?String(Jt):null})}).then(()=>{console.log("[Wizard] Saved property data to order")}).catch(gt=>{console.error("[Wizard] Failed to save property data:",gt)})}ke.coordinates?qs(ke.coordinates):X?.lat&&X?.lng&&qs({lat:X.lat,lng:X.lng}),X?.state&&Yc(X.state),X?.city&&su(X.city),X?.zipCode&&Gc(X.zipCode);const Et=ke.coordinates?.lat||X?.lat,ka=ke.coordinates?.lng||X?.lng;if(Et&&ka&&Zn("/api/comps/prewarm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lat:Et,lng:ka,subjectAddress:X?.fullAddress||"",assignmentId:b})}).then(Bt=>{Bt.success?console.log("[Prewarm] Started background comp fetch:",Bt.status):console.warn("[Prewarm] Failed to start:",Bt.error)}).catch(Bt=>{console.warn("[Prewarm] Request failed:",Bt)}),Et&&ka){const Bt=b||"subject",Jt=`${Bt}:${Et}:${ka}`;_o.current.has(Jt)||(_o.current.add(Jt),fetch(`/api/els/${Bt}?lat=${Et}&lng=${ka}`).then(gt=>gt.json()).then(gt=>{if(gt.success){const Ra=[];if(gt.factorSubscores){const fa=gt.factorSubscores,Is=gt.rawSignals||{};fa.flood!==void 0&&Ra.push({name:"Flood Zone",status:fa.flood>=80||fa.flood>=50?"OK":"−",detail:Is.femaFloodZone||"",subscore:fa.flood}),fa.highway!==void 0&&Ra.push({name:"Highway Proximity",status:fa.highway>=80||fa.highway>=50?"OK":"−",detail:`${Math.round(Is.distanceToHighway||0)} ft`,subscore:fa.highway}),fa.rail!==void 0&&Ra.push({name:"Railroad Proximity",status:fa.rail>=80||fa.rail>=50?"OK":"−",detail:`${Math.round(Is.distanceToRail||0)} ft`,subscore:fa.rail}),fa.water!==void 0&&Ra.push({name:"Water Feature",status:fa.water>=60?"+":"OK",detail:`${Math.round(Is.distanceToWater||0)} ft`,subscore:fa.water}),fa.park!==void 0&&Ra.push({name:"Park/Green Space",status:fa.park>=60?"+":"OK",detail:`${Math.round(Is.distanceToPark||0)} ft`,subscore:fa.park})}Nn({score:gt.score,tier:gt.tier,factors:Ra}),console.log(`[ELS] Subject property score: ${gt.score} (${gt.tier})`)}}).catch(gt=>console.warn("[ELS] Failed to compute subject score:",gt)))}nu({gla:jt.squareFeet||ke.squareFeet,beds:jt.bedrooms||ke.bedrooms,baths:jt.bathrooms||ke.bathrooms,yearBuilt:jt.yearBuilt||ke.yearBuilt,lotSize:jt.lotSize||ke.lotSize,basement:gD("basement",jt.basement||ke.foundation),garageSpaces:jt.garageSpaces||ke.garageSpaces});const Yt=[...ke.photos||[],...jt.photos||[]].filter((Bt,Jt,gt)=>Bt&&gt.indexOf(Bt)===Jt);Jl(Yt),Yt.length===0?console.warn("[Wizard] Subject photos came back EMPTY for",X?.fullAddress||X?.streetAddress,"— gallery will fall back to empty state. Public Record photos:",ke.photos?.length||0,"/ MLS photos:",jt.photos?.length||0):console.log(`[Wizard] Subject photos loaded: ${Yt.length} unique photo(s)`),b&&O&&Yt.length>0&&fetch(`/api/orders/${b}/subject-photos`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({photoUrls:Yt,source:"PropMix"})}).catch(Bt=>console.warn("[Wizard] Failed to persist subject photos:",Bt));const ha=zj(xe)??zj(C?.order?.propertyData),Rt=!Ao.isAnalyzing&&(!!Ao.condition||!!Ao.qual
53ity);if(ha)Rt||Gi({isAnalyzing:!1,condition:ha.condition,quality:ha.quality});else if(!Ea&&Yt.length>0&&!Rt){li.current&&li.current.abort();const Bt=new AbortController;li.current=Bt,Gi({isAnalyzing:!0}),(async()=>{try{const Jt=jt?.listingId||jt?.mlsNumber,gt=await fetch("/api/ai/analyze-property-photos",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({photoUrls:Yt.slice(0,4),propertyAddress:X.fullAddress,propertyType:ke.propertyType||jt.propertyType,mlsNumber:Jt||void 0}),signal:Bt.signal});if(li.current!==Bt)return;if(!gt.ok){console.warn("[AI Photo Analysis] HTTP error:",gt.status),Gi({isAnalyzing:!1});return}const Ra=await gt.json();if(li.current!==Bt)return;if(Ra.success&&Ra.data){Gi({isAnalyzing:!1,condition:Ra.data.condition,quality:Ra.data.quality}),console.log("[AI Photo Analysis] Subject property ratings:",Ra.data);const fa=jO(Ra.data);J(fa),ye(Is=>TO(Is,Ra.data,fa))}else Gi({isAnalyzing:!1})}catch(Jt){if(Jt?.name==="AbortError")return;console.warn("[AI Photo Analysis] Failed to analyze subject photos:",Jt),li.current===Bt&&Gi({isAnalyzing:!1})}finally{li.current===Bt&&(li.current=null)}})()}},Ae=()=>{fe(d0()),ye(ux),He([]),ge("Owner"),Xt(!1),xc(null),Hc(!1),a(0),localStorage.removeItem("wizardStep"),localStorage.removeItem("propertyLoaded")};o.useEffect(()=>{b!==Re&&(ne(null),Me.current=null,lt.current=null,Tt.current=null,je.current=null)},[b,Re]),o.useEffect(()=>{if(!C?.order)return;const P=C.order,X=C.progress||[],xe=Ow(F,U),Ye=(oe==="failed"||oe==="done")&&_.length>0,ke=bq(P.id,xe,X)+(Ye?`|omitted-fetch-${oe}`:""),jt=jq(U,D&&Z);if(Tt.current===ke){Tt.current=null,console.log("[Wizard] Skipping redundant order reload after navigation");return}if(Tt.current=null,lt.current!==ke&&C?.order)try{console.log("[Wizard] Loading local order data:",P,"Progress entries:",X.length);const Et=Vt=>({value:Vt,source:"Echo",isEdited:!1,alternatives:{echo:Vt}}),ka=P.subjectAddress?Mx({street:P.subjectAddress,city:P.city,state:P.state,zip:P.zipCode},{emptyFallback:""}):"";let Yt={...d0(),subjectAddress:Et(ka),loanNumber:Et(P.loanNumber||""),client:Et(P.clientName||""),lender:Et(""),borrower:Et(P.borrowerName||""),form:Et(""),purpose:Et(P.appraisalPurpose||""),owner:Et("")},ha=ux;const Rt={};X.forEach(Vt=>{Vt.stepKey&&Vt.stepData&&(Rt[Vt.stepKey]=Vt.stepData)});const Bt=(Vt,Ut)=>Vt==null?Ut:typeof Vt!="object"?{...Ut,value:Vt}:{value:Vt.value??Ut.value,source:Vt.source??Ut.source,isEdited:Vt.isEdited??Ut.isEdited,alternatives:Vt.alternatives??Ut.alternatives??{}},Jt=(Vt,Ut)=>{if(!Vt)return Ut;const _a={...Ut};return Object.keys(Ut).forEach(Ss=>{const fr=Vt[Ss],an=Ut[Ss];_a[Ss]=Bt(fr,an)}),Object.keys(Vt).forEach(Ss=>{!(Ss in _a)&&Vt[Ss]&&typeof Vt[Ss]=="object"&&"value"in Vt[Ss]&&(_a[Ss]=Bt(Vt[Ss],{value:"",source:"Derived",isEdited:!1,alternatives:{}}))}),_a},gt=(Vt,Ut)=>{if(!Vt)return Ut;const _a={...Ut};return Object.keys(Ut).forEach(Ss=>{const fr=Vt[Ss],an=Ut[Ss];_a[Ss]=Bt(fr,an)}),Object.keys(Vt).forEach(Ss=>{!(Ss in _a)&&Vt[Ss]&&typeof Vt[Ss]=="object"&&"value"in Vt[Ss]&&(_a[Ss]=Bt(Vt[Ss],{value:"",source:"Derived",isEdited:!1,alternatives:{}}))}),_a};if(Rt.order_snapshot?.orderData&&(Yt=Jt(Rt.order_snapshot.orderData,Yt),console.log("[Wizard] Restored orderData from progress")),!Yt.assignmentType?.value&&P.appraisalPurpose){const Vt=B$(P.appraisalPurpose);Vt&&(Yt.assignmentType={value:Vt,source:"Echo",isEdited:!1,alternatives:{echo:Vt}},Vt==="Other"&&!Yt.assignmentTypeOtherDescription?.value&&(Yt.assignmentTypeOtherDescription=Et(P.appraisalPurpose)),console.log("[Wizard] Derived assignmentType from appraisalPurpose:",P.appraisalPurpose,"→",Vt))}const Ra=C?.participants;if(Ra&&Array.isArray(Ra)){const Vt=Ra.find(Ut=>Ut.roleName==="appraiser");Vt?.userName&&(Yt.appraiser={value:Vt.userName,source:"Echo",isEdited:!1,alternatives:{echo:Vt.userName}},console.log("[Wizard] Overlaid appraiser from participant:",Vt.userName))}const fa=Rt.subject_site||Rt.subject_property;if(fa?.subjectSiteOverrideLog&&Array.isArray(fa.subjectSiteOverrideLog)&&ce(fa.subjectSiteOverrideLog),fa?.subjectSiteLocalFields&&t
53ypeof fa.subjectSiteLocalFields=="object"&&We(fa.subjectSiteLocalFields),fa?.propertyData&&(ha=gt(fa.propertyData,ux),console.log("[Wizard] Restored propertyData from progress")),P.propertyData?.propMixData&&typeof P.propertyData.propMixData=="object"){const Vt=P.propertyData.propMixData,Ut={propertyDetails:Vt.propertyDetails||{},listingDetails:Vt.listingDetails||{}};ha=mv(Ut,ha),Sp(Ut),Object.values(Rt).some(fr=>Array.isArray(fr?.historyData))||He(MO(Ut,Vt.allListingSheets));const Ss=Ut.listingDetails;!Ss.listingId&&!Ss.listPrice&&!Ss.status&&Hc(!0),console.log("[Wizard] Restored provider snapshot for report data")}!Rt.subject_site&&Rt.zoning_history?.propertyData&&(console.log("[Wizard] Legacy zoning_history.propertyData found, merging"),ha=gt(Rt.zoning_history.propertyData,ha));const Is=Yt.subjectAddress?.value||P.subjectAddress||"";if(Rt.zoning_api_data?.zoningData&&Is){const Vt=Rt.zoning_api_data?.address||"";(Vt===Is||Vt&&Is&&Vt.toLowerCase().includes(Is.toLowerCase().split(",")[0]))&&(Td(Rt.zoning_api_data.zoningData),js(Is),console.log("[Wizard] Restored zoning API data from progress for:",Is))}if(Rt.zoning_screenshot?.screenshot&&Is){const Vt=Rt.zoning_screenshot?.address||"",Ut=Vt===Is||Vt&&Is&&Vt.toLowerCase().includes(Is.toLowerCase().split(",")[0]),_a=Rt.zoning_screenshot?.cacheVersion===Zj;Ut&&(Ap(Rt.zoning_screenshot.screenshot),$u.current=!_a,console.log(_a?"[Wizard] Restored zoning screenshot from progress":"[Wizard] Restored stale zoning screenshot; upgrading zoom in background"))}Rt.property_lab?.propertyData&&(ha=gt(Rt.property_lab.propertyData,ha),console.log("[Wizard] Merged propertyData from property_lab step")),P.county&&!ha.county?.value&&(ha={...ha,county:{value:P.county,source:"Echo",isEdited:!1,alternatives:{echo:P.county}}},console.log("[Wizard] Seeded county from order row:",P.county));const cs=["review","addendum","rights_adjust","calculator","lease_summary","sales_grid","property_lab","comp_intent","subject_site","zoning_history","subject_property","order_snapshot"],br=Vt=>{for(const Ut of cs)if(Rt[Ut]?.[Vt]!==void 0)return Rt[Ut];return null},zr=[P.subjectAddress,P.city,P.state,P.zipCode].filter(Boolean).join(", "),_s=(Vt,Ut)=>{const _a=Math.abs(Vt.lat-Ut.lat),Ss=Math.abs(Vt.lng-Ut.lng);return _a>.02||Ss>.02},et=(Vt,Ut)=>{const _a=Math.abs(Vt.lat-Ut.lat),Ss=Math.abs(Vt.lng-Ut.lng);return Math.sqrt((_a*111)**2+(Ss*85)**2)},pa=cX(P,br),Gt=pa?.coords??null,hs=pa?.source??"none";pa&&(console.log("[Wizard] Initially using",hs,"coordinates:",pa.coords),qs(pa.coords),pa.shouldPersist&&(!P.latitude||!P.longitude)&&Qj(P.id,pa.coords,hs)),zr&&Gt?(console.log("[Wizard] Validating stored coordinates by geocoding:",zr),fetch("/api/mapbox/geocode",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({address:zr,types:"address"})}).then(Vt=>Vt.json()).then(Vt=>{if(Vt.success&&Vt.result){const{lat:Ut,lng:_a,confidence:Ss,place:fr,formattedAddress:an}=Vt.result,Sl={lat:Ut,lng:_a},Dd=_s(Gt,Sl);if(!Dd){console.log("[Wizard] Stored coordinates match geocoded (within ~2km), keeping stored");return}const Un=et(Gt,Sl),Ui=Ss==="exact"||Ss==="high"||typeof Ss=="number"&&Ss>=.8,uo=Un>5,sn=P.city?.toLowerCase().trim(),rn=fr?.toLowerCase().trim(),Co=sn&&rn&&(rn.includes(sn)||sn.includes(rn));if(Dd&&(Ui||uo||Co)){const po=Ui?"high confidence":uo?`large mismatch (${Un.toFixed(1)}km)`:`city match (${rn})`;console.log(`[Wizard] Accepting geocode correction (${po}):`,Gt,"→",Sl),qs(Sl),Qj(P.id,Sl,"geocode-corrected")}else console.log("[Wizard] Mismatch detected but no acceptance criteria met:",{confidence:Ss,distanceKm:Un.toFixed(1),expectedCity:sn,geocodedPlace:rn})}else console.log("[Wizard] Geocoding returned no results, keeping stored coordinates")}).catch(Vt=>{console.error("[Wizard] Geocoding failed, keeping stored coordinates:",Vt)})):zr&&!Gt&&(console.log("[Wizard] No coordinates found, geocoding:",zr),fetch("/api/mapbox/geocode",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({address:zr,types:"address"})}).then(Vt=>Vt.json()).then(Vt=>{if(Vt.success&&Vt.result){const{lat:Ut,lng:_a}=Vt.result;console.log("[Wizard] Geocoded coordinates:",Ut,_a),qs({lat:Ut,lng:_a}),Qj(P.id,{lat:Ut,lng:_a},"geocoded")}else console.warn("[Wizard] Geocoding returned no results for:",zr)}).catch(Vt=>console.error("[Wizard] Geocoding failed:",Vt)));const qr=br("subjectDetails"),ys=qr?.subjectDetails?{...qr.subjectDetails}:{};qr?.subjectDetails&&console.log("[Wizard] Restored subjectDetails from progress");const yr=P.propertyData;yr&&(yr.beds!=null&&(ys.beds=yr.beds),yr.baths!=null&&(ys.baths=yr.baths),yr.gla!=null&&(ys.gla=yr.gla),yr.guestCapacity!=null&&(ys.guestCapacity=yr.guestCapacity),yr.propertyType&&(ys.propertyType=yr.propertyType)),Object.keys(ys).length>0&&nu(ys);const Yr=br("subjectPhotos"),Ge=Yr?.subjectPhotos?.filter(Vt=>Vt&&Vt.trim()!=="")||[],bt=(()=>{const Vt=P.propertyData?.propMixData;if(!Vt||typeof Vt!="object")return[];const Ut=Vt.propertyDetails||{},_a=Vt.listingDetails||{};return[...Array.isArray(Ut.photos)?Ut.photos:[],...Array.isArray(_a.photos)?_a.photos:[]].filter((Ss,fr,an)=>
53typeof Ss=="string"&&Ss.trim()!==""&&an.indexOf(Ss)===fr)})();(async()=>{let Vt=[];try{const Ut=await fetch(`/api/orders/${P.id}/subject-photos`,{credentials:"include"});if(Ut.ok){const _a=await Ut.json();_a?.success&&Array.isArray(_a.photos)&&(Vt=_a.photos.map(Ss=>Ss.originalUrl).filter(Ss=>Ss&&Ss.trim()!==""))}}catch(Ut){console.warn("[Wizard] Failed to fetch subject_photos table:",Ut)}Vt.length>0?(Jl(Vt),console.log(`[Wizard] Restored subjectPhotos from subject_photos table: ${Vt.length}`)):Ge.length>0?(Jl(Ge),console.log("[Wizard] Restored subjectPhotos from progress"),fetch(`/api/orders/${P.id}/subject-photos`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({photoUrls:Ge,source:"PropMix"})}).catch(Ut=>console.warn("[Wizard] subject_photos backfill failed:",Ut))):bt.length>0&&(Jl(bt),console.log("[Wizard] Restored subjectPhotos from provider snapshot:",bt.length))})();const Za=zj(P.propertyData);if(Za)Gi({isAnalyzing:!1,condition:Za.condition,quality:Za.quality});else if(!Ea&&!VM(P.propertyData)&&(Yr?.subjectPhotos?.length||bt.length)>0){const Vt=Ge.length>0?Ge:bt;li.current&&li.current.abort();const Ut=new AbortController;li.current=Ut,Gi({isAnalyzing:!0}),fetch("/api/ai/analyze-property-photos",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({photoUrls:Vt.slice(0,4),propertyAddress:Mx({street:P.subjectAddress,city:P.city,state:P.state,zip:P.zipCode},{emptyFallback:""})}),signal:Ut.signal}).then(_a=>_a.ok?_a.json():(console.warn("[AI Photo Analysis] HTTP error:",_a.status),null)).then(_a=>{if(li.current===Ut)if(_a&&_a.success&&_a.data){Gi({isAnalyzing:!1,condition:_a.data.condition,qual
53ity:_a.data.quality});const Ss=jO(_a.data);J(Ss),ye(fr=>TO(fr,_a.data,Ss)),console.log("[Wizard] Restored AI ratings from cache:",_a.data.condition?.rating,_a.data.quality?.rating)}else Gi({isAnalyzing:!1})}).catch(_a=>{_a?.name!=="AbortError"&&li.current===Ut&&Gi({isAnalyzing:!1})}).finally(()=>{li.current===Ut&&(li.current=null)})}const ra=parseFloat(P.latitude||"0"),ta=parseFloat(P.longitude||"0");if(ra&&ta){const Vt=P.id||"subject",Ut=`${Vt}:${ra}:${ta}`;_o.current.has(Ut)||(_o.current.add(Ut),fetch(`/api/els/${Vt}?lat=${ra}&lng=${ta}`).then(_a=>_a.json()).then(_a=>{if(_a.success){const Ss=[];if(_a.factorSubscores){const fr=_a.factorSubscores,an=_a.rawSignals||{};fr.flood!==void 0&&Ss.push({name:"Flood Zone",status:fr.flood>=80||fr.flood>=50?"OK":"−",detail:an.femaFloodZone||"",subscore:fr.flood}),fr.highway!==void 0&&Ss.push({name:"Highway Proximity",status:fr.highway>=80||fr.highway>=50?"OK":"−",detail:`${Math.round(an.distanceToHighway||0)} ft`,subscore:fr.highway}),fr.rail!==void 0&&Ss.push({name:"Railroad Proximity",status:fr.rail>=80||fr.rail>=50?"OK":"−",detail:`${Math.round(an.distanceToRail||0)} ft`,subscore:fr.rail}),fr.water!==void 0&&Ss.push({name:"Water Feature",status:fr.water>=60?"+":"OK",detail:`${Math.round(an.distanceToWater||0)} ft`,subscore:fr.water}),fr.park!==void 0&&Ss.push({name:"Park/Green Space",status:fr.park>=60?"+":"OK",detail:`${Math.round(an.distanceToPark||0)} ft`,subscore:fr.park})}Nn({score:_a.score,tier:_a.tier,factors:Ss}),console.log(`[Wizard] Restored ELS score: ${_a.score} (${_a.tier})`)}}).catch(_a=>console.warn("[ELS] Failed to restore score:",_a)))}if(!jt){const Vt=br("occupancy");Vt?.occupancy&&(ge(Vt.occupancy),console.log("[Wizard] Restored occupancy:",Vt.occupancy));const Ut=br("historyData");Ut?.historyData&&Ut.historyData.length>0&&(He(Ut.historyData),console.log("[Wizard] Restored historyData from progress"));const _a=br("compLabState");if(_a?.compLabState){re(_a.compLabState),console.log("[Wizard] Restored compLabState from progress");const pi=_a.compLabState.results;if(pi&&pi.length>0){const il=pi.slice(0,6).map(ed=>ed.photoUrl).filter(ed=>!!ed).map(ed=>r$(ed));il.length>0&&n$(il).catch(()=>{})}}const Ss=br(pI),fr=h?.id?Y0(h.id):null,an=fr?Rt[fr]:null,{snapshot:Sl,source:Dd}=xJ({progress:[...Ss?[{stepKey:pI,stepData:Ss}]:[],...fr&&an?[{stepKey:fr,stepData:an}]:[]],userId:h?.id??null});let Un=Sl;if(Un&&h?.id){const Oi=`cachedLabStateCache__user_${h.id}`,pi=Rt[Oi];if(pi){const il={...Un};Array.isArray(pi.allCachedSales)&&(il.allCachedSales=pi.allCachedSales),Array.isArray(pi.elsCache)&&(il.elsCache=pi.elsCache),Array.isArray(pi.compAiCache)&&(il.compAiCache=pi.compAiCache),Un=il}}if(Un){const Oi=C?.boundaryGeometries,pi=Array.isArray(Oi)?Oi.filter(il=>typeof il?.boundaryId=="string"&&il.polygon!=null):[];pi.length>0&&Array.isArray(Un.appliedBoundaries)&&(Un={...Un,appliedBoundaries:GS(Un.appliedBoundaries,pi)})}if(Un){if(Gn.current&&Array.isArray(Gn.current.appliedBoundaries)){const Oi=Gn.current.appliedBoundaries.filter(pi=>pi?.id&&pi?.polygon).map(pi=>({boundaryId:pi.id,polygon:pi.polygon}));Oi.length>0&&Array.isArray(Un.appliedBoundaries)&&(Un={...Un,appliedBoundaries:GS(Un.appliedBoundaries,Oi)})}Gn.current=Un,console.log(`[Wizard] Restored cachedLabState from progress (source: ${Dd})`),wd(Un)}const Ui=br("marketLabState");if(Ui?.marketLabState){_e(Ui.marketLabState);const Oi=Bz(Rt,Iw(Ui.marketLabState));Oi&&(na(Oi),console.log("[Wizard] Restored eval chart images from progress")),console.log("[Wizard] Restored marketLabState from progress")}const uo=br("compIntentState");uo?.compIntentState&&(xa(uo.compIntentState),console.log("[Wizard] Restored compIntentState from progress:",uo.compIntentState.priorities));const sn=br("afterRepairedSubject");sn?.afterRepairedSubject&&Object.keys(sn.afterRepairedSubject).length>0&&(Tg(sn.afterRepairedSubject),console.log("[Wizard] Restored afterRepairedSubject from progress:",Object.keys(sn.afterRepairedSubject))),sn?.renovationState&&(ni(sn.renovationState),console.log("[Wizard] Restored renovationState from progress"));const rn=br("compScenarioTags");rn?.compScenarioTags&&Object.keys(rn.compScenarioTags).length>
530&&(ff(rn.compScenarioTags),console.log("[Wizard] Restored compScenarioTags from progress:",Object.keys(rn.compScenarioTags).length,"comps tagged"));const Co=br("gridAdjustments");Co?.gridAdjustments&&Object.keys(Co.gridAdjustments).length>0&&(Tn(Co.gridAdjustments),console.log("[Wizard] Restored gridAdjustments from progress:",Object.keys(Co.gridAdjustments).length,"comps with adjustments"));const ji=br("csvSubjectValues");ji?.csvSubjectValues&&Object.keys(ji.csvSubjectValues).length>0&&(Ka(ji.csvSubjectValues),console.log("[Wizard] Restored csvSubjectValues from progress:",Object.keys(ji.csvSubjectValues).length,"fields"));const po=br("bridgeValues");if(po?.bridgeValues){const Oi=po.bridgeValues;gf({asIs:typeof Oi.asIs=="string"?Oi.asIs:"",afterRepaired:typeof Oi.afterRepaired=="string"?Oi.afterRepaired:"",commentary:typeof Oi.commentary=="string"?Oi.commentary:""}),console.log("[Wizard] Restored bridgeValues from progress")}const Ac=br("cleanedComps"),Qu=[..._a?.compLabState?.cleanedComps||[],...Ac?.cleanedComps||[]],yu=_a?.compLabState?.selectedUsed||[];if(yu.length>0){const Oi=nj(yu,Qu,Ir&&!Ea);Ze(Oi),console.log("[Wizard] Hydrated cleanedComps from selectedUsed:",Oi.length)}else if(_a?.compLabState?.results&&_a.compLabState.results.length>0&&Qu.length>0){const Oi=new Set(Qu.flatMap(ed=>Fv(ed))),pi=_a.compLabState.results.filter(ed=>Fv(ed).some(Sm=>Oi.has(Sm))),il=nj(pi,Qu,Ir&&!Ea);il.length>0?(Ze(il),console.log("[Wizard] Hydrated cleanedComps from results:",il.length)):(Ze(Ac?.cleanedComps||_a.compLabState.cleanedComps||[]),console.log("[Wizard] No matching comparable snapshots for cleanedComps"))}else Qu.length>0?(Ze(Ac?.cleanedComps||_a.compLabState.cleanedComps||[]),console.log("[Wizard] Restored cleanedComps without source snapshots:",Qu.length)):console.log("[Wizard] No cleanedComps found in progress");const Wg=br("leaseholdState");Wg?.leaseholdState&&(Mi(Wg.leaseholdState),console.log("[Wizard] Restored leaseholdState from progress"));const vb=br("selectedAgency");vb?.selectedAgency&&(to(vb.selectedAgency),console.log("[Wizard] Restored selectedAgency:",vb.selectedAgency))}fe(Yt),ye(XS(ha)),ne(P.id);const Mt={},ms=Yt.assignmentType?.value,cr=ms==="Purchase Transaction"||ms==="Purchase",Cn=ms==="Refinance Transaction"||ms==="Refinance";Mt["subject.assignmentPurchase"]=cr?!0:null,Mt["subject.assignmentRefinance"]=Cn?!0:null,Mt["subject.assignmentOther"]=!cr&&!Cn&&ms?!0:null;const Ai=Yt.offeredForSale?.value;Mt["subject.offeredForSaleYes"]=Ai===!0?!0:null,Mt["subject.offeredForSaleNo"]=Ai===!1?!0:null,Mt["subject.propertyRightsFeeSimple"]=!0,Mt["subject.propertyRightsLeasehold"]=null,Mt["subject.propertyRightsOther"]=null;const Rn=ha.censusTract?.value;Rn&&(Mt["subject.censusTract"]=String(Rn));const hn=ms==="Purchase Transaction"||ms==="Purchase",Ml=ms==="Refinance Transaction"||ms==="Refinance"||!hn&&!!ms;Mt["contract.isPurchase"]=hn?!0:null,Mt["contract.isRefinance"]=Ml?!0:null,Ml&&(Mt["contract.contractPrice"]=null,Mt["contract.contractDate"]=null,Mt["contract.sellerName"]=null,Mt["contract.isSellerOwner"]=null,Mt["contract.sellerOwnerDataSource"]=null,Mt["contract.didAnalyzeContract"]=null,Mt["contract.didNotAnalyzeContract"]=!0,Mt["contract.contractAnalysisExplanation"]="Not applicable — refinance transaction");const bu=Rt.property_lab_locks?.marketLock;!Jd.current&&Rt.property_lab_locks&&(Jd.current=!0,bu?.locked===!0&&fp(!0),Rt.property_lab_locks?.submarketLock?.locked===!0&&$m(!0),Cg(Rt.property_lab_locks));const Kn=bu?.stats;if(Kn){const Vt=Kn.locationType;Vt&&(Mt["neighborhood.locationUrban"]=Vt==="Urban"?!0:null,Mt["neighborhood.locationSuburban"]=Vt==="Suburban"?!0:null,Mt["neighborhood.locationRural"]=Vt==="Rural"?!0:null);const Ut=Kn.builtUp;Ut&&(Mt["neighborhood.builtUpOver75"]=Ut==="Over75"?!0:null,Mt["neighborhood.builtUp25to75"]=Ut==="25to75"?!0:null,Mt["neighborhood.builtUpUnder25"]=Ut==="Under25"?!0:null);const _a=Kn.growth;_a&&(Mt["neighborhood.growthRapid"]=_a==="Rapid"?!0:null,Mt["neighborhood.growthStable"]=_a==="Stable"?!0:null,Mt["neighborhood.growthSlow"]=_a==="Slow"?!0:null);const Ss=Kn.propertyValueTrend;Ss&&(Mt["neighborhood.propertyValuesIncreasing"]=Ss==="Increasing"?!0:null,Mt["neighborhood.propertyValuesStable"]=Ss==="Stable"?!0:null,Mt["neighborhood.propertyValuesDeclining"]=Ss==="Declining"?!0:null);const fr=Kn.demandSupply;fr&&(Mt["neighborhood.demandSupplyShortage"]=fr==="Shortage"?!0:null,Mt["neighborhood.demandSupplyInBalance"]=fr==="InBalance"?!0:null,Mt["neighborhood.demandSupplyOverSupply"]=fr==="OverSupply"?!0:null);const an=Kn.marketingTime;an&&(Mt["neighborhood.marketingTimeUnder3"]=an==="Under3"||an==="Under3Months"?!0:null,Mt["neighborhood.marketingTime3to6"]=an==="3to6"||an==="3to6Months"?!0:null,Mt["neighborhood.marketingTimeOver6"]=an==="Over6"||an==="Over6Months"?!0:null);const Sl=new Date().getFullYear(),Dd=Kn.priceRange?.low||0,Un=Kn.priceRange?.high||0,Ui=Kn.priceRange?.predominant||0,uo=Kn.ageRange?.high?Sl-Kn.ageRange.high:0,sn=Kn.ageRange?.low?Sl-Kn.ageRange.low:0,rn=Kn.ageRange?.predominant?Sl-Kn.ageRange.predominant:0;Dd&&(Mt["neighborhood.priceLow"]=String(Math.round(Dd/1e3))),Un&&(Mt["neighborhood.priceHigh"]=String(Math.round(Un/1e3))),Ui&&(Mt["neighborhood.pricePredominant"]=String(Math.round(Ui/1e3))),uo&&(Mt["neighborhood.ageLow"]=String(uo)),sn&&(Mt["neighborhood.ageHigh"]=String(sn)),rn&&(Mt["neighborhood.agePredominant"]=String(rn)),Kn.landUse&&(Mt["neighborhood.landUseOneUnit"]=String(Kn.landUse.oneUnit||0),Mt["neighborhood.landUse2to4"]=String(Kn.landUse.twoToFour||0),Mt["neighborhood.landUseMultiFamily"]=String(Kn.landUse.multiFamily||0),Mt["neighborhood.landUseCommercial"]=String(Kn.landUse.commercial||0),Mt["neighborhood.landUseOther"]=String(Kn.landUse.other||0)),console.log("[Wizard] Populated neighborhood from locked market stats:",Object.keys(Mt).filter(po=>po.startsWith("neighborhood.")).length,"fields");const Co=an==="Under3"?"Under3Months":an==="3to6"?"3to6Months":an==="Over6"?"Over6Months":an||"3to6Months",ji=Rt.property_lab_locks?.neighborhoodInfo;ji&&(ji.boundaries&&(Mt["neighborhood.boundaries"]=ji.boundaries),ji.description&&(Mt["neighborhood.description"]=ji.description),ji.marketConditions&&(Mt["neighborhood.marketConditions"]=ji.marketConditions),(ji.boundaries||ji.description)&&tt(!0),console.log("[Wizard] Populated neighborhood text fields from locked neighborhoodInfo")),_e(po=>({...po,neighborhoodGrid:{location:Vt||po.neighborhoodGrid?.location||"Suburban",builtUp:Ut||po.neighborhoodGrid?.builtUp||"Over75",growth:_a||po.neighborhoodGrid?.growth||"Stable",propertyValues:Ss||po.neighborhoodGrid?.propertyValues||"Stable",demandSupply:fr||po.neighborhoodGrid?.demandSupply||"InBalance",marketingTime:Co||po.neighborhoodGrid?.marketingTime||"3to6Months",priceLow:Dd,priceHigh:Un,pricePredominant:Ui,ageLow:uo,ageHigh:sn,agePredominant:rn,landUseOneUnit:Kn.landUse?.oneUnit||0,landUseTwoToFour:Kn.landUse?.twoToFour||0,landUseMultiFamily:Kn.landUse?.multiFamily||0,landUseCommercial:Kn.landUse?.commercial||0,landUseOther:Kn.landUse?.other||0,neighborhoodBoundaries:ji?.boundaries||po.neighborhoodGrid?.neighborhoodBoundaries||"",neighborhoodDescription:ji?.description||po.neighborhoodGrid?.neighborhoodDescription||"",marketConditions:ji?.marketConditions||po.neighborhoodGrid?.marketConditions||""},...!po.marketStats&&bu.salesData?.length?{marketStats:OO(bu)}:{}}))}else{const Vt=Rt.property_lab_locks?.neighborhoodInfo;Vt&&(Vt.boundaries&&(Mt["neighborhood.boundaries"]=Vt.boundaries),Vt.de
53scription&&(Mt["neighborhood.description"]=Vt.description),Vt.marketConditions&&(Mt["neighborhood.marketConditions"]=Vt.marketConditions),(Vt.boundaries||Vt.description)&&tt(!0),console.log("[Wizard] Populated neighborhood text fields from locked neighborhoodInfo (no lockStats)"),_e(Ut=>({...Ut,neighborhoodGrid:{...Ut.neighborhoodGrid||{},neighborhoodBoundaries:Vt.boundaries||Ut.neighborhoodGrid?.neighborhoodBoundaries||"",neighborhoodDescription:Vt.description||Ut.neighborhoodGrid?.neighborhoodDescription||"",marketConditions:Vt.marketConditions||Ut.neighborhoodGrid?.marketConditions||""}})))}const oh=Rt.property_lab_locks?.submarketLock;oh?.salesData?.length&&_e(Vt=>({...Vt,...Vt.subMarketStats?{}:{subMarketStats:OO(oh)}}));const xy=bu?.propertyCards?.length?bu.propertyCards:bu?.salesData?.length?bu.salesData:void 0;if(xy?.length&&Kt.length===0){const Vt=xy.map((Ut,_a)=>({id:String(Ut.id??`lock-${_a}`),address:Ut.address||"",status:Ut.status||"CLSD",listPrice:Ut.listPrice??null,salePrice:Ut.price??Ut.salePrice??null,dom:Ut.dom??null,gla:Ut.sqft??Ut.gla??null,lotSqft:Ut.lotSqft??null,beds:Ut.beds??null,baths:Ut.baths??null,yearBuilt:Ut.yearBuilt??null,ppsf:Ut.pricePerSqft??(Ut.sqft>0&&Ut.price>0?Math.round(Ut.price/Ut.sqft):null),closeDate:Ut.saleDate??Ut.closeDate??null,listDate:Ut.listDate??null,latitude:Ut.coordinates?.lat??Ut.latitude??null,longitude:Ut.coordinates?.lng??Ut.longitude??null}));Sa(Vt),console.log("[Wizard] Restored",Vt.length,"market properties from locked",bu?.propertyCards?.length?"propertyCards":"salesData (legacy lock)")}const Hg=oh?.propertyCards?.length?oh.propertyCards:oh?.salesData?.length?oh.salesData:void 0;if(Hg?.length&&Qt.length===0){const Vt=Hg.map((Ut,_a)=>({id:String(Ut.id??`lock-${_a}`),address:Ut.address||"",status:Ut.status||"CLSD",listPrice:Ut.listPrice??null,salePrice:Ut.price??Ut.salePrice??null,dom:Ut.dom??null,gla:Ut.sqft??Ut.gla??null,lotSqft:Ut.lotSqft??null,beds:Ut.beds??null,baths:Ut.baths??null,yearBuilt:Ut.yearBuilt??null,ppsf:Ut.pricePerSqft??(Ut.sqft>0&&Ut.price>0?Math.round(Ut.price/Ut.sqft):null),closeDate:Ut.saleDate??Ut.closeDate??null,listDate:Ut.listDate??null,latitude:Ut.coordinates?.lat??Ut.latitude??null,longitude:Ut.coordinates?.lng??Ut.longitude??null}));ea(Vt),console.log("[Wizard] Restored",Vt.length,"submarket properties from locked propertyCards")}ir(Vt=>({...Vt,...Mt})),lt.current=ke;const lh=P.addOns||[];al(lh);const by=lh.includes("leasehold")||lh.includes("land_lease");if(dm(by),console.log("[Wizard] Set order addOns:",lh,"leasehold:",by),Qr(!1),P.subjectAddress){Xt(!0),P.state&&Yc(P.state),P.city&&su(P.city),P.zipCode&&Gc(P.zipCode);const Vt=pn.indexOf("order_snapshot"),Ut=T?0:Math.max(Vt,0),_a=new URLSearchParams(x).get("resumeStep"),Ss=_a&&pn.indexOf(_a)!==-1?_a:P.currentStep,fr=Ss?pn.indexOf(Ss):-1,an=fr>=Ut?fr:Ut;if(je.current!==P.id){console.log("[Wizard] Applying resume step",{orderId:P.id,savedStepKey:Ss,resumeStep:an,stepKeyMapLength:pn.length}),a(an);{const Ui=new Set;let uo=!1;if(Object.values(Rt).forEach(rn=>{Array.isArray(rn?.visitedStepKeys)&&(uo=!0,rn.visitedStepKeys.forEach(Co=>Ui.add(Co)))}),!uo)for(let rn=0;rn<=an;rn++){const Co=pn[rn];Co&&Ui.add(Co)}const sn=new Set;Ui.forEach(rn=>{const Co=pn.indexOf(rn);Co>=0&&sn.add(Co)}),sn.add(an),u.current=sn,p(sn)}je.current=P.id}else console.log("[Wizard] Skipping resume (already applied for this order)",{orderId:P.id,savedStepKey:Ss});const Sl=P.propertyData?.propMixData,Dd=!!Sl&&typeof Sl=="object"&&(Object.keys(Sl.propertyDetails||{}).length>0||Object.keys(Sl.listingDetails||{}).length>0),Un=`${P.id}:${P.subjectAddress||""}:${P.city||""}:${P.state||""}:${P.zipCode||""}`;if(P.subjectAddress&&!Dd&&Me.current!==Un){Me.current=Un;const Ui=new URLSearchParams({street:P.subjectAddress,city:P.city||"",state:P.state||"",zip:P.zipCode||""});(async()=>{try{const uo=await fetch(`/api/property?${Ui.toString()}`,{credentials:"include"}),sn=await uo.json().catch(()=>({}));if(!uo.ok||!sn.success){console.warn("[Wizard] Automatic provider load returned no data:",sn.error||uo.status);return}const rn={propertyDetails:sn.propertyDetails||{},listingDetails:sn.listingDetails||{},allListingSheets:sn.allListingSheets||[]},Co={fullAddress:ka,streetAddress:P.subjectAddress,city:P.city,state:P.state,zipCode:P.zipCode,lat:rn.propertyDetails.coordinates?.lat||(P.latitude?parseFloat(P.latitude):void 0),lng:rn.propertyDetails.coordinates?.lng||(P.longitude?parseFloat(P.longitude):void 0)};if(j.current!==P.id)return;await he(rn,Co),console.log("[Wizard] Automatic provider data loaded for existing order")}catch(uo){console.warn("[Wizard] Automatic provider load failed:",uo)}})()}}}catch(Et){console.error("[Wizard] Order hydration failed:",Et),m({title:"Error loading order",description:Et instanceof Error?Et.message:"Failed to load order data. Please try refreshing the page.",variant:"destructive"})}},[C,F,U,Re,Wi,D,oe,me]),o.useEffect(()=>{localStorage.removeItem("wizardStep"),localStorage.removeItem("propertyLoaded"),b||(a(0),fe(d0()),ye(ux),He([]),ge("Owner"),Xt(!1),ne(null),xc(null),Hc(!1),al([]));const P=localStorage.getItem("sourcePreference");P&&["system","prefer_mls_pr","prefer_echo"].includes(P)&&Oa(P)},[b]),o.useEffect(()=>{if(!b||!O)return;let P=!1;return AO(()=>JS(b),{isCancelled:()=>P}).then(X=>{P||!X.conclusive||Gm(X.inspection)}),()=>{P=!0}},[b,O]),o.useEffect(()=>{if(!ii?.payload)return;const P=ii.payload.mappedFields?.fields||ii.payload.rawData?.extractedFields;if(!P)return;const X={"roomCounts.bedrooms":"bedrooms","roomCounts.fullBaths":"fullBaths","roomCounts.halfBaths":"halfBaths","roomCounts.glaSqft":"gla","roomCounts.totalRooms":"totalRooms","roomCounts.stories":"stories","roomCounts.belowGradeArea":"basementArea","roomCounts.belowGradeFinis
53hed":"basementFinish","general.yearBuilt":"yearBuilt","general.effectiveAge":"effectiveAge","general.designStyle":"designStyle","foundation.type":"foundationWalls","exterior.walls":"exteriorWalls","exterior.roofSurface":"roofSurface","exterior.gutters":"guttersDownspouts","exterior.windowType":"windowType","heating.type":"heatingType","heating.fuel":"heatingFuel","cooling.type":"coolingType","interior.flooring":"interiorFloors","interior.walls":"interiorWalls","interior.trimFinish":"trimFinish","interior.bathFloor":"bathFloor","interior.bathWainscot":"bathWainscot","carStorage.garageType":"garageType","carStorage.garageCars":"garageCars","carStorage.drivewaySurface":"drivewaySurface","amenities.fireplaceCount":"fireplace","amenities.pool":"pool"};ye(xe=>{const Ye={...xe};for(const[ke,jt]of Object.entries(X)){const[Et,ka]=ke.split("."),Yt=P[Et];if(!Yt||!(ka in Yt))continue;const ha=Yt[ka],Rt=ha?.value??ha;if(Rt==null||Rt==="")continue;const Bt=Ye[jt];Bt&&typeof Bt=="object"&&"alternatives"in Bt&&(Ye[jt]={...Bt,alternatives:{...Bt.alternatives,inspection:String(Rt)}})}return Ye})},[ii]);const Ke=o.useMemo(()=>{const P=ii?.payload?.mappedFields?.fields||ii?.payload?.rawData?.extractedFields;if(!P?.site)return;const X=P.site,xe=jt=>{const Et=X[jt];if(!Et)return;const ka=typeof Et=="object"?Et.value??Et.text:Et;return ka!=null&&ka!==""?String(ka):void 0},Ye=xe("topography")??xe("Topography"),ke=xe("viewType")??xe("view")??xe("View");return Ye||ke?{topography:Ye,viewType:ke}:void 0},[ii]),ft=o.useMemo(()=>{const P={},X=Pe.viewType;X?.confirmed&&X?.value&&(P.view=X.value);const xe=Pe.viewFactor;return xe?.confirmed&&xe?.value&&new Set(["Beneficial","Neutral","Adverse"]).has(xe.value)&&(P.viewImpact=xe.value),Object.keys(P).length>0?P:void 0},[Pe]),mt=o.useRef(!1),Xe=o.useRef(!1);o.useEffect(()=>{if(!b||!O)return;mt.current=!1,Xe.current=!0,(async()=>{try{const X=await fetch(`/api/avm-state/${b}`);if(X.ok){const xe=await X.json();console.log("[Wizard] AVM state load response:",{success:xe.success,hasMarketLocked:"marketLocked"in xe,marketLockedValue:xe.marketLocked,hasSubMarketLocked:"subMarketLocked"in xe,subMarketLockedValue:xe.subMarketLocked}),xe.success&&("avmResults"in xe&&xe.avmResults!==void 0&&(Yn(xe.avmResults),console.log("[Wizard] Restored AVM results from database")),"verifiedSubject"in xe&&xe.verifiedSubject!==void 0&&(yd(xe.verifiedSubject),console.log("[Wizard] Restored verified subject from database")),"selectedAvmCompIds"in xe&&Array.isArray(xe.selectedAvmCompIds)&&xe.selectedAvmCompIds.length>0&&(Xi(xe.selectedAvmCompIds),console.log("[Wizard] Restored selected AVM comp IDs from database")),"marketLocked"in xe&&console.log("[Wizard] /api/avm-state returned marketLocked:",xe.marketLocked,"(ignored — StepPropertyLab is canonical)"),"subMarketLocked"in xe&&console.log("[Wizard] /api/avm-state returned subMarketLocked:",xe.subMarketLocked,"(ignored — StepPropertyLab is canonical)"),"subMarketPropertyIds"in xe&&Array.isArray(xe.subMarketPropertyIds)&&xe.subMarketPropertyIds.length>0&&(Rg(xe.subMarketPropertyIds),console.log("[Wizard] Restored AVM submarket property IDs from database:",xe.subMarketPropertyIds.length)))}}catch(X){console.error("[Wizard] Failed to load AVM state:",X)}finally{setTimeout(()=>{Xe.current=!1,mt.current=!0},100)}})()},[b,O]);const _t=o.useRef(null),oa=o.useRef(""),ls=o.useRef(!1),Ps=o.useRef({avmResults:null,verifiedSubject:null,selectedAvmCompIds:[],marketLocked:!1,subMarketLocked:!1,subMarketPropertyIds:[]});Ps.current={avmResults:In,verifiedSubject:Ri,selectedAvmCompIds:Qa,marketLocked:ki,subMarketLocked:Ol,subMarketPropertyIds:ml};const Er=o.useRef(null),mn=o.useCallback(P=>{Er.current=P},[]);o.useEffect(()=>{if(!b||!O)return;const P=()=>{try{Er.current?.()}catch(ke){console.error("[Wizard] Verify unload flush failed:",ke)}if(!ls.current)return;const X=Ps.current;if(!X.avmResults&&!X.verifiedSubject&&X.selectedAvmCompIds.length===0&&!X.marketLocked&&!X.subMarketLocked&&X.subMarketPropertyIds.length===0)return;const xe=JSON.stringify({assignmentId:b,...X});typeof navigator.sendBeacon=="function"&&navigator.sendBeacon("/api/avm-state/save",new Blob([xe],{type:"application/json"}))&&(ls.current=!1)};return window.addEventListener("pagehide",P),()=>window.removeEventListener("pagehide",P)},[b,O]),o.useEffect(()=>{if(!b||!O||Xe.current||!In&&!Ri&&Qa.length===0&&!ki&&!Ol&&ml.length===0)return;const P=JSON.stringify({avmResults:In?{rankedCompsCount:In.rankedComps?.length}:null,verifiedSubject:Ri??null,selectedAvmCompIds:Qa,marketLocked:ki,subMarketLocked:Ol,subMarketPropertyIds:ml});if(P!==oa.current)return oa.current=P,ls.current=!0,_t.current&&clearTimeout(_t.current),_t.current=setTimeout(async()=>{try{const X=new AbortController,xe=setTimeout(()=>X.abort(),3e4),Ye=fetch("/api/avm-state/save",{method:"POST",headers:{"Content-Type":"application/json"},signal:X.signal,body:JSON.stringify({assignmentId:b,avmResults:In,verifiedSubject:Ri,selectedAvmCompIds:Qa,marketLocked:ki,subMarketLocked:Ol,subMarketPropertyIds:ml})}).finally(()=>clearTimeout(xe));await Go(b,Ye),ls.current=!1,console.log("[Wizard] Saved AVM state to database")}catch(X){console.error("[Wizard] Failed to save AVM state:",X)}},1e3),()=>{_t.current&&(clearTimeout(_t.current),b&&O&&(In||Ri||Qa.length>0||ki||Ol||ml.length>0)&&fetch("/api/avm-state/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({assignmentId:b,avmResults:In,verifiedSubject:Ri,selectedAvmCompIds:Qa,marketLocked:ki,subMarketLocked:Ol,subMarketPropertyIds:ml})}).then(()=>{console.log("[Wizard] Flushed AVM state to database on unmount")}).catch(X=>{console.error("[Wizard] Failed to flush AVM state on unmount:",X)}))}},[b,O,In,Ri,Qa,ki,Ol,ml]);const vr=o.useCallback(async(P,X)=>{if(!(!b||!O)&&!(!ci&&Ea))try{await Lh(b,{saveProgress:{stepKey:P,stepData:X,isCompleted:!0}}),console.log("[Wizard] Saved progress for step:",P)}catch(xe){console.error("[Wizard] Failed to save progress:",xe)}},[b,O,ci,Ea]),tn=o.useRef(null),An=o.useRef(null),lo=o.useRef(null),Si=o.useRef(!1),Bo=o.useRef(null),nl=o.useRef(null),Ki=o.useRef({allCachedSalesSig:-1,elsCacheSig:-1,compAiCacheSig:-1}),rc=o.useRef(null),Ku=o.useRef(()=>{}),wd=o.useCallback(P=>{Ku.current(P)},[]),vc=h?.id?Y0(h.id):null,nc=h?.id?`cachedLabStateCache__user_${h.id}`:null;o.useEffect(()=>{Ki.current={allCachedSalesSig:-1,elsCacheSig:-1,compAiCacheSig:-1},rc.current=null,lo.current=null,Si.current=!1},[b,h?.id]);const _n=P=>{let X=2166136261;for(let xe=0;xe<P.length;xe++)X^=P.charCodeAt(xe),X=Math.imul(X,16777619)>>>0;return X>>>0},To=P=>{if(!P||P.length===0)return 0;let X="";for(const[xe,Ye]of P)X+=`${xe}|${Ye?.score??""}|${Ye?.tier??""}
53|${Ye?.isOverridden?1:0}|${Ye?.isPartial?1:0};`;return _n(X)},So=P=>{if(!P||P.length===0)return 0;let X="";for(const xe of P){const Ye=xe;X+=`${Ye?.id??""}|${Ye?.salePrice??Ye?.listPrice??""}|${Ye?.status??""};`}return _n(X)},wa=P=>{if(!P||P.length===0)return 0;let X="";for(const[xe,Ye]of P)X+=`${xe}|${Ye?.condition??""}|${Ye?.quality??""}|${Ye?.confidence??""}|${Ye?.btDesignStyle??""};`;return _n(X)},di=o.useCallback((P,X)=>{const xe=$j(P,X,new Date(0)),Ye=ke=>{if(ke===null||typeof ke!="object")return JSON.stringify(ke)??"null";if(Array.isArray(ke))return"["+ke.map(Ye).join(",")+"]";const jt=ke,Et=[];for(const ka of Object.keys(jt).sort())jt[ka]!==void 0&&Et.push(JSON.stringify(ka)+":"+Ye(jt[ka]));return"{"+Et.join(",")+"}"};return _n(Ye(xe.saveProgress.stepData.cachedLabState))},[]);Ku.current=P=>{try{const{allCachedSales:X,elsCache:xe,compAiCache:Ye,...ke}=P;h?.id&&(rc.current=di(ke,h.id)),Ki.current={allCachedSalesSig:So(X),elsCacheSig:To(xe),compAiCacheSig:wa(Ye)},console.log(`[Wizard] Seeded lab-save baselines from restored snapshot (pool=${X?.length??0}, els=${xe?.length??0}, ai=${Ye?.length??0})`)}catch(X){console.warn("[Wizard] Failed to seed lab-save baselines:",X)}};const us=o.useCallback((P,X)=>{if(!b||!vc||!h?.id)return;if(X){const ke=P.labState,jt=ke?ke.selectedComps:void 0,Et=Array.isArray(jt)?jt.map(ha=>({id:ha.id,snapshotId:ha.snapshotId,mlsNumber:ha.mlsNumber,gridFieldOverrides:ha.gridFieldOverrides})):[],ka=ke?{...P,labState:{...ke,properties:[],results:[],selectedComps:[],_cachedGridOverrides:Et}}:P,Yt=$j(ka,h.id);Lh(b,Yt,{bypass:!0,keepalive:!0}).catch(ha=>{console.warn("[Wizard] Failed to persist cachedLabState (keepalive):",ha)});return}const xe=di(P,h.id);if(xe===rc.current)return;rc.current=xe;const Ye=$j(P,h.id);Si.current=!0,Lh(b,Ye).then(()=>{Si.current=!1}).catch(ke=>{Si.current=!1,console.warn("[Wizard] Failed to persist cachedLabState (light):",ke)})}
53,[b,vc,h?.id,di]),ks=o.useCallback((P,X)=>{if(!b||!nc)return;let xe=P.allCachedSales;if(xe&&xe.length>0){const ha=new Set,Rt=[];for(const Bt of xe){const Jt=Bt.id;Jt&&ha.has(Jt)||(Jt&&ha.add(Jt),Rt.push(Bt))}xe=Rt}let Ye=P.elsCache,ke=P.compAiCache;const jt=P.keepIds,Et=3e3;if(((P.elsCache?.length??0)>Et||(P.compAiCache?.length??0)>Et)&&jt&&jt.size>0){const ha=jt,Rt=(Bt,Jt)=>{if(!Bt||Bt.length===0)return Bt;const gt=Bt.filter(([Ra])=>ha.has(Ra));return gt.length===0?(console.warn(`[Wizard] Skipping ${Jt} prune — no keys matched the pool id set (${Bt.length} entries kept)`),Bt):(gt.length!==Bt.length&&console.log(`[Wizard] Pruned ${Jt} on save: ${Bt.length} → ${gt.length} entries`),gt)};Ye=Rt(Ye,"elsCache"),ke=Rt(ke,"compAiCache")}const Yt={saveProgress:{stepKey:nc,stepData:{allCachedSales:xe,elsCache:Ye,compAiCache:ke,savedAt:new Date().toISOString()}}};Lh(b,Yt,X?{bypass:!0,keepalive:!0}:void 0).catch(ha=>{console.warn("[Wizard] Failed to persist cachedLabState (heavy):",ha)})},[b,nc]),On=o.useCallback(P=>{if(!b||!O||!vc)return;const X=P.labState,xe=P.currentShapes?.circles?.length??0,Ye=P.currentShapes?.polygons?.length??0,ke=P.appliedBoundaries?.length??0,jt=X?.selectedComps?.length??0;if(X?.searchPerformed!==!0&&xe===0&&Ye===0&&ke===0&&jt===0)return;const{allCachedSales:ka,elsCache:Yt,compAiCache:ha,...Rt}=P;An.current=Rt,lo.current=Rt,tn.current&&clearTimeout(tn.current),tn.current=setTimeout(()=>{const fa=An.current;An.current=null,tn.current=null,fa&&us(fa,!1)},2e3);const Bt=So(ka),Jt=To(Yt),gt=wa(ha);if((Bt!==Ki.current.allCachedSalesSig||Jt!==Ki.current.elsCacheSig||gt!==Ki.current.compAiCacheSig)&&nc){const fa=new Set,Is=br=>{const zr=br;for(const _s of[zr?.id,zr?.snapshotId,zr?.propertyId,zr?.mlsNumber,zr?.mlsData?.ListingId,zr?.mlsData?.MLSNumber,zr?.mlsData?.mlsNumber])_s&&fa.add(String(_s))},cs=P.labState?.properties;Array.isArray(cs)&&cs.forEach(Is),(ka??[]).forEach(Is),nl.current={allCachedSales:ka,elsCache:Yt,compAiCache:ha,keepIds:fa},Ki.current={allCachedSalesSig:Bt,elsCacheSig:Jt,compAiCacheSig:gt},Bo.current&&clearTimeout(Bo.current),Bo.current=setTimeout(()=>{const br=nl.current;nl.current=null,Bo.current=null,br&&ks(br,!1)},2e3)}},[b,O,vc,nc,us,ks]),ui=o.useCallback(()=>{tn.current&&(clearTimeout(tn.current),tn.current=setTimeout(()=>{const P=An.current;An.current=null,tn.current=null,P&&us(P,!1)},300)),Bo.current&&(clearTimeout(Bo.current),Bo.current=setTimeout(()=>{const P=nl.current;nl.current=null,Bo.current=null,P&&ks(P,!1)},300))},[us,ks]);o.useEffect(()=>{const P=xe=>{tn.current&&(clearTimeout(tn.current),tn.current=null);const Ye=An.current;An.current=null;const ke=Ye??(Si.current?lo.current:null);ke&&us(ke,xe),Bo.current&&(clearTimeout(Bo.current),Bo.current=null);const jt=nl.current;nl.current=null,jt&&ks(jt,xe)},X=()=>P(!0);return window.addEventListener("pagehide",X),window.addEventListener("beforeunload",X),()=>{window.removeEventListener("pagehide",X),window.removeEventListener("beforeunload",X),P(!1)}},[us,ks]);const Xc=o.useRef(null),[Nc,Pd]=o.useState(!1);o.useEffect(()=>{Pd(!1)},[b,h?.id]),o.useEffect(()=>{if(!b||!O||!h?.id)return;const P=`${b}::${h.id}`;if(Xc.current===P){Pd(!0);return}const X=ke=>Array.isArray(ke.appliedBoundaries)&&ke.appliedBoundaries.some(jt=>jt?.id&&!String(jt.id).startsWith("drawn-area-")&&jt?.type!=="radius"&&!jt?.polygon);if(Gn.current&&!X(Gn.current)){Xc.current=P,Pd(!0);return}let xe=!1,Ye=!1;return(async()=>{try{let ke=await DA(b).catch(()=>null);ke||(ke=fi.getQueryData(kx(b))??null,ke&&console.warn("[Wizard] Full order fetch failed — restoring per-user cachedLabState from the slim payload"));const jt=fa=>Array.isArray(fa?.degradedBranches)&&fa.degradedBranches.includes("progress"),Et=fa=>Array.isArray(fa?.degradedBranches)&&fa.degradedBranches.includes("boundaryGeometries");for(let fa=0;fa<2&&ke&&jt(ke)&&!xe;fa++){if(console.warn("[Wizard] Order payload degraded (progress branch timed out) — retrying deferred per-user restore"),await new Promise(cs=>setTimeout(cs,1e3*(fa+1))),xe)return;const Is=await kA(b).catch(()=>null);Is&&(ke=Is)}if(ke&&Et(ke)&&!xe){console.warn("[Wizard] Order payload degraded (boundaryGeometries branch timed out) — retrying to restore polygon");for(let fa=0;fa<2&&ke&&Et(ke)&&!xe;fa++){if(await new Promise(cs=>
53setTimeout(cs,500*(fa+1))),xe)return;const Is=await kA(b).catch(()=>null);Is&&(ke=Is,Et(Is)?fa===1&&console.warn("[Wizard] boundaryGeometries retry exhausted — proceeding without polygon (banner expected)"):console.log("[Wizard] boundaryGeometries retry succeeded on attempt",fa+1))}}if(!ke)return;let ka=Array.isArray(ke?.progress)?ke.progress:[];$.current.size>0&&(ka=ij(ka,Array.from($.current.values())));const Yt=Y0(h.id),ha=`cachedLabStateCache__user_${h.id}`,Rt=ka.find(fa=>fa?.stepKey===Yt),Bt=ka.find(fa=>fa?.stepKey===ha),Jt=fb(Rt);if(Aq(Jt,ae.current)){Ye=!0,console.log("[Wizard] Per-user cachedLabState omitted from slim payload — waiting for on-demand snapshot fetch");return}const gt=Rt?.stepData?.cachedLabState;if(xe)return;const Ra=fa=>{const Is=fa?.boundaryGeometries;return Array.isArray(Is)?Is.filter(cs=>typeof cs?.boundaryId=="string"&&cs.polygon!=null):[]};if(gt&&!Gn.current){const fa={...gt},Is=Bt?.stepData;Is&&(Array.isArray(Is.allCachedSales)&&(fa.allCachedSales=Is.allCachedSales),Array.isArray(Is.elsCache)&&(fa.elsCache=Is.elsCache),Array.isArray(Is.compAiCache)&&(fa.compAiCache=Is.compAiCache));const cs=Ra(ke);cs.length>0&&Array.isArray(fa.appliedBoundaries)&&(fa.appliedBoundaries=GS(fa.appliedBoundaries,cs)),Gn.current=fa,console.log("[Wizard] Restored cachedLabState from per-user step (deferred)"),wd(fa)}else if(Gn.current&&X(Gn.current)){const fa=Ra(ke);if(fa.length>0&&Array.isArray(Gn.current.appliedBoundaries)){const Is=Gn.current.appliedBoundaries.filter(zr=>zr?.id&&!String(zr.id).startsWith("drawn-area-")&&zr?.type!=="radius"&&!zr?.polygon).map(zr=>String(zr.name||zr.id)),cs=GS(Gn.current.appliedBoundaries,fa),br=cs.filter((zr,_s)=>!Gn.current.appliedBoundaries[_s]?.polygon&&zr?.polygon).length;Gn.current={...Gn.current,appliedBoundaries:cs},console.log(`[Wizard] Re-merged boundary polygons into existing cachedLabState (deferred): missing=[${Is.join(",")}], filled=${br}`)}}}catch(ke){console.warn("[Wizard] Per-user cachedLabState restore failed:",ke)}finally{!xe&&!Ye&&(Xc.current=P,Pd(!0))}})(),()=>{xe=!0}},[b,O,h?.id,oe,F,z]);const Dr=Nc||!O||f&&!v,[co,Od]=o.useState(null),kl=o.useRef(null);o.useEffect(()=>{if(!b||!h?.id)return;const P=`cachedLabStateCache__user_${h.id}`;if(z.has(P))return;const X=`${b}::${h.id}`;if(kl.current===X)return;const xe=fi.getQueryData(ZS(b))??fi.getQueryData(kx(b)),Ye=Array.isArray(xe?.progress)?xe.progress:[],Et=($.current.size>0?ij(Ye,Array.from($.current.values())):Ye).find(Yt=>Yt?.stepKey===P)?.stepData,ka=Array.isArray(Et?.elsCache)||Array.isArray(Et?.compAiCache)||Array.isArray(Et?.allCachedSales);Et&&ka?(Od({elsCache:Array.isArray(Et.elsCache)?Et.elsCache:void 0,compAiCache:Array.isArray(Et.compAiCache)?Et.compAiCache:void 0,allCachedSales:Array.isArray(Et.allCachedSales)?Et.allCachedSales:[]}),console.log("[Wizard] Delivering late heavy cache to PropertyLab:",{elsCacheEntries:Et.elsCache?.length??0,compAiCacheEntries:Et.compAiCache?.length??0,allCachedSalesEntries:Et.allCachedSales?.length??0}),Ki.current={allCachedSalesSig:Array.isArray(Et.allCachedSales)?So(Et.allCachedSales):Ki.current.allCachedSalesSig,elsCacheSig:To(Array.isArray(Et.elsCache)?Et.elsCache:void 0),compAiCacheSig:wa(Array.isArray(Et.compAiCache)?Et.compAiCache:void 0)},kl.current=X):F&&(Od(Yt=>Yt??{allCachedSales:[]}),kl.current=X)},[b,h?.id,z,F]),o.useCallback(async P=>{if(!(!b||!O))try{await fetch(`/api/v2/orders/${b}`,{method:"PATCH",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(P)}),oT(b),console.log("[Wizard] Updated order:",Object.keys(P))}catch(X){console.error("[Wizard] Failed to update order:",X)}},[b,O]),o.useEffect(()=>{const P=se.subjectAddress?.value;if(P!==Hm){if(Hm&&(Td(null),Ap(null),console.log("[Wizard] Address changed, clearing prefetched zoning data")),!P){js(null),Xl(null);return}if(js(P),Fi){console.log("[Wizard] Zoning data already available, skipping prefetch");return}Wm(!0),Xl(null),console.log("[Wizard] Prefetching zoning data for:",P);const X=P,xe=Km.current;Km.current=!1,(async()=>{try{const[Ye,ke]=await Promise.all([FI(X,xe),hT(X,void 0,xe)]);if(X!==se.subjectAddress?.value)return;if(Ye.success&&Ye.data&&(Ye.data.zoneCode||Ye.data.zoneName||Ye.data.zoneDescription))Xl(null),Td(Ye.data),console.log("[Wizard] Zoning data prefetched:",Ye.data.zoneCode),b&&O&&(vr("zoning_api_data",{zoningData:Ye.data,address:X}),console.log("[Wizard] Zoning API data saved to progress"));else{const jt=Ye.error||"No zoning data returned";Xl(jt),console.warn("[Wizard] Zoning prefetch returned no data:",jt)}X===se.subjectAddress?.value&&ke.success&&(Ap(ke),b&&O&&vr("zoning_screenshot",{screenshot:ke,address:X,cacheVersion:Zj}))}catch(Ye){X===se.subjectAddress?.value&&Xl(Ye instanceof Error?Ye.message:"Zoning lookup failed"),console.warn("[Wizard] Zoning prefetch failed:",Ye)}finally{Wm(!1)}})()}},[se.subjectAddress?.value,Hm,Fi,b,O,vr]);const ih=o.useCallback(()=>{Km.current=!0,Td(null),Ap(null),Xl(null),Id.current=null,$u.current=!1,js(null)},[]);o.useEffect(()=>{const P=se.subjectAddress?.value;if(!P||Vu&&!$u.current||!Fi||bo||Id.current===P)return;Id.current=P;let X=!1;return(async()=>{try{const xe=await hT(P);if(X)return;P===se.subjectAddress?.value&&xe.success?($u.current=!1,Ap(xe),console.log("[Wizard] Re-fetched zoning screenshot at current zoom"),b&&O&&vr("zoning_screenshot",{screenshot:xe,address:P,cacheVersion:Zj})):Id.current=null}catch(xe){console.warn("[Wizard] Zoning screenshot re-fetch failed:",xe),Id.current=null}})(),()=>{X=!0}},[se.subjectAddress?.value,Vu,Fi,bo,b,O,vr]);const bm=o.useCallback(P=>{const X=Array.from(u.current).map(jt=>pn[jt]).filter(jt=>typeof jt=="string"),xe={orderData:se,propertyData:H,subjectCoordinates:Os,subjectDetails:Br,subjectPhotos:mr,visitedStepKeys:X};let Ye=null;try{Ye=SJ(Gn.current)}catch(jt){console.error("[Wizard] stripBoundaryGeometryFromSnapshot failed on step persist; omitting cachedLabState:",jt)}const ke=HV(pt);switch(P){case"subject_site":return{...xe,occupancy:de,historyData:Be,subjectSiteOverrideLog:Ie,subjectSiteLocalFields:Pe};case"comp_intent":return{...xe,occupancy:de,historyData:Be,compIntentState:ot,marketLabState:Ot,afterRepairedSubject:Zo,renovationState:Xp,compScenarioTags:hl,csvSubjectValues:Bn};case"property_lab":return{...xe,occupancy:de,historyData:Be,compIntentState:ot,compLabState:ke,marketLabState:Ot,cleanedComps:qe,compScenarioTags:hl,csvSubjectValues:Bn,cachedLabState:Ye,gridAdjustments:Ks};case"sales_grid":return{...xe,occupancy:de,historyData:Be,compIntentState:ot,compLabState:ke,marketLabState:Ot,cleanedComps:qe,compScenarioTags:hl,cachedLabState:Ye,gridAdjustments:Ks};case"lease_summary":case"agency_check":case"calculator":case"rights_adjust":case"addendum":return{...xe,occupancy:de,historyData:Be,compIntentState:ot,compLabState:ke,marketLabState:Ot,cleanedComps:qe,leaseholdState:$r,selectedAgency:tl,cachedLabState:Ye};case"review":return{...xe,occupancy:de,historyData:Be,cleanedComps:qe,compScenarioTags:hl,gridAdjustments:Ks,afterRepairedSubject:Zo,renovationState:Xp,marketLabState:Ot,bridgeValues:vd};default:return{...xe,marketLabState:Ot}}},[se,H,de,Be,ot,pt,Ot,qe,$r,tl,Os,Br,mr,Zo,Xp,hl,Ks,Bn,Ie,Pe,vd]),qg=o.useRef(bm);qg.current=bm,o.useEffect(()=>{if(!Fi)return;const P=_T(H,Fi);P!==H&&(ye(P),b&&O&&vr("subject_site",{...qg.current("subject_site"),propertyData:P}))},[Fi,H,b,O,vr]);const If=o.useCallback(P=>{if(P>=0&&P<pn.length)return pn[P];const X=Math.max(0,Math.min(P,pn.length-1)),xe=pn[X]||"order_snapshot";return console.warn(`[Wizard] Step index ${P} out of range (0-${pn.length-1}), clamped to '${xe}'`),xe},[pn]),ym=o.useCallback(P=>{it.current=P},[]),Yg=o.useCallback(async P=>{if(zm(P),!!P){zi?.getLibrarySearches&&Xd(zi.getLibrarySearches()),zi?.getOrderMarketStates&&qm(zi.getOrderMarketStates()),Ym(!0);try{const X=await fetch("/api/market-library");if(X.ok){const xe=await X.json();Array.isArray(xe)&&Xd(xe)}if(b){const xe=await DA(b).catch(()=>null);if(xe){const Ye=xe?.marketStates||xe?.order?.marketStates;Array.isArray(Ye)&&qm(Ye)}}}catch(X){console.error("[Wizard] Failed to load header saved data:",X)}finally{Ym(!1)}!b&&Nd==="order"&&Fu("library")}},[zi,b,Nd]),xu=o.useCallback(P=>{zi?.applyLibrarySearch?.(P),zm(!1)},[zi]),vi=o.useCallback(P=>{zi?.applyOrderState?.(P),zm(!1)},[zi]),Gg=o.useCallback(async P=>{try{const X=await fetch(`/api/market-library/${P}`,{method:"DELETE"});X.ok?(Xd(xe=>xe.filter(Ye=>Ye.id!==P)),zi?.removeLibrarySearchFromState?.(P)):console.error("[Wizard] Delete library search failed:",X.status)}catch(X){console.error("[Wizard] Failed to delete library search:",X)}},[zi]);o.useEffect(()=>!b||!O?void 0:D2(X=>
53{X.orderId===b&&X.ok&&fl.current&&(Tr("saved"),Fr.current&&clearTimeout(Fr.current),Fr.current=setTimeout(()=>{fl.current&&Tr("idle")},2500))}),[b,O]);const Ld=o.useRef(!1),[w,wt]=o.useState(!1),Pt=4e3,Ba=(P,X)=>Promise.race([P.catch(()=>{}),new Promise(xe=>setTimeout(xe,X))]),Ts=async()=>{if(zi?.flushPendingLocks)try{await Ba(zi.flushPendingLocks(),Pt)}catch{}if(b&&O)try{await Ba(sE(b),Pt)}catch{}},ia=async()=>{if(!Ld.current){Ld.current=!0,wt(!0);try{if(await Ts(),T&&t===ca.ADDRESS&&!st){m({title:"Property Required",description:"Please look up a property address first",variant:"destructive"});return}if(t<io-1){const P=t+1;a(P),window.scrollTo(0,0)}}finally{Ld.current=!1,fl.current&&wt(!1)}}},Ca=async()=>{if(!Ld.current){Ld.current=!0,wt(!0);try{await Ts();const P=T?ca.ADDRESS:ca.ORDER;t>P&&(a(X=>X-1),window.scrollTo(0,0))}finally{Ld.current=!1,fl.current&&wt(!1)}}},[Ls,Qs]=o.useState(!1),[Lt,La]=o.useState(!1),lr=async()=>{if(Lt||!b||!Xf(b))return;La(!0);const P=window.open("about:blank","_blank");try{if(!Xf(b))throw new Error("Editing session ended");const X=await TV();if(!Xf(b))throw new Error("Editing session ended");if(!X)throw new Error("Unsaved edits could not be saved — preview blocked");const xe=await fetch(`/api/uad36/prefill/${encodeURIComponent(b)}?skipExternal=true`,{credentials:"include"});if(!xe.ok)throw new Error(`prefill ${xe.status}`);const{sections:Ye}=await xe.json(),ke=Ye?.subjectProperty?.AddressLineText,jt=ke&&typeof ke=="object"?ke.value:ke,Et=b.replace(/[^A-Za-z0-9]+/g,"").slice(-5)||"report",ka=Jt=>Jt.trim().replace(/[^A-Za-z0-9]+/g,"-").replace(/^-+|-+$/g,""),ha=`${["3.6URAR",Et,...jt?.trim()?[ka(jt)]:[]].join("-")}.pdf`,Rt=await fetch(`/api/reports/styled/urar/pdf?cache=1&filename=${encodeURIComponent(ha)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ye??{})});if(!Rt.ok){P&&!P.closed&&P.close();const Jt=await Rt.text();throw new Error(`PDF request failed (${Rt.status}): ${Jt}`)}const{url:Bt}=await Rt.json();P?P.location.href=Bt:window.location.href=Bt}catch(X){P&&!P.closed&&P.close(),console.error("[Wizard] URAR preview error:",X),m({title:"Preview failed",description:X instanceof Error?X.message:"Could not generate the PDF preview.",variant:"destructive"})}finally{La(!1)}},Ys=()=>{if(!Ls){if(Qs(!0),b&&O){const P=If(t),X=bm(P);vr(P,X).then(()=>console.log("[Wizard] Saved all progress before exit:",P))}ci&&Ea&&b&&tc(!0),b&&sessionStorage.removeItem(`lock-self-released:${b}`),m({title:"Draft Saved",description:"Your progress is being saved."}),y(q2({isPlatformAdmin:S}))}},Ms=o.useCallback(P=>P==="Sales Grid"&&Ea?"Grids":P,[Ea]),Zr=o.useMemo(()=>Pn.map((P,X)=>({name:P,status:X===t?"current":d.has(X)&&X!==t?"done":"upcoming"})),[Pn,t,d]),cn=o.useMemo(()=>{const X=(se.subjectAddress?.value||"").split(",").map(ka=>ka.trim()),xe=X[0]||"",Ye=vn||X[1]||"",ke=Jn||(X[2]?X[2].replace(/\s*\d{5}(-\d{4})?$/,"").trim():""),Et=[Ye,ke,Ei||""].filter(Boolean).join(", ");return{street:xe,cityStateZip:Et,beds:H.bedrooms?.value?String(H.bedrooms.value):Ri?.bedrooms!=null?String(Ri.bedrooms):void 0,baths:(()=>{const ka=H.fullBaths?.value!=null?Number(H.fullBaths.value):null,Yt=H.halfBaths?.value!=null?Number(H.halfBaths.value):null,ha=H.bathrooms?.value?parseFloat(String(H.bathrooms.value)):null;if(ka!=null||ha!=null)return yg(ka,Yt,ha);if(Ri?.bathrooms!=null)return yg(null,null,Ri.bathrooms)})(),sqft:H.gla?.value?String(H.gla.value).replace(/,/g,""):Ri?.gla!=null?String(Ri.gla):void 0,orderNumber:C?.order?.orderNumber||(se.orderNumber?.value?String(se.orderNumber.value):"")||""}},[se.subjectAddress,se.orderNumber,C,vn,Jn,Ei,H.bedrooms,H.bathrooms,H.fullBaths,H.halfBaths,H.gla,Ri]),Jr=o.useCallback(async()=>{if(!b||!O){m({title:"Subject refresh unavailable",description:"Save this order before requesting provider photos.",variant:"destructive"});return}const P=se.subjectAddress?.value||"";if(P){ut(!0);try{const X=new URLSearchParams({street:P,city:vn||"",state:Jn||"",zip:Ei||"",nocache:"true"}),xe=await fetch(`/api/property?${X.toString()}`,{credentials:"include"}),Ye=await xe.json().catch(()=>({}));if(!xe.ok||!Ye.success)throw new Error(Ye.error||`Provider request failed (${xe.status})`);const ke={propertyDetails:Ye.propertyDetails||{},listingDetails:Ye.listingDetails||{},allListingSheets:Ye.allListingSheets||[]};await he(ke,{fullAddress:P,streetAddress:P,city:vn,state:Jn,zipCode:Ei,lat:ke.propertyDetails.coordinates?.lat||Os?.lat,lng:ke.propertyDetails.coordinates?.lng||Os?.lng})}catch(X){m({title:"Subject refresh failed",description:X instanceof Error?X.message:"Provider data could not be loaded.",variant:"destructive"})}finally{ut(!1)}}},[O,b,se.subjectAddress,vn,Jn,Ei,Os,m]),Wn=o.useMemo(()=>{const P=se.subjectAddress?.value;if(!P)return null;const X=P.split(",").map(br=>br.trim()),xe=H.bedrooms?.value?parseInt(String(H.bedrooms.value)):null,Ye=H.fullBaths?.value?parseInt(String(H.fullBaths.value)):null,ke=H.halfBaths?.value?parseInt(String(H.halfBaths.value)):null,jt=H.bathrooms?.value?parseFloat(String(H.bathrooms.value)):Ye!=null?Ye+(ke??0)*.5:null,Et=H.gla?.value?parseInt(String(H.gla.value).replace(/[^0-9]/g,"")):null,ka=H.lotSize?.value?parseInt(String(H.lotSize.value).replace(/[^0-9]/g,"")):null,Yt=H.yearBuilt?.value?parseInt(String(H.yearBuilt.value)):null,ha=H.stories?.value?parseInt(String(H.stories.value)):null,Rt=H.garageCars?.value?parseInt(String(H.garageCars.value)):null,Bt=se.salePrice?.value?parseInt(String(se.salePrice?.value).replace(/[^0-9]/g,"")):null,Jt=mr||[],gt=Hi?.listingDetails||{},Ra=Hi?.propertyDetails||{},fa=zX(Hi,H),Is=Ra.squareFeet&&parseInt(String(Ra.squareFeet))||null,cs=Ra.lotSize&&parseInt(String(Ra.lotSize))||null;return{id:"subject",address:X[0]||P,city:vn||X[1]||"",state:Jn||"",zip:Ei||"",price:Bt||null,beds:xe,baths:jt,fullBathrooms:Ye,halfBathrooms:ke,sqft:Et,sqftPR:Is,lotSqft:ka,lotSqftPR:cs,yearBuilt:Yt||void 0,yearBuiltPR:Ra.yearBuilt&&parseInt(String(Ra.yearBuilt))||void 0,stories:ha||void 0,garageSpaces:Rt||void 0,style:H.designStyle?.value?String(H.designStyle.value):gt.style||Ra.style||void 0,propertyType:fa.propertyType,unitCount:fa.unitCount,unitCountSource:fa.unitCountSource,unitCountAlternatives:fa.unitCountAlternatives,unitCountConflict:fa.unitCountConflict,buildingAreaSqft:fa.buildingAreaSqft,buildingAreaSource:fa.buildingAreaSource,photoUrl:Jt[0]||null,photos:Jt,photoCount:Jt.length,dom:gt.daysOnMarket||null,status:v0(gt),coordinates:Os||null,echoLocationScore:gl?{score:gl.score,tier:gl.tier,factors:gl.factors,isOverrid
53den:!1}:void 0,conditionRating:Ao?.condition?.rating||void 0,qualityRating:Ao?.quality?.rating||void 0,aiConditionRating:ao?.conditionRating??null,aiConditionSignals:ao?.conditionSignals?.length?JSON.stringify(ao.conditionSignals):null,aiQualitySignals:ao?.qualitySignals?.length?JSON.stringify(ao.qualitySignals):null,aiRecentUpdates:ao?.recentUpdates?.length?JSON.stringify(ao.recentUpdates):null,aiBasementDetails:ao?.basementDetails??null,publicRecordData:{bedrooms:Ra.bedrooms||void 0,bathrooms:Ra.bathrooms||void 0,squareFeet:Ra.squareFeet||void 0,livingArea:Ra.squareFeet||void 0,...fa.publicRecordData,lotSize:Ra.lotSize||void 0,lotAcres:Ra.lotSizeAcres||void 0,yearBuilt:Ra.yearBuilt||void 0,style:Ra.style||void 0,construction:Ra.construction||void 0,roof:Ra.roofType||void 0,RoofType:Ra.roofType||void 0,foundation:Ra.foundation||void 0,FoundationType:Ra.foundation||void 0,heating:Ra.heating||void 0,cooling:Ra.cooling||void 0,garage:Ra.garage||void 0,garageSpaces:Ra.garage&&parseInt(String(Ra.garage))||void 0,fireplace:Ra.fireplace||void 0,fireplaceCount:Ra.fireplace||void 0,taxes:Ra.taxes||H.taxes?.value||void 0,taxYear:Ra.taxYear||H.taxYear?.value||void 0,taxAssessedValue:Ra.taxAssessedValue||void 0,county:Ra.county||H.county?.value||void 0,zoning:Ra.zoningCode||H.zoningClassification?.value||void 0,zoningDescription:Ra.zoningDescription||void 0,neighborhood:Ra.neighborhood||void 0,subdivision:Ra.subdivision||void 0,owner:Ra.owner||void 0,apn:Ra.apn||void 0,legalDescription:Ra.legalDescription||void 0,ExteriorWalls:Ra.construction||H.exteriorWalls?.value||void 0},mlsData:{bedrooms:gt.bedrooms||void 0,bathrooms:gt.bathrooms||void 0,squareFeet:gt.squareFeet||void 0,...fa.mlsData,unitBreakdown:fa.unitBreakdown,unitMix:fa.unitMix,lotSize:gt.lotSize||void 0,yearBuilt:gt.yearBuilt||void 0,style:gt.style||void 0,stories:gt.stories??Ra.stories??ha??void 0,bathroomsFull:gt.fullBathrooms??(H.fullBaths?.value!=null?parseInt(String(H.fullBaths.value)):void 0),bathroomsHalf:gt.halfBathrooms??(H.halfBaths?.value!=null?parseInt(String(H.halfBaths.value)):void 0),garageSpaces:gt.garageSpaces||Rt||void 0,basement:gt.basement||H.basementFinish?.value||void 0,construction:gt.construction||H.exteriorWalls?.value||void 0,roof:gt.roofType||H.roofSurface?.value||void 0,foundation:gt.foundation||H.foundationWalls?.value||void 0,heating:gt.heating||H.heatingType?.value||void 0,cooling:gt.cooling||H.coolingType?.value||void 0,pool:gt.pool||void 0,poolFeatures:gt.pool||void 0,fireplace:gt.fireplace?!0:void 0,fireplaceFeatures:gt.fireplaceFeatures||void 0,fireplaceCount:gt.fireplace||void 0,fireplacesTotal:gt.fireplace||void 0,parking:gt.parkingType||void 0,parkingFeatures:gt.parkingFeatures||void 0,water:gt.water||H.waterType?.value||void 0,sewer:gt.sewer||H.sanitarySewerType?.value||void 0,electricity:gt.electricity||void 0,gas:gt.gas||void 0,utilities:gt.utilities||void 0,taxes:gt.taxes||H.taxes?.value||void 0,taxYear:gt.taxYear||H.taxYear?.value||void 0,assessedValue:gt.taxAssessedValue||void 0,associationYn:gt.associationYn,associationName:gt.associationName||void 0,associationFee:gt.associationFee||H.hoaFees?.value||void 0,associationFeeFrequency:gt.associationFeeFrequency||void 0,zoning:gt.zoning||H.zoningClassification?.value||void 0,subdivision:gt.subdivision||H.neighborhoodName?.value||void 0,schoolDistrict:gt.schoolDistrict||void 0,elementarySchool:gt.elementarySchool||void 0,middleSchool:gt.middleSchool||void 0,highSchool:gt.highSchool||void 0,county:gt.county||H.county?.value||void 0,apn:gt.apn||void 0,publicRemarks:gt.publicRemarks||gt.description||void 0,originalListPrice:gt.originalListPrice||void 0,interiorFeatures:gt.interiorFeatures||void 0,exteriorFeatures:gt.exteriorFeatures||void 0,appliances:gt.appliances||void 0,laundryFeatures:gt.laundryFeatures||void 0,flooring:gt.flooring||void 0,lotFeatures:gt.lotFeatures||void 0,lotDimensions:gt.lotDimensions||void 0,lotSizeDimensions:gt.lotDimensions||void 0,lotSizeAcres:gt.lotSizeAcres??void 0,lotSizeSquareFeet:gt.lotSizeSquareFeet??void 0,lotShape:gt.lotShape||void 0,topography:gt.topography||void 0,frontageLength:gt.frontageLength||void 0,frontageType:gt.frontageType||void 0,roadSurfaceType:gt.roadSurfaceType||void 0,propertyType:gt.propertyType||void 0,legalDescription:gt.legalDescription||void 0,concessions:gt.concessions||void 0,saleTerms:gt.saleTerms||void 0,patioFeatures:gt.patioFeatures||void 0,fencing:gt.fencing||void 0,privateOutdoorSpace:gt.privateOutdoorSpace||void 0,securityFeatures:gt.securityFeatures||void 0,solarPanelYN:gt.solarPanelYN||void 0,otherStructures:gt.otherStructures||void 0,driveway:gt.driveway||void 0,spaFeatures:gt.spaFeatures||void 0,spaYN:gt.spaYN??void 0,garageYN:gt.garageYN??void 0,attachedGarageYN:gt.attachedGarageYN??void 0,garageArea:gt.garageArea??void 0,carStorageType:gt.carStorageType||void 0,parkingTotal:gt.parkingTotal??void 0,parkingOwnership:gt.parkingOwnership||void 0,carportYN:gt.carportYN??void 0,openParkingSpaces:gt.openParkingSpaces??void 0,garageOwnership:gt.garageOwnership||void 0,ownership:gt.ownership||void 0,livingAreaSource:gt.livingAreaSource||void 0,directions:gt.directions||void 0,contingency:gt.contingency||void 0,heatingFuel:gt.heatingFuel||void 0,heatingFuelType:gt.heatingFuel||void 0,basementEntry:gt.basementEntry||void 0,basementType:gt.basementType||void 0,belowGradeTotalArea:gt.belowGradeTotalArea??void 0,cumulativeDaysOnMarket:gt.cumulativeDaysOnMarket??void 0,previousListPrice:gt.previousListPrice??void 0,distressedYN:gt.distressedYN??void 0,roomType:gt.roomType||void 0,roomDescription:gt.roomDe
53scription||void 0,township:gt.township||void 0,view:gt.view||void 0,greenFeatures:gt.greenFeatures||void 0,hersIndex:gt.hersIndex??void 0,equipment:gt.equipment||void 0,bathFeatures:gt.bathFeatures||void 0,attic:gt.attic||void 0,waterfront:gt.waterfront||void 0,newConstruction:gt.newConstruction??void 0,closedDate:gt.closedDate||void 0,spLpRatio:gt.spLpRatio??void 0,taxExemptions:gt.taxExemptions||void 0,specialAssessments:gt.specialAssessments||void 0,roomsTotal:gt.roomsTotal??void 0,mainLevelArea:gt.mainLevelArea??void 0,possession:gt.possession||void 0}}},[se.subjectAddress,se.salePrice,vn,Jn,Ei,Os,H,gl,Ao,ao,mr,Hi]),Dt=Ll||qi?52:220,Da=Wi&&(t===ca.PROPERTY_LAB||t===ca.SALES_GRID)?"property_lab":Wi&&t===ca.COMP_INTENT?"comp_intent":sh&&[ca.LEASE_SUMMARY,ca.AGENCY_CHECK,ca.CALCULATOR,ca.RIGHTS_ADJUST,ca.ADDENDUM].includes(t)?"leasehold":gu&&t===ca.STR?"str":Ir&&t===ca.EVAL?"eval":ac!==-1&&t===ac?"review":null,Ia=Da!==null&&Dw(Da,!0,W(Da,Da==="property_lab"&&t===ca.SALES_GRID),Dr),ar=Pq(A,Ia),Xs=!Ll&&zc&&!ar,Fa=Ll||qi&&!Xs,is=Fa?52:220,Cr=Wi&&(t===ca.PROPERTY_LAB||t===ca.SALES_GRID)||sh&&[ca.LEASE_SUMMARY,ca.AGENCY_CHECK,ca.CALCULATOR,ca.RIGHTS_ADJUST,ca.ADDENDUM].includes(t)||gu&&t===ca.STR||Ir&&t===ca.EVAL,Io=T&&t===ca.ADDRESS,Qi=t>=ca.ORDER&&!Cr&&!(ac!==-1&&t===ac),ic=P=>{a(P),window.scrollTo(0,0)},dr=o.useMemo(()=>(ue||[]).map(P=>({name:P.name,type:P.type})),[ue]);if(Wu)return e.jsx(K2,{onContinue:Hn,initialSelection:hr});const _r=Re||b||void 0,Ni=e.jsx(nZ,{children:e.jsxs("div",{className:"h-screen bg-background font-sans text-foreground flex flex-col overflow-hidden",children:[A&&e.jsx("div",{className:"fixed inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-lg p-8 flex flex-col items-center gap-4",children:[e.jsx(za,{className:"h-8 w-8 animate-spin text-primary"}),e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Loading Order"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Fetching order data..."})]})]})}),Bg&&e.jsxs("header",{className:"h-11 bg-[#072034] flex items-center shrink-0 z-30","data-testid":"wizard-field-search-header",children:[e.jsx("div",{className:"flex items-center justify-center shrink-0 px-3",style:{width:Dt},children:e.jsx("img",{src:aE,alt:"Banks Technologies",className:"h-5 opacity-90"})}),e.jsx("div",{className:"flex-1 flex items-center justify-end px-4",children:e.jsx(vV,{sectionNames:{},getRoots:Gu,extraEntries:Sb,onSelect:zg,className:"[&_input]:bg-white [&_input]:border-white/20"})})]}),Wi&&ca.PROPERTY_LAB!==-1&&t===ca.PROPERTY_LAB&&e.jsxs("header",{className:"h-11 bg-[#072034] flex items-center shrink-0 z-30","data-testid":"global-header",children:[e.jsx("div",{className:"flex items-center justify-center shrink-0 px-3",style:{width:Dt},children:e.jsx("img",{src:aE,alt:"Banks Technologies",className:"h-5 opacity-90","data-testid":"header-logo"})}),e.jsxs("div",{className:"flex-1 flex items-center gap-4 px-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Eu,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-white/40",size:14}),e.jsx("input",{className:"w-full h-8 pl-8 pr-3 bg-white/10 border border-white/15 rounded-md text-[12px] text-white placeholder:text-white/40 outline-none focus:border-[#C5A572]/60 focus:bg-white/15 transition-all",placeholder:"Search Property",value:Zt,onChange:P=>Rs(P.target.value),"data-testid":"input-global-search"})]}),e.jsxs(xn,{open:gc,onOpenChange:Yg,children:[e.jsx(bn,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1.5 text-white/80 text-[11px] font-medium cursor-pointer hover:text-white transition-colors","data-testid":"btn-header-saved",children:[e.jsx(h2,{size:13,className:"text-[#C5A572]"}),e.jsx("span",{children:"Saved"}),so.length+Uc.length+eu.length>0&&e.jsx("span",{className:"flex items-center justify-center bg-[#C5A572] text-white text-[9px] font-bold w-[18px] h-[18px] rounded-full",children:so.length+Uc.length+eu.length}),e.jsx(Rr,{size:11,className:"text-white/50"})]})}),e.jsxs(yn,{align:"start",className:"w-80 p-0","data-testid":"header-saved-dropdown",children:[e.jsxs("div",{className:"flex border-b bg-gray-50",children:[b&&e.jsxs("button",{className:`flex-1 px-3 py-2 text-xs font-medium transition-colors ${Nd==="order"?"bg-white text-blue-700 border-b-2 border-blue-600":"text-gray-600 hover:bg-gray-100"}`,onClick:()=>Fu("order"),"data-testid":"header-tab-order",children:["This Order",eu.length>0&&e.jsxs("span",{className:"ml-1 text-[10px] text-gray-500",children:["(",eu.length,")"]})]}),e.jsxs("button",{className:`flex-1 px-3 py-2 text-xs font-medium transition-colors ${Nd==="library"?"bg-white text-blue-700 border-b-2 border-blue-600":"text-gray-600 hover:bg-gray-100"}`,onClick:()=>Fu("library"),"data-testid":"header-tab-library",children:["Library",Uc.length>0&&e.jsxs("span",{className:"ml-1 text-[10px] text-gray-500",children:["(",Uc.length,")"]})]}),e.jsxs("button",{className:`flex-1 px-3 py-2 text-xs font-medium transition-colors ${Nd==="comps"?"bg-white text-blue-700 border-b-2 border-blue-600":"text-gray-600 hover:bg-gray-100"}`,onClick:()=>Fu("comps"),"data-testid":"header-tab-comps",children:["Comps",so.length>0&&e.jsxs("span",{className:"ml-1 text-[10px] text-gray-500",children:["(",so.length,")"]})]})]}),e.jsx("div",{className:"max-h-72 overflow-y-auto",children:Eg?e.jsxs("div",{className:"flex items-center justify-center py-6",children:[e.jsx(za,{className:"w-4 h-4 animate-spin text-gray-400"}),e.jsx("span",{className:"ml-2 text-xs text-gray-500",children:"Loading..."})]}):Nd==="order"&&b?eu.length===0?e.jsxs("div",{className:"px-4 py-6 text-center text-xs text-gray-500",children:["No locked markets yet.",e.jsx("br",{}),e.jsx("span",{className:"text-[10px]",children:"Lock a market in Property Lab to save it here."})]}):eu.map(P=>e.jsx("div",{className:"px-3 py-2 hover:bg-gray-50 border-b last:border-b-0 group","data-testid":`header-order-state-${P.id}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:P.name}),e.jsxs("div",{className:"text-[10px] text-gray-500 flex items-center gap-2",children:[P.salesCount&&e.jsxs("span",{children:[P.salesCount," sales"]}
53),P.radiusMiles&&e.jsxs("span",{children:[parseFloat(P.radiusMiles).toFixed(1)," mi"]}),P.lockedAt&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Pu,{className:"w-2.5 h-2.5"}),new Date(P.lockedAt).toLocaleDateString()]})]})]}),e.jsx(De,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:()=>vi(P),"data-testid":`header-apply-order-${P.id}`,children:"Apply"})]})},P.id)):Nd==="library"?Uc.length===0?e.jsxs("div",{className:"px-4 py-6 text-center text-xs text-gray-500",children:["No saved searches in library.",e.jsx("br",{}),e.jsx("span",{className:"text-[10px]",children:"Save market searches for quick reuse."})]}):Uc.map(P=>e.jsx("div",{className:"px-3 py-2 hover:bg-gray-50 border-b last:border-b-0 group","data-testid":`header-library-${P.id}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:P.name}),e.jsxs("div",{className:"text-[10px] text-gray-500 flex items-center gap-2",children:[P.salesCount&&e.jsxs("span",{children:[P.salesCount," sales"]}),P.useCount!=null&&P.useCount>0&&e.jsxs("span",{children:["Used ",P.useCount,"x"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(De,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",onClick:()=>xu(P),"data-testid":`header-apply-library-${P.id}`,children:"Apply"}),e.jsx("button",{onClick:()=>Gg(P.id),className:"p-1 rounded hover:bg-red-100 opacity-0 group-hover:opacity-100 transition-opacity","data-testid":`header-delete-library-${P.id}`,children:e.jsx(Ci,{className:"w-3 h-3 text-red-500"})})]})]})},P.id)):so.length===0?e.jsxs("div",{className:"px-4 py-6 text-center text-xs text-gray-500",children:["No selected comps yet.",e.jsx("br",{}),e.jsx("span",{className:"text-[10px]",children:"Select comps in Property Lab to see them here."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-3 py-2 bg-gray-50 border-b text-[10px] text-gray-500 font-medium",children:[so.length," comp",so.length!==1?"s":""," selected"]}),so.slice(0,10).map((P,X)=>e.jsxs("div",{className:"px-3 py-1.5 border-b last:border-b-0 hover:bg-gray-50","data-testid":`header-comp-${P.compId||X}`,children:[e.jsx("div",{className:"text-xs font-medium truncate",children:P.address||`Comp ${X+1}`}),e.jsxs("div",{className:"text-[10px] text-gray-500 flex items-center gap-2",children:[P.price>0&&e.jsxs("span",{children:["$",Number(P.price).toLocaleString()]}),P.gla>0&&e.jsxs("span",{children:[Number(P.gla).toLocaleString()," SF"]}),P.beds>0&&e.jsxs("span",{children:[P.beds,"bd/",P.baths,"ba"]})]})]},P.compId||X)),so.length>10&&e.jsxs("div",{className:"px-3 py-2 text-center text-[10px] text-gray-400",children:["+",so.length-10," more"]})]})})]})]}),e.jsx("div",{className:"flex-1"}),h&&e.jsx("div",{className:"w-7 h-7 rounded-full bg-[#C5A572]/30 flex items-center justify-center text-[10px] font-bold text-[#C5A572] border border-[#C5A572]/40","data-testid":"header-avatar",children:(h.firstName?.[0]||h.email?.[0]||"U").toUpperCase()})]})]}),e.jsxs("div",{className:"flex-1 min-w-0 min-h-0 flex overflow-hidden",children:[e.jsx(Kh.div,{animate:{width:Dt},transition:{type:"spring",damping:25,stiffness:300},className:"relative shrink-0","data-testid":"sidebar-slot",children:e.jsxs(Kh.aside,{animate:{width:is},transition:{type:"spring",damping:25,stiffness:300},onPointerEnter:Og,onPointerLeave:Xo,className:Q("absolute inset-y-0 left-0 z-40 bg-[#072034] text-white flex flex-col border-r border-slate-800 overflow-hidden",qi&&Xs&&"shadow-2xl shadow-black/40"),"data-testid":"sidebar",children:[e.jsx("div",{className:`flex items-center ${Fa?"justify-center":"flex-start"} px-3 py-2.5 border-b border-white/10`,children:e.jsx("div",{className:"flex items-center gap-2.5",children:e.jsx("button",{onClick:Lg,className:"p-1 hover:bg-white/10 rounded transition-colors text-white/80 hover:text-white","data-testid":"button-toggle-sidebar",title:qi?zc?"Pin sidebar open":"Expand sidebar":"Collapse sidebar",children:Fa?e.jsx(f2,{size:16}):e.jsx(oL,{size:16})})})}),e.jsx("button",{onClick:()=>gp(!0),className:Q("w-full text-left border-b border-white/10 transition-colors group relative",Fa?"p-2 flex items-center justify-center":"p-3","bg-black/20 hover:bg-white/5"),title:Fa?cn.street:void 0,"data-testid":"sidebar-subject-button",children:Fa?e.jsx(Fo,{size:16,className:"text-[#C5A572]"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-0.5",children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-widest text-[#C5A572]","data-testid":"text-sidebar-order-label",children:zu&&cn.orderNumber?cn.orderNumber:"Subject"}
53),e.jsx(ub,{size:10,className:"text-white/30 group-hover:text-white/60 transition-colors"})]}),e.jsx("div",{className:"text-[13px] font-bold text-white leading-tight whitespace-nowrap truncate",children:cn.street||"No address"}),e.jsx("div",{className:"text-[11px] text-white/60 mb-1.5 whitespace-nowrap truncate",children:cn.cityStateZip}),(cn.beds||cn.baths||cn.sqft)&&e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-medium text-white/40 whitespace-nowrap",children:[cn.beds&&e.jsxs("span",{children:[cn.beds," Bed"]}),cn.beds&&cn.baths&&e.jsx("span",{children:"·"}),cn.baths&&e.jsxs("span",{children:[cn.baths," Bath"]}),(cn.beds||cn.baths)&&cn.sqft&&e.jsx("span",{children:"·"}),cn.sqft&&e.jsxs("span",{children:[Number(cn.sqft).toLocaleString()," sqft"]})]})]})}),e.jsxs("div",{className:"flex-1 py-3 overflow-y-auto scrollbar-hide",children:[!Fa&&e.jsx("div",{className:"px-4 text-[9px] font-bold uppercase tracking-widest text-white/30 mb-2",children:"Workflow"}),e.jsx("div",{className:"flex flex-col",children:Zr.map((P,X)=>{const xe=MX(P.name),Ye=e.jsxs("button",{onClick:()=>ic(X),className:Q("flex items-center w-full py-[7px] text-left transition-colors relative group",Fa?"justify-center px-0":"px-4",P.status==="current"?"bg-white/10":"hover:bg-white/5"),"data-testid":`sidebar-step-${P.name.toLowerCase().replace(/[&\s]+/g,"-")}`,children:[P.status==="current"&&e.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-[3px] bg-[#C5A572]"}),Fa?e.jsxs("div",{className:"relative flex items-center justify-center w-7 h-7",children:[e.jsx(xe,{size:15,className:Q(P.status==="current"?"text-[#C5A572]":P.status==="done"?"text-white/60":"text-white/30 group-hover:text-white/55 transition-colors")}),P.status==="done"&&e.jsx("span",{className:"absolute -top-0.5 -right-0.5 w-3 h-3 rounded-full bg-emerald-500 border border-[#072034] flex items-center justify-center",children:e.jsx(Bs,{size:8,strokeWidth:3.5,className:"text-white"})})]}):e.jsx("div",{className:"flex items-center justify-center w-4 h-4 mr-2.5",children:P.status==="done"?e.jsx(Bs,{size:12,className:"text-[#C5A572]"}):P.status==="current"?e.jsx("div",{className:"w-2 h-2 rounded-full bg-[#C5A572]"}):e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-white/20 group-hover:bg-white/40 transition-colors"})}),!Fa&&e.jsxs("span",{className:Q("text-[12px] whitespace-nowrap",P.status==="current"?"text-white font-medium":P.status==="done"?"text-white/60 font-normal":"text-white/50 font-normal"),children:[X+1,". ",Ms(P.name)]})]});return e.jsx(Mn.Fragment,{children:Fa?e.jsxs(Ga,{delayDuration:150,children:[e.jsx(Ha,{asChild:!0,children:Ye}),e.jsxs(Wa,{side:"right",className:"text-xs",children:[X+1,". ",Ms(P.name)]})]}):Ye},X)})})]}),e.jsxs("div",{className:Q(Fa?"px-1.5 flex flex-col items-center":"px-3","pb-2 space-y-1.5"),children:[!Fa&&e.jsx("div",{className:"text-[9px] font-bold uppercase tracking-widest text-white/30 px-0 mb-1",children:"Reference Panels"}),(()=>{const P=[];xr&&P.push({key:"str",label:"STR Report",open:()=>Fe(!0)}),Ea&&b&&P.push({key:"uad36",label:"UAD 3.6 Report",open:()=>{try{window.sessionStorage.setItem("uad36:return-via-history","1")}catch{}y(`/3.6/${b}`)}});const X=se.form?.value||"";if(no&&(X==="1004"||X===""||X.includes("1004"))&&P.push({key:"1004",label:"Form 1004",open:()=>ya(!0)}),P.length===0)return null;const Ye=()=>{P.length===1?P[0].open():Ua(ke=>!ke)};return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:Ye,title:Fa?"Report":void 0,className:Q("rounded text-[11px] font-medium transition-all",Fa?"w-8 h-8 flex items-center justify-center":"w-full flex items-center gap-2 px-3 py-2","text-white/60 hover:bg-white/10 hover:text-white border border-white/10"),"data-testid":"sidebar-report-button",children:[e.jsx(sT,{size:13}),!Fa&&"Report",!Fa&&P.length>1&&e.jsx("span",{className:"ml-auto text-[9px] bg-white/15 px-1 rounded",children:P.length})]}),P.length>1&&zt&&e.jsx("div",{className:"absolute left-0 right-0 top-full z-50 pt-0.5","data-testid":"report-addon-menu",children:e.jsx("div",{className:"bg-[#0a1929] border border-white/15 rounded shadow-lg py-0.5",children:P.map(ke=>e.jsx("button",{onClick:jt=>{jt.stopPropagation(),ke.open(),Ua(!1)},className:"w-full text-left px-3 py-1.5 text-[10px] text-white/70 hover:bg-white/10 hover:text-white transition-colors","data-testid":`report-open-${ke.key}`,children:ke.label},ke.key))})})]})})(),e.jsxs("button",{onClick:()=>Wr(!0),title:Fa?"Inspection":void 0,className:Q("rounded text-[11px] font-medium transition-all relative",Fa?"w-8 h-8 flex items-center justify-center":"w-full flex items-center gap-2 px-3 py-2","text-white/60 hover:bg-white/10 hover:text-white border border-white/10"),"data-testid":"sidebar-inspection-button",children:[e.jsx(g2,{size:13})," ",!Fa&&"Inspection",ii&&e.jsx("span",{className:"absolute -top-0.5 -right-0.5 w-2.5 h-2.5 bg-emerald-500 rounded-full border-2 border-[#072034]"})]}),jo&&e.jsxs("button",{onClick:()=>Bc(!0),title:Fa?"Notes":void 0,disabled:!b,className:Q("rounded text-[11px] font-medium transition-all",Fa?"w-8 h-8 flex items-center justify-center":"w-full flex items-center gap-2 px-3 py-2","text-white/60 hover:bg-white/10 hover:text-white border border-white/10",!b&&"opacity-40 cursor-not-allowed"),"data-testid":"sidebar-notes-button",children:[e.jsx(gn,{size:13})," ",!Fa&&"Notes"]}),e.jsxs("button",{onClick:()=>Ve(!0),title:Fa?"Market Data":void 0,className:Q("rounded text-[11px] font-medium transition-all",Fa?"w-8 h-8 flex items-center justify-center":"w-full flex items-center gap-2 px-3 py-2","text-white/60 hover:bg-white/10 hover:text-white border border-white/10"),"data-testid":"sidebar-market-button",children:[e.jsx(Pl,{size:13})," ",!Fa&&"Market Data"]}),e.jsxs("button",{onClick:async()=>
53{if(b&&O)try{await Ba(sE(b),Pt)}catch{}b&&b$({url:window.location.pathname+window.location.search,orderId:b,step:If(t)}),y("/profile#wizard-defaults")},title:Fa?"Settings":void 0,className:Q("rounded text-[11px] font-medium transition-all",Fa?"w-8 h-8 flex items-center justify-center":"w-full flex items-center gap-2 px-3 py-2","text-white/60 hover:bg-white/10 hover:text-white border border-white/10"),"data-testid":"sidebar-settings-button",children:[e.jsx(rT,{size:13})," ",!Fa&&"Settings"]}),Wi&&t===ca.PROPERTY_LAB&&e.jsx(e.Fragment,{children:!1})]}),dr.length>0&&e.jsx(e.Fragment,{children:Fa?e.jsx("div",{className:"border-t border-white/10 bg-black/20 py-2 flex flex-col items-center",children:e.jsx("button",{className:"w-8 h-8 flex items-center justify-center text-white/50 hover:text-white hover:bg-white/10 rounded",title:`Documents (${dr.length})`,children:e.jsx(gn,{size:14})})}):e.jsxs("div",{className:"p-3 border-t border-white/10 bg-black/20",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-widest text-white/30",children:"Documents"}),e.jsx("span",{className:"text-[10px] bg-white/10 px-1.5 py-0.5 rounded text-white/60",children:dr.length})]}),e.jsx("div",{className:"space-y-1.5",children:dr.map((P,X)=>e.jsxs("div",{className:"flex items-center gap-2 text-white/50 hover:text-white cursor-pointer group",children:[e.jsx(gn,{size:11,className:"group-hover:text-[#C5A572] transition-colors"}),e.jsx("span",{className:"text-[11px] truncate flex-1",children:P.name})]},X))})]})}),e.jsx(FX,{orderId:b,hydrationPending:V||D,recentlySaved:au==="saved",railCollapsed:Fa}),!Ea&&!(Ir&&t===ca.EVAL)&&e.jsx("div",{className:Q(Fa?"px-1.5 flex justify-center":"px-3","py-2 border-t border-white/10"),children:e.jsxs("button",{onClick:Ys,disabled:Ls,className:Q("rounded text-[11px] font-medium text-white/40 hover:text-white/70 hover:bg-white/10 transition-colors",Fa?"w-8 h-8 flex items-center justify-center":"w-full flex items-center gap-2 px-3 py-2",Ls&&"opacity-50 pointer-events-none"),title:Fa?"Exit Wizard":void 0,"data-testid":"sidebar-exit-button",children:[Ls?e.jsx(za,{size:12,className:"animate-spin"}):e.jsx(nT,{size:12}),!Fa&&(Ls?"Saving...":"Exit Wizard")]})}),Ea&&e.jsx("div",{className:Q(Fa?"px-1.5 flex justify-center":"px-3","py-2 border-t border-white/10"),children:e.jsxs("button",{onClick:lr,disabled:Lt,className:Q("rounded text-[11px] font-medium text-white/40 hover:text-white/70 hover:bg-white/10 transition-colors",Fa?"w-8 h-8 flex items-center justify-center":"w-full flex items-center gap-2 px-3 py-2",Lt&&"opacity-50 pointer-events-none"),title:Fa?"Preview":void 0,"data-testid":"sidebar-preview-pdf-button",children:[Lt?e.jsx(za,{size:12,className:"animate-spin"}):e.jsx(gn,{size:12}),!Fa&&(Lt?"Generating…":"Preview")]})})]})}),e.jsxs(ME,{as:"main",ref:sm,readOnly:du,"data-testid":"wizard-main-step-pane",className:Q("flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden bg-white",du&&"select-none opacity-50"),children:[e.jsx("div",{className:Q("flex-1 min-h-0 relative",OJ(Cr),Cr?"bg-slate-100":Io?"bg-[#f6f7f8] p-6 lg:p-10 pb-20":""),"data-view-mode-scroll-root":!0,children:e.jsx("div",{className:Cr?"h-full w-full":Io?"max-w-4xl mx-auto":"",children:(()=>{const P=Wi&&(t===ca.PROPERTY_LAB||t===ca.SALES_GRID);P&&Dr&&!V&&!Z&&(qc.current=!0),P&&(bf.current=t);const X=bf.current===ca.SALES_GRID,xe=sh&&[ca.LEASE_SUMMARY,ca.AGENCY_CHECK,ca.CALCULATOR,ca.RIGHTS_ADJUST,ca.ADDENDUM].includes(t),Ye=T&&t===ca.ADDRESS,ke=Ea&&t===ca.AT_A_GLANCE_36,jt=Ea&&t===ca.ASSIGNMENT_36,Et=Ea&&t===ca.SUBJECT_PROPERTY_36,ka=Ea&&t===ca.SITE_36,Yt=Ea&&t===ca.IMPROVEMENTS_36,ha=hu&&t===ca.SALES_CONTRACT_36,Rt=Zc&&t===ca.PROJECT_INFORMATION_36,Bt=wn&&t===ca.LISTING_SALE_HISTORY_36,Jt=Ea&&t===ca.MARKET_36,gt=Ed&&t===ca.COST_APPROACH_36,Ra=t===ca.ORDER,fa=t===ca.SUBJECT_SITE,Is=Wi&&t===ca.COMP_INTENT,cs=gu&&t===ca.STR,br=Ir&&t===ca.EVAL,zr=ac!==-1&&t===ac,_s=(et,pa,Gt,hs,qr)=>{if(!pa&&!Zl.current.has(et))return null;pa&&Zl.current.add(et);const ys=Dw(et,pa,W(et,et==="property_lab"&&t===ca.SALES_GRID),Dr);
53return e.jsxs(Kh.div,{initial:!1,animate:{opacity:pa?1:0,x:pa?0:-10},transition:{duration:.2},className:Q(!pa&&"hidden",Gt&&"h-full",ys&&"relative"),"data-wizard-search-section":qr,children:[e.jsx("div",{inert:ys||void 0,"aria-busy":ys||void 0,className:Q(Gt&&"h-full",ys&&"pointer-events-none select-none"),children:e.jsx(o.Suspense,{fallback:e.jsx(qX,{}),children:e.jsx(WV,{visible:pa,children:hs})})}),ys&&e.jsx("div",{className:"absolute inset-0 z-40 flex items-start justify-center bg-background/90 pt-32","data-testid":"step-hydration-overlay",children:e.jsx(UX,{})})]},et)};return e.jsxs(e.Fragment,{children:[T&&_s("address",Ye,!1,A?null:e.jsx(Yq,{onPropertyLoaded:he,onReset:Ae,onAdvanceToNextStep:()=>{a(ca.ORDER),window.scrollTo(0,0)},isLoading:Le,setIsLoading:ut,hasPropertyData:st})),Ea&&_s("at_a_glance_36",ke,!0,e.jsx(wo,{stepName:"At A Glance (URAR 3.6)",children:e.jsx(TX,{orderId:b||"new",isActive:ke,onNavigateSection:(et,pa)=>{const hs={site:ca.SITE_36,improvements:ca.IMPROVEMENTS_36,outbuilding:ca.IMPROVEMENTS_36,exterior:ca.IMPROVEMENTS_36,interior:ca.IMPROVEMENTS_36,vehicleStorage:ca.SUBJECT_PROPERTY_36,amenities:ca.SUBJECT_PROPERTY_36}[et];hs!==void 0&&hs!==-1&&((et==="amenities"||et==="vehicleStorage")&&r(et),et==="improvements"&&pa&&/^(bldg|unit):/.test(pa)&&i(pa),a(hs),window.scrollTo(0,0))},focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"atAGlance"),Ea&&_s("assignment_36",jt,!0,e.jsx(wo,{stepName:"Assignment (URAR 3.6)",children:e.jsx(IX,{orderId:b||"new",isActive:jt,focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"assignment"),Ea&&_s("subject_property_36",Et,!0,e.jsx(wo,{stepName:"Subject Property (URAR 3.6)",children:e.jsx(EX,{orderId:b||"new",isActive:Et,focusSection:s,onFocusSectionHandled:()=>r(void 0),focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"subjectProperty"),Ea&&_s("site_36",ka,!0,e.jsx(wo,{stepName:"Site (URAR 3.6)",children:e.jsx(CX,{orderId:b||"new",isActive:ka,focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"site"),Ea&&_s("improvements_36",Yt,!0,e.jsx(wo,{stepName:"Improvements (URAR 3.6)",children:e.jsx(RX,{orderId:b||"new",isActive:Yt,focusSection:n,onFocusSectionHandled:()=>i(void 0),focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"improvements"),hu&&_s("sales_contract_36",ha,!0,e.jsx(wo,{stepName:"Sales Contract (URAR 3.6)",children:e.jsx(wX,{orderId:b||"new",isActive:ha,focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"salesContract"),Zc&&_s("project_information_36",Rt,!0,e.jsx(wo,{stepName:"Project Information (URAR 3.6)",children:e.jsx(PX,{orderId:b||"new",isActive:Rt,focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"projectInformation"),wn&&_s("listing_sale_history_36",Bt,!0,e.jsx(wo,{stepName:"Listing & Sale History (URAR 3.6)",children:e.jsx(DX,{orderId:b||"new",forceListed:fm===!0||fm==="true",forcePrior:gm===!0||gm==="true",isActive:Bt,focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"listingSaleHistory"),Ea&&_s("market_36",Jt,!0,e.jsx(wo,{stepName:"Market (URAR 3.6)",children:e.jsx(OX,{orderId:b||"new",isActive:Jt,focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"market"),Ed&&_s("cost_approach_36",gt,!0,e.jsx(wo,{stepName:"Cost Approach (URAR 3.6)",children:e.jsx(LX,{orderId:b||"new",stepTitle:Tp,useCostApproach:ti.approaches.useCostApproach.checked,useSiteValuation:ti.approaches.useSiteValuation.checked,isActive:gt,focusRequest:l,onFocusRequestHandled:()=>c(void 0)})}),"costApproach"),_s("order",Ra,!1,zu?e.jsx(wo,{stepName:"Order 3.6 (Marivic)",children:e.jsx(jX,{orderId:b||"new"})}):e.jsx(wo,{stepName:"Order Snapshot",children:e.jsx(pY,{data:se,setData:fe,mlsListingData:lm,mlsLookupNoListing:cm,documents:ue,onDocumentsChange:be,orderId:b||void 0,inspectionCaptured:Bb(ii),evalStyle:Ir&&!Ea})})),$g&&e.jsxs("div",{className:"flex items-start gap-2 px-4 py-2.5 bg-blue-50 border-b border-blue-200 text-[11px] text-blue-800","data-testid":"profile-change-banner",children:[e.jsx("span",{className:"flex-1",children:$g}),e.jsx("button",{onClick:()=>qu(null),className:"text-blue-500 hover:text-blue-700 shrink-0 font-semibold","data-testid":"btn-dismiss-profile-banner",children:"✕"})]}),_s("subject_site",fa,!1,e.jsx(wo,{stepName:"Subject Site",children:e.jsx(E6,{data:H,setData:ye,history:Be,address:se.subjectAddress?.value||"",occupancy:de,setOccupancy:ge,subjectAddress:se.subjectAddress?.value||"",prefetchedZoningData:Fi,prefetchedZoningScreenshot:Vu,prefetchedZoningLoading:bo,prefetchedZoningError:ou,onRetryZoning:ih,femaPanelLookupStatus:bp,femaRefreshing:ru,onRefreshFema:om,overrideLog:Ie,onOverrideLogged:et=>ce(pa=>[...pa,et]),persistedLocalFields:Pe,onLocalFieldsChange:We,onResetOverrideLog:()=>ce([]),inspectionUpdatedAt:ii?.timestamp||ii?.payload?.timestamp||ii?.createdAt||null,inspectionCaptured:Bb(ii),appId:C?.order?.appId,hasSalesContract:!!(se.contractDate?.value||se.contractPrice?.value),profile:Rd,orderId:b||void 0,enableUad36:Ea,marketLocationType:Ot.neighborhoodGrid?.location,inspectionSiteData:Ke})})),xr&&_s("str_subject",t===ca.STR_SUBJECT,!1,e.jsx(wo,{stepName:"STR Subject",children:e.jsx(B6,{data:H,setData:ye,orderId:b||void 0,inspectionCaptured:Bb(ii)})})),Wi&&_s("comp_intent",Is,!1,e.jsx(wo,{stepName:"Comp Intent",children:e.jsx(RJ,{inspectionImport:ii,subjectAddress:se.subjectAddress?.value||"",subjectState:Jn,subjectCity:vn,subjectZip:Ei,subjectData:hq(H),propertyData:H,propMixData:Hi||void 0,subjectPhotos:mr,subjectCoordinates:Os,initialIntent:ot,csvSubjectValues:Bn,externalSelectionEdits:rs??void 0,onSave:xa,showVerifyButton:Zs.includes("avm")||Ea,onVerifyComplete:et=>{const pa=rW(Ps.current.verifiedSubject,et);Ps.current={...Ps.current,verifiedSubject:pa},ls.current=!0,yd(pa)},onRegisterUnloadFlush:mn,isVerified:Ri!==null,activeAddOns:Zs,enableDualScenario:$a,afterRepairedSubject:Zo,onAfterRepairedSubjectChange:Tg,renovationState:Xp,onRenovationStateChange:ni,subjectQCLoading:Ao.isAnalyzing,orderId:b||void 0,enableUad36:Ea,isActive:Is,step2SiteGridSeed:ft})})),Wi&&_s("property_lab",P,!0,e.jsxs(e.Fragment,{children:[!qc.current&&P&&e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"relative z-50 flex items-center gap-2 px-4 py-2.5 border-b border-slate-200 bg-white","data-testid":"property-lab-lock-skeleton-toolbar",children:[e.jsxs("div",{className:Q("flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium",ki?"bg-[#D0FAE5] text-emerald-900":"bg-slate-100 text-slate-500"),"data-testid":"skeleton-chip-market-lock",children:[ki?e.jsx(Hr,{className:"h-3.5 w-3.5"}):e.jsx(Ql,{className:"h-3.5 w-3.5"}),ki?"Market Locked":"Market"]}),e.jsxs("div",{className:Q("flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium",Ol?"bg-[#D0FAE5] text-emerald-900":"bg-amber-50 text-amber-700/70"),"data-testid":"skeleton-chip-submarket-lock",children:[Ol?e.jsx(Hr,{className:"h-3.5 w-3.5"}):e.jsx(Ql,{className:"h-3.5 w-3.5"}),Ol?"Sub-Market Locked":"Sub-Market"]}),e.jsxs("span",{className:"ml-2 flex items-center gap-1.5 text-xs text-slate-400",children:[e.jsx(za,{className:"h-3 w-3 animate-spin"}),"Loading Property Lab…"]})]}),!Ia&&e.jsx("div",{className:"flex-1 flex items-center justify-center text-slate-500 text-sm","data-testid":"property-lab-restoring",children:"Restoring your map state…"})]}),qc.current&&e.jsx(wo,{stepName:X?Ms("Sales Grid"):"Property Lab",orderId:b||void 0,context:()=>({currentStep:t,hasSubject:!!Os,cleanupMode:_c}),children:e.jsx(gJ,{inspectionImport:ii,propertyData:H,subjectAddress:se.subjectAddress?.value||"",subjectCoordinates:Os,assignmentId:b||void 0,effectiveDate:se.effectiveDate?.value||"",subjectState:Jn,subjectZipCode:Ei,subjectPropertyType:Hi?.propertyDetails?.propertyType||Hi?.listingDetails?.propertyType,subjectProviderData:
53Hi,onBack:Ca,onNext:ia,onProceedToCleanup:et=>{re(pa=>({...pa,selectedUsed:et}))},onCleanedCompsChange:et=>{console.log("[Wizard] Received cleanedComps from PropertyLab:",et.length),Ze(et)},onCleanupModeChange:et=>{bd(et)},onCsvSubjectImport:et=>{Ka(pa=>({...pa,...et}))},onNeighborhoodInfoChange:et=>{(et.boundaries||et.description||et.marketConditions)&&_e(pa=>({...pa,neighborhoodGrid:{...Qz,...pa.neighborhoodGrid||{},neighborhoodBoundaries:et.boundaries||pa.neighborhoodGrid?.neighborhoodBoundaries||"",neighborhoodDescription:et.description||pa.neighborhoodGrid?.neighborhoodDescription||"",marketConditions:et.marketConditions||pa.neighborhoodGrid?.marketConditions||""}}))},onNeighborhoodAiGenerated:tt,initialNeighborhoodInfo:Ot.neighborhoodGrid?{boundaries:Ot.neighborhoodGrid.neighborhoodBoundaries||"",description:Ot.neighborhoodGrid.neighborhoodDescription||"",marketConditions:Ot.neighborhoodGrid.marketConditions||"",aiGenerated:sa||!!(Ot.neighborhoodGrid.neighborhoodBoundaries&&Ot.neighborhoodGrid.neighborhoodDescription)}:void 0,compIntentState:ot,boostItems:ln,onApplyBoostItems:et=>{go(et),b&&Lh(b,{boostWeights:OZ(et)})},onSaveBoostDefault:async et=>{if(h?.id)try{const pa=await fetch(`/api/profile/${h.id}/defaults`,{credentials:"include"});if(!pa.ok)throw new Error(`HTTP ${pa.status}`);const hs=(await pa.json())?.defaults||{},qr="property-lab-match-default",ys=BS(et),yr=Za=>ys.weightOverrides[Za]||0,Yr={id:qr,name:"Property Lab Match",boostCriteria:ys.priorities,baselineWeights:{proximity:yr("proximity"),gla:yr("gla"),els:yr("els"),bedsBaths:yr("bedsBaths")},weightOverrides:ys.weightOverrides},Ge=Array.isArray(hs.weightPresets)?hs.weightPresets:[],bt=await fetch(`/api/profile/${h.id}/defaults`,{method:"PUT",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({...hs,weightPresets:[...Ge.filter(Za=>Za?.id!==qr),Yr],defaultWeightPresetId:qr})});if(!bt.ok)throw new Error(`HTTP ${bt.status}`);xd.current=Yr,m({title:"Match default saved",description:"New eligible orders will use these priorities."})}catch(pa){console.error("[Wizard] Failed to save boost weights:",pa),m({title:"Could not save default",description:"Your order settings were not changed.",variant:"destructive"})}},onResetBoostItems:()=>qj(xd.current||bs),enableStr:gu,enableUad36:Ea,evalGridProfile:Ir&&!Ea,evalCompGridRows:Ir&&!Ea?It:void 0,evalSubjectVehicleStorageItems:Ir&&!Ea?Ue:void 0,evalSubjectVehicleStorageExplicitNone:Ir&&!Ea?xt:void 0,evalSubjectVehicleStorageLegacyLabel:Ir&&!Ea?qt:void 0,evalSubjectVehicleStorageHasLegacyOverride:Ir&&!Ea?fs:void 0,onEvalSubjectVehicleStorageEvidenceChange:yt,evalCustomComparisonFactors:Ir&&!Ea?Wt:void 0,onEvalCustomComparisonFactorsChange:Ir&&!Ea?et=>Va.current?.(et):void 0,moduleDefaultFilters:Ir?hz:void 0,subjectPhotos:mr,initialSelectedComps:pt.selectedUsed,initialAvmResults:In,onAvmResultsChange:Yn,initialSelectedAvmComps:Qa,onSelectedAvmCompsChange:Xi,initialVerifiedSubject:Ri,onVerifiedSubjectChange:yd,initialMarketLocked:ki,onMarketLockedChange:fp,initialSubMarketLocked:Ol,onSubMarketLockedChange:$m,initialLocksRow:Ig,onLockDataChanged:Sd,initialSubMarketPropertyIds:ml,onSubMarketPropertyIdsChange:Rg,enableDualScenario:$a,initialCompScenarioTags:hl,onCompScenarioTagsChange:ff,initialAfterRepairedOverrides:Zo,onOpenSubjectDrawer:()=>xf(!0),persistedGridAdjustments:Ks,onGridAdjustmentChange:(et,pa,Gt)=>{if(Tn(hs=>{const qr=hs[et];if(Gt===null){if(!qr||!(pa in qr))return hs;const ys={...qr};if(delete ys[pa],Object.keys(ys).length===0){const yr={...hs};return delete yr[et],yr}return{...hs,[et]:ys}}return{...hs,[et]:{...qr||{},[pa]:Gt}}}),Ir&&!Ea){const hs=tX(pa);if(hs){const qr=qe.find(ys=>ys.compId===et||ys.mlsNumber===et||ys.id===et);gs.current?.({identity:{compId:et,mlsNumber:qr?.mlsNumber,address:qr?.address},fieldName:hs,value:Gt===null?"":Gt})}}},onGridCompFieldEdit:(et,pa,Gt,hs,qr,ys)=>{const yr=kY(pa),Yr=[...UY(pa,Gt),...VY(pa,Gt)];if(Ir&&!Ea&&gs.current?.({identity:hs??{compId:et},fieldName:Ew(pa),value:Gt,source:qr,alternatives:Object.entries({...ys??{},...qr?{[qr]:Gt}:{}}).filter(ra=>ra[1]!==null&&ra[1]!==void 0&&(ra[1]!==""||ra[0]===qr)).map(([ra,ta])=>({source:ra,value:ta}))}),!yr&&Yr.length===0)return;let bt=(so.length>0?so:qe).findIndex(ra=>ra.compId===et);if(bt<0&&(bt=(pt?.selectedUsed||[]).findIndex(ta=>ta?.id===et||ta?.snapshotId===et)),bt<0||bt>2)return;const Za={};yr&&(Za[Wo(bt+1,yr)]=String(Gt));for(const ra of Yr)Za[Wo(bt+1,ra.gridKey)]=ra.value;ir(ra=>{let ta=!1;for(const[Mt,ms]of Object.entries(Za))if(ra[Mt]!==ms){ta=!0;break}return ta?{...ra,...Za}:ra})},onSubjectGridFieldEdit:(et,pa,Gt)=>{if(Ir&&!Ea&&(et==="neighborhoodName"||et==="NeighborhoodName")){const ys=Gt==="MLS"||Gt==="PublicRecord"||Gt==="AI"||Gt==="User"?Gt:"User",yr=ys==="MLS"?"mls":ys==="PublicRecord"?"public_record":ys==="User"?"user":null;ye(Yr=>({...Yr,neighborhoodName:{...Yr.neighborhoodName||{},value:String(pa),source:ys,isEdited:!0,alternatives:{...Yr.neighborhoodName?.alternatives||{},...yr?{[yr]:String(pa)}:{}}}}))}if(Ir&&!Ea&&et==="aboveGrade"){const ys=String(pa).trim().split("|"),yr=ys.length===3?String(ys[2]).trim().split("."):[],Yr=yr.length>0&&yr[0]!==""?Number(yr[0]):void 0,Ge=yr.length>1&&yr[1]!==""?Number(yr[1]):ys.length===3?0:void 0;if((Yr===void 0||Number.isFinite(Yr))&&(Ge===void 0||Number.isFinite(Ge))&&(Yr===void 0||Yr>=0)&&(Ge===void 0||Ge>=0)){const bt=Gt==="MLS"||Gt==="PublicRecord"?Gt:"User",Za=bt==="PublicRecord"?"public_record":"mls";ye(ra=>{const ta=(Mt,ms)=>({...Mt||{},value:ms===void 0?"":String(ms),source:bt,isEdited:!0,alternatives:{...Mt?.alternatives||{},...ms===void 0?{}:{[Za]:String(ms)}}});return{...ra,fullBaths:ta(ra.fullBaths,Yr),halfBaths:ta(ra.halfBaths,Ge),bathrooms:{...ra.bathrooms||{},value:Yr===void 0?"":String(Yr+(Ge??0)*.5),source:bt,isEdited:!0}}}),gs.current?.({identity:{compId:"subject"},fieldName:"fullBathrooms",value:Yr??""}),gs.current?.({identity:{compId:"subject"},fieldName:"halfBathrooms",value:Ge??""}),gs.current?.({identity:{compId:"subject"},fieldName:"baths",value:Yr==null?"":Yr+(Ge??0)*.5})}}if(Ir&&!Ea&&["heatingCooling","garageCarport","garageParking","porchPatioDeck","design","de
53signStyle","neighborhoodName","NeighborhoodName","VehicleStorageItems","location","locationComparison","locationType","siteLocationType","neighborhoodClassification","siteInfluence","SiteInfluenceType","attachmentType","attachedDetached","AttachmentType","AttachedDetached"].includes(et)&&gs.current?.({identity:{compId:"subject"},fieldName:Ew(et),value:pa,source:Gt,...et==="neighborhoodName"||et==="NeighborhoodName"?{source:Gt,alternatives:Object.entries({...H.neighborhoodName?.alternatives??{},...Gt==="MLS"?{mls:pa}:Gt==="PublicRecord"?{public_record:pa}:Gt==="User"?{user:pa}:{}}).filter(ys=>ys[1]!==null&&ys[1]!==void 0&&(ys[1]!==""||Gt==="MLS"&&ys[0]==="mls"||Gt==="PublicRecord"&&ys[0]==="public_record"||Gt==="User"&&ys[0]==="user")).map(([ys,yr])=>({source:ys==="public_record"?"PublicRecord":ys==="mls"?"MLS":ys==="user"?"User":ys,value:yr}))}:{}}),et==="leaseholdFeeSimple"){ye(ys=>({...ys,estateType:{...ys.estateType||{},value:String(pa),source:"User",isEdited:!0}}));return}const{verifySelections:hs}=XT(et,pa),qr=Object.keys(hs);qr.length>0&&xa(ys=>{const yr={...ys.fieldSelections||{}};for(const Yr of qr)yr[Yr]={...yr[Yr]||{},selectedSource:"manual",manualValue:hs[Yr]};return{...ys,fieldSelections:yr}})},initialCachedLabState:Gn.current,lateElsCache:co?.elsCache,lateCompAiCache:co?.compAiCache,lateAllCachedSales:co?.allCachedSales,cachesPending:z.has(`cachedLabStateCache__user_${h?.id??""}`),onLabStateChange:et=>{Gn.current=et,On(et)},onRequestImmediateSave:ui,strRentalComps:Sc,onMapSnapshotChange:dt,onRegisterActions:em,onAvmLoadingChange:xb,onLockedTimeAdjRateChange:Vc,onMarketPropertiesUpdate:Sa,onSubmarketPropertiesUpdate:ea,headerSearchQuery:Zt,wizardPreloadStatus:rl,wizardIsPreloading:Hu,wizardPreloadComplete:_i,wizardPreloadIsReady:Nf,maxSalesComps:24,initialCleanupMode:X})})]})),sh&&_s("leasehold",xe,!1,e.jsx(wo,{stepName:"Leasehold",children:e.jsx(Q2,{children:e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex-shrink-0 bg-white border-b px-6 py-2 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-slate-700",children:"Land Lease"}),e.jsx("div",{className:"h-4 w-px bg-slate-200"}),e.jsxs("span",{className:"text-xs text-slate-500",children:["Step ",t-ca.LEASE_SUMMARY+1," of 5"]})]}),e.jsx(Z2,{})]}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[t===ca.LEASE_SUMMARY&&e.jsx(uX,{subjectAddress:se.subjectAddress?.value||"",subjectData:{beds:void 0,sqft:void 0,yearBuilt:H.yearBuilt?.value?parseInt(String(H.yearBuilt.value)):void 0},initialData:$r.leaseTerms,loanTermYears:30,selectedAgency:tl,onAgencyChange:to,onSave:et=>Mi(pa=>({...pa,leaseTerms:et})),onBack:Ca,onNext:ia,uploadedPdfInfo:$r.uploadedPdfInfo,onPdfInfoChange:et=>Mi(pa=>({...pa,uploadedPdfInfo:et}))}),t===ca.AGENCY_CHECK&&$r.leaseTerms&&e.jsx(pX,{leaseTerms:$r.leaseTerms,loanTermYears:30,selectedAgency:tl,onAgencyChange:to,onBack:Ca,onNext:ia}),t===ca.CALCULATOR&&$r.leaseTerms&&e.jsx(mX,{leaseTerms:$r.leaseTerms,loanTermYears:30,selectedAgency:tl,onAgencyChange:to,initialDiscountRate:$r.discountRateSetup,initialCalculationType:$r.calculationType,initialIncomeCapCalc:$r.incomeCapCalculation,initialPVCalc:$r.pvCalculation,onLeaseTermsUpdate:et=>{Mi(pa=>({...pa,leaseTerms:pa.leaseTerms?{...pa.leaseTerms,...et}:null}))},onSave:(et,pa,Gt,hs)=>{Mi(qr=>({...qr,calculationType:et,discountRateSetup:pa,incomeCapCalculation:Gt,pvCalculation:hs}))},onBack:Ca,onNext:ia}),t===ca.RIGHTS_ADJUST&&e.jsx(hX,{selectedComps:pt.selectedUsed.map(et=>({id:et.id,address:et.address,salePrice:et.price,indicatedValue:et.price})),calculatedRightsAdjustment:$r.calculationType==="IncomeCapRightsAdjustment"?$r.incomeCapCalculation?.rightsAdjustment||0:$r.pvCalculation?.leasedFeeValue||0,initialAdjustments:$r.compAdjustments,leaseTerms:$r.leaseTerms,loanTermYears:30,selectedAgency:tl,onAgencyChange:to,onSave:et=>Mi(pa=>({...pa,compAdjustments:et})),onBack:Ca,onNext:ia}),t===ca.ADDENDUM&&$r.leaseTerms&&e.jsx(fX,{subjectAddress:se.subjectAddress?.value||"",leaseTerms:$r.leaseTerms,calculationType:$r.calculationType,leasedFeeValue:$r.calculationType==="IncomeCapRightsAdjustment"?$r.incomeCapCalculation?.rightsAdjustment||0:$r.pvCalculation?.leasedFeeValue||0,compAdjustments:$r.compAdjustments,reportFragments:$r.reportFragments,finalLeaseholdValue:$r.finalLeaseholdValue,loanTermYears:30,selectedAgency:tl,onAgencyChange:to,onUpdateFragment:(et,pa)=>Mi(Gt=>({...Gt,reportFragments:{...Gt.reportFragments,[et]:pa}})),onUpdateFinalValue:et=>Mi(pa=>({...pa,finalLeaseholdValue:et})),onGenerateNarrative:async()=>{try{const pa=await(await fetch("/api/leasehold/ai/generate-narrative",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({leaseTerms:$r.leaseTerms,calculationType:$r.calculationType,leasedFeeValue:$r.calculationType==="IncomeCapRightsAdjustment"?$r.incomeCapCalculation?.rightsAdjustment:$r.pvCalculation?.leasedFeeValue,compAdjustments:$r.compAdjustments})})).json();pa.success&&Mi(Gt=>({...Gt,reportFragments:{...Gt.reportFragments,...pa.fragments}}))}catch(et){console.error("Failed to generate narrative:",et)}},onBack:Ca,onComplete:()=>{m({title:"Leasehold Analysis Complete",description:"You can now proceed to the final review."}),ia()}})]})]})})})),gu&&_s("str",cs,!1,e.jsx(wo,{stepName:"STR",children:e.jsx(_$,{onNavigateNext:()=>a(et=>Math.min(et+1,Pn.length-1)),onNavigatePrev:()=>a(et=>Math.max(et-1,0)),initialSubject:Qc,initialComps:Dl.comps,orderId:b||void 0,subjectSourceOrderId:Qc?._sourceOrderId,compsSourceOrderId:Dl._sourceOrderId,children:e.jsx(YX,{externalStep:Zd,onStateChange:ym})})})),Ir&&_s("eval",br,!0,e.jsx(wo,{stepName:"Evaluation",children:e.jsx(NX,{subjectAddress:se.subjectAddress?.value||"",subjectState:Jn,subjectDetails:jf,subjectFactSources:Tf,subjectPhotos:mr,marketLabState:Ot,cleanedComps:qe,latitude:Os?.lat,longitude:Os?.lng,orderId:Re||b||void 0,corePropertyData:IO({propertyData:H,orderData:se,historyData:Be,propMixData:Hi}),clientName:se.lenderName?.value||se.client?.value||"",effectiveDate:se.effectiveDate?.value||"",appraiserName:se.appraiser?.value||"",appraiserLicense:se.appraiserLicense?.value||h?.licenseNumber||"",appraiserLicenseState:h?.licenseState||Jn,appraiserCompany:se.appraiserCompany?.value||h?.companyName||"",appraiserEmail:h?.email||"",appraiserPhone:h?.phone||"",zoningClassification:Jc.zoningClassification?.value||"",zoningDescription:Jc.zoningDescription?.value||"",zoningClassificationSource:Jc.zoningClassification?.source,zoningDescriptionSource:Jc.zoningDescription?.source,zoningCompliance:Jc.zoningCompliance?.value||"",zoningScreenshotUrl:Vu?.imageBase64||Vu?.imageUrl,zoningScreenshotAddress:Hm,intendedUser:C?.order?.intakeExtras?.intendedUser||"",intendedUse:C?.order?.appraisalPurpose||"",inspectorName:C?.order?.intakeExtras?.inspectorName||"",occupancyType:de||C?.order?.occupancyStatus||"",ownerOfRecord:se.owner?.value||"",inspectionType:"Desktop",inspectionDate:"",compsMapSnapshot:Ee,selectedTemplateId:Mg,gridAdjustments:Ks,orderStatus:C?.order?.status||"",reportLabel:P2("eval"),evalMarketChartImages:Object.keys($t).length>0?$t:void 0,onBack:()=>a(et=>Math.max(et-1,0)),onComplete:()=>{m({title:"Evaluation Report Complete",description:"EVAL export complete."})}})})),ac!==-1&&_s("review",zr,!1,e.jsx(wo,{stepName:"Review",children:e.jsx(IG,{orderData:se,propertyData:Jc,setPropertyData:ye,occupancy:de,conflictCount:nh(),selectedComps:qe.map(et=>{const pa=Gt=>et.cleanedFields.find(qr=>qr.fieldKey===Gt)?.finalValue;return{id:et.compId,address:et.address,salePrice:et.price,dateOfSale:pa("saleDate"),location:et.locationComparison||"
53N;Res",view:et.viewComparison||"N;Res",quality:et.quality,condition:et.condition,gla:et.gla,bedrooms:et.beds,bathrooms:et.baths,garageSpaces:pa("garageSpaces"),lotSize:pa("lotSize"),yearBuilt:pa("yearBuilt"),basement:pa("basement"),mlsNumber:et.mlsNumber}}),marketLabState:Ot,isTdcxExpress:Bu,inspectionCaptured:Bb(ii),onGenerate:async()=>{try{const et=ta=>ta?.value!=null?String(ta.value):"",pa=ta=>ta?.value??null,Gt=Jc,hs=se,qr={order:{subjectAddress:et(hs.subjectAddress),city:vn||"",state:Jn||"",zip:Ei||"",county:et(Gt.county),borrower:et(hs.borrower),coBorrower:et(hs.coBorrower),lender:et(hs.lender),client:et(hs.client),appraiser:et(hs.appraiser),appraiserEmail:"",appraiserLicense:et(hs.appraiserLicense),appraiserLicenseExpiration:et(hs.appraiserLicenseExpiration),appraiserLicenseType:et(hs.appraiserLicenseType),loanNumber:et(hs.loanNumber),fhaVaNumber:et(hs.fhaVaNumber),effectiveDate:et(hs.effectiveDate),owner:et(hs.owner),occupancy:de,form:et(hs.form),assignmentType:et(hs.assignmentType),purpose:et(hs.purpose),contractPrice:et(hs.contractPrice),contractDate:et(hs.contractDate),offeredForSale:pa(hs.offeredForSale),offeredForSaleDataSource:et(hs.offeredForSaleDataSource),offeredForSaleMlsNumber:et(hs.offeredForSaleMlsNumber),offeredForSalePrice:et(hs.offeredForSalePrice),offeredForSaleListDate:et(hs.offeredForSaleListDate),sellerOwnerOfRecord:pa(hs.sellerOwnerOfRecord),contractAnalyzed:pa(hs.contractAnalyzed),contractAnalysisExplanation:et(hs.contractAnalysisExplanation),financialAssistance:pa(hs.financialAssistance),financialAssistanceAmount:et(hs.financialAssistanceAmount),financialAssistanceDescription:et(hs.financialAssistanceDescription)},property:{neighborhoodName:et(Gt.neighborhoodName),pinNumber:et(Gt.pinNumber),legalDescription:et(Gt.legalDescription),censusTract:et(Gt.censusTract)||et(Gt.tract),mapReference:et(Gt.mapReference)||et(Gt.plat),taxYear:et(Gt.taxYear),taxes:et(Gt.taxes),yearBuilt:et(Gt.yearBuilt),pud:et(Gt.pud),hoaFees:et(Gt.hoaFees),hoaFeeFrequency:et(Gt.hoaFeeFrequency),zoningClassification:et(Gt.zoningClassification),zoningDescription:et(Gt.zoningDescription),zoningCompliance:et(Gt.zoningCompliance),highestBestUse:Gt.highestBestUse?.value??!0,highestBestUseExplanation:et(Gt.highestBestUseDescription),county:et(Gt.county),lotSize:et(Gt.lotSize),lotDimensions:et(Gt.lotDimensions),stories:et(Gt.stories),designStyle:et(Gt.designStyle),totalRooms:et(Gt.totalRooms),bedrooms:et(Gt.bedrooms),fullBaths:et(Gt.fullBaths),halfBaths:et(Gt.halfBaths),gla:et(Gt.gla),basementArea:et(Gt.basementArea),basementFinish:et(Gt.basementFinish),heatingType:et(Gt.heatingType),heatingFuel:et(Gt.heatingFuel),coolingType:et(Gt.coolingType),garageType:et(Gt.garageType),garageCars:et(Gt.garageCars),drivewaySurface:et(Gt.drivewaySurface),foundationWalls:et(Gt.foundationWalls),exteriorWalls:et(Gt.exteriorWalls),roofSurface:et(Gt.roofSurface),guttersDownspouts:et(Gt.guttersDownspouts),windowType:et(Gt.windowType),stormSash:et(Gt.stormSash),screens:et(Gt.screens),interiorFloors:et(Gt.interiorFloors),interiorWalls:et(Gt.interiorWalls),trimFinish:et(Gt.trimFinish),bathFloor:et(Gt.bathFloor),bathWainscot:et(Gt.bathWainscot),femaFloodZone:et(Gt.femaFloodZone),femaMapNumber:et(Gt.femaMapNumber),femaMapDate:et(Gt.femaMapDate),electricityType:et(Gt.electricityType),gasType:et(Gt.gasType),waterType:et(Gt.waterType),sanitarySewerType:et(Gt.sanitarySewerType),streetType:et(Gt.streetType),streetSurface:et(Gt.streetSurface),effectiveAge:et(Gt.effectiveAge),quality:et(Gt.quality),condition:et(Gt.condition),actualAge:et(Gt.actualAge),location:et(Gt.location),view:et(Gt.view)},history:Be?.map(ta=>({date:ta.date,price:ta.price,type:ta.type,source:ta.source}))||[]},ys=await fetch("/api/reports/tdcx",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(qr)});if(!ys.ok)throw new Error("Failed to generate TDCX file");const yr=await ys.blob(),Ge=(ys.headers.get("Content-Disposition")||"").match(/filename="?(.+?)"?$/),bt=Ge?Ge[1]:"report.tdcx",Za=window.URL.createObjectURL(yr),ra=document.createElement("a");ra.href=Za,ra.download=bt,document.body.appendChild(ra),ra.click(),window.URL.revokeObjectURL(Za),ra.remove(),m({title:"Success",description:"TOTAL File (.tdcx) downloaded! Double-click to open in TOTAL."})}catch(et){console.error("TDCX generation error:",et),m({title:"Error",description:"Failed to generate TOTAL file. Please try again.",variant:"destructive"})}},onNavigateToStep:et=>{a(et),window.scrollTo(0,0)},enableBridgeValue:$a,bridgeValues:vd,onBridgeValuesChange:gf,bridgeAsIsPrefill:yc.asIs?.mid??null,bridgeAfterRepairedPrefill:yc.afterRepaired?.mid??null,onGenerateBridgePdf:async()=>{try{const et=CG(Re,b);if(!et){const ms=hj("no-id");
53m({title:ms.title,description:ms.description,variant:"destructive"});return}const pa=ms=>ms?.value!=null?String(ms.value):"",Gt=Jc,qr=[pa(se.subjectAddress),[vn,Jn,Ei].filter(Boolean).join(", ")].filter(Boolean),ys=Xp?.analysis,yr={orderId:et,subjectAddress:qr.join(", "),subjectPhotoUrl:mr&&mr.length>0?mr[0]:null,subjectBeds:Gt.bedrooms?.value!=null?Number(Gt.bedrooms.value):null,subjectBaths:Gt.fullBaths?.value!=null?Number(Gt.fullBaths.value):null,subjectGla:Gt.gla?.value!=null?Number(Gt.gla.value):null,asIsValue:vd.asIs.trim()!==""?Number(vd.asIs):null,afterRepairedValue:vd.afterRepaired.trim()!==""?Number(vd.afterRepaired):null,asIsRangeLow:yc.asIs?.low??null,asIsRangeHigh:yc.asIs?.high??null,afterRepairedRangeLow:yc.afterRepaired?.low??null,afterRepairedRangeHigh:yc.afterRepaired?.high??null,asIsComps:wi("as-is"),afterRepairedComps:wi("after-repaired"),rehabSummary:ys?.summary??null,rehabTotalCost:ys?.totalCost??null,rehabScopeItems:Array.isArray(ys?.scopeItems)?ys.scopeItems.map(ms=>({description:ms.description,cost:ms.cost??null,category:ms.category??null})):[],reconciliationCommentary:vd.commentary.trim()!==""?vd.commentary:null},Yr=await fetch("/api/bridge-value/report",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(yr)});if(!Yr.ok){const ms=hj(Yr.status);m({title:ms.title,description:ms.description,variant:"destructive"});return}const Ge=await Yr.blob(),Za=(Yr.headers.get("Content-Disposition")||"").match(/filename="?(.+?)"?$/),ra=Za?Za[1]:"bridge-value.pdf",ta=window.URL.createObjectURL(Ge),Mt=document.createElement("a");Mt.href=ta,Mt.download=ra,document.body.appendChild(Mt),Mt.click(),window.URL.revokeObjectURL(ta),Mt.remove(),m({title:"Success",description:"Bridge Value report (PDF) downloaded."})}catch(et){console.error("Bridge Value generation error:",et);const pa=hj("network");m({title:pa.title,description:pa.description,variant:"destructive"})}}})}))]})})()})}),Qi&&e.jsxs("footer",{inert:du||void 0,className:"h-[36px] bg-slate-50 border-t border-slate-200 flex items-center justify-between px-6 shrink-0 mt-auto","data-testid":"wizard-footer",children:[e.jsxs("div",{className:"flex items-center gap-3 text-[12px] font-medium text-slate-400",children:[Zr.map((P,X)=>e.jsx("div",{className:Q("w-[6px] h-[6px] rounded-full",P.status==="current"?"bg-[#C5A572]":P.status==="done"?"bg-green-400":"bg-slate-300"),title:Ms(P.name)},X)),e.jsx("span",{className:"ml-1 text-slate-400",children:Ms(Pn[t])}),e.jsx(Oq,{orderId:b,hydrationPending:V||D,recentlySaved:au==="saved"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(T?t>ca.ADDRESS:t>ca.ORDER)&&e.jsx("button",{onClick:Ca,disabled:w,className:"px-4 py-1 text-[12px] font-medium text-slate-600 hover:bg-slate-200 rounded transition-colors disabled:opacity-50 disabled:pointer-events-none","data-testid":"button-back",children:"Back"}),e.jsxs("button",{onClick:ia,disabled:w,className:"px-4 py-1 text-[12px] font-medium bg-[#072034] text-white hover:bg-[#0a2f4c] rounded shadow-sm transition-colors flex items-center gap-1.5 disabled:opacity-60 disabled:pointer-events-none","data-testid":"button-next",children:[w&&e.jsx(za,{size:13,className:"animate-spin","data-testid":"button-next-spinner"}),Wi&&t===ca.COMP_INTENT?"Continue to Property Lab":t+1<Pn.length?`Next: ${Ms(Pn[t+1])}`:"Next",e.jsx(fo,{size:14})]})]})]})]}),Ea&&e.jsx(ME,{readOnly:du,"data-testid":"wizard-urar-rail-pane",className:Q("h-full min-h-0 shrink-0 flex flex-col bg-white",du&&"select-none opacity-50"),children:e.jsx(LJ,{orderId:b||"new",onLockConflict:()=>{_g()},onJumpToField:P=>{const[X,...xe]=P.split("."),Ye=xe.join("."),ke=UT(X)??X,jt=sc.find(Et=>Et.sectionId===ke);!jt||jt.stepIndex===-1||(yl.current+=1,c({sectionId:X,fieldName:Ye,nonce:yl.current,ownerSectionId:jt.sectionId}),a(jt.stepIndex))}})})]}),e.jsx(jT,{property:Wn,open:No,onClose:()=>gp(!1),isSubject:!0,orderId:b,isPhotosLoading:Le&&mr.length===0,onRefreshPhotos:Jr}),e.jsx(s$,{open:_u,onClose:()=>xf(!1),address:se.subjectAddress?.value||"",orderData:se,subjectCoordinates:Os,historyData:Be,conditionRating:Ao?.condition??null,qualityRating:Ao?.quality??null,isAnalyzing
53CQ:Ao?.isAnalyzing??!1,elsScore:gl}),e.jsx(LY,{open:os,onClose:()=>ya(!1),formData:QY(HY(tr),qe),onFieldChange:(P,X)=>{const xe=ZY(P);ir(Ye=>{const ke={...Ye,[P]:X};if(xe)for(const jt of xe.gridPaths)ke[jt]=X;return ke})},formType:se.form?.value?`URAR ${se.form.value}`:"URAR Form 1004",orderId:b??void 0}),At&&e.jsx(o.Suspense,{fallback:null,children:e.jsx(gX,{open:At,onClose:()=>Fe(!1),strState:it.current??{currentStep:0,analysisId:null,assignmentId:b??null,intendedUser:"",intendedUse:"",assignmentDate:new Date().toISOString().split("T")[0],legalityStatus:null,legalityVerification:{jurisdiction:"",sourceUrl:"",dateVerified:"",verifiedBy:""},scopeAcknowledgements:{incomeAnalysisOnly:!1,notForm1007:!1,grossIncomeOnly:!1,excludesGoingConcern:!1,excludesFFE:!1},seasonalityAcknowledged:!1,competencyAcknowledged:!1,legalityAnswers:{permitStatus:null,conditionalRestrictions:"",permitTransfer:null,pendingLegislation:null,pendingLegislationNotes:""},legalityTextOverrides:{legalityParagraphOverride:null,eaLanguageOverride:null,regulatoryRiskOverride:null},marketConditions:{hbuConclusion:null,hbuRationale:"",marketType:null,demandSeasonality:null,demandDriver:null,demandDriverOther:"",demandDriverDetail:"",dataSourcesConsulted:[],dataReliabilityNotes:""},compAdjustments:{},ltrComps:[],ltrMonthlyRent:null,projectedAdr:null,projectedOccupancy:null,expenseRatio:40,seasonalityNarrative:"",dataDateRange:"",subject:{address:se.subjectAddress?.value||"",city:vn||void 0,state:Jn||void 0,zip:Ei||void 0,county:typeof H.county=="string"?H.county:H.county?.value||void 0,propertyType:H.propertyType?.value||void 0,bedrooms:H.bedrooms?.value?Number(H.bedrooms.value):void 0,bathrooms:H.bathrooms?.value?Number(H.bathrooms.value):void 0,gla:H.gla?.value?Number(String(H.gla.value).replace(/,/g,"")):void 0,yearBuilt:H.yearBuilt?.value?Number(H.yearBuilt.value):void 0,condition:H.condition?.value||void 0,zoning:H.zoningClassification?.value||void 0,parking:H.garage?.value||void 0},availableComps:[],selectedComps:[],adjustments:null,reconciliation:null,narratives:{ganrNarrative:"",occupancyNarrative:"",incomeNarrative:"",analysisNarrative:""},certification:{certifications:[],otherServicesPerformed:"",competencyAffirmed:!1,ethicsAffirmed:!1,dataReliabilityAffirmed:!1,scopeConfirmations:[],extraordinaryAssumptionConfirmed:!1,priorServicesAnswer:null,priorServicesDescription:"",customCertifications:null,customAssumptions:null},signature:null,status:"draft",isSaving:!1,lastSavedAt:null}})}),e.jsx(Vz,{open:vt,onClose:()=>Ve(!1),marketStats:Ot.marketStats,subMarketStats:Ot.subMarketStats,properties:Kt,subMarketProperties:Qt,subjectPrice:H.salePrice?.value?Number(H.salePrice.value):void 0,subjectYearBuilt:H.yearBuilt?.value?Number(H.yearBuilt.value):void 0,subjectGla:H.gla?.value?Number(H.gla.value):void 0,subjectBeds:H.bedrooms?.value?Number(H.bedrooms.value):void 0,subjectBaths:H.bathrooms?.value?Number(H.bathrooms.value):void 0,subjectLotSize:H.lotSize?.value?Number(String(H.lotSize.value).replace(/[^0-9]/g,"")):void 0,subjectListing:Nz(Hi?.listingDetails),reportFormType:uu,assignmentId:(ci||!Ea)&&b||void 0,analyticsState:Je,onAnalyticsStateChange:ci||!Ea?ht:void 0,neighborhoodAiGenerated:sa,onNeighborhoodAiGeneratedChange:ci||!Ea?tt:void 0,neighborhoodInfo:Ot.neighborhoodGrid?{boundaries:Ot.neighborhoodGrid.neighborhoodBoundaries||"",description:Ot.neighborhoodGrid.neighborhoodDescription||"",marketConditions:Ot.neighborhoodGrid.marketConditions||""}:void 0,onNeighborhoodInfoChange:ci||!Ea?P=>{_e(X=>({...X,neighborhoodGrid:{...X.neighborhoodGrid||{},neighborhoodBoundaries:P.boundaries,neighborhoodDescription:P.description,marketConditions:P.marketConditions}})),b&&fetch("/api/market-session/neighborhood-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({assignmentId:b,neighborhoodInfo:P})}).catch(X=>console.error("[Wizard] Failed to persist neighborhoodInfo:",X))}:void 0,subjectAddress:se.subjectAddress?.value||"",subjectCity:vn,subjectCounty:H.county?.value||void 0,subjectState:Jn,subMarketGeometry:Gn.current?{polygon:Gn.current.currentShapes?.polygons?.[0]||null,appliedBoundaries:Gn.current.appliedBoundaries,radiusMiles:Gn.current.labState?.marketDefinition?.radiusMiles,center:Os||void 0}:Os?{center:Os}:void 0,onApplyChartsToReport:Ea&&ci&&b?async P=>{try{const X=await fetch(`/api/uad36/prefill/${encodeURIComponent(b)}?skipExternal=true`,{credentials:"include"});if(!X.ok){console.error("[Market] chart apply: prefill fetch failed",X.status);return}const xe=await X.json(),Ye=xe?.sections??{},ke=Array.isArray(Ye?.market?.exhibitPhotos?.value)?Ye.market.exhibitPhotos.value:[],jt=kU(ke,P),Et=Ye?.market?.[Il.PriceTrendDataSourceNames]?.value,ka=!Array.isArray(Et)||Et.length===0,Yt={...Ye,market:{...Ye.market,exhibitPhotos:{value:jt,confidence:"manual",source:"user",userEdited:!0},...ka?{[Il.PriceTrendDataSourceNames]:{value:["MLS"],confidence:"manual",source:"user",userEdited:!0}}:{}}},ha=await fetch(`/api/uad36/save/${encodeURIComponent(b)}`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({sections:Yt,conditionality:xe?.conditionality??{}})});if(!ha.ok){console.error("[Market] chart apply: save failed",ha.status);return}fi.invalidateQueries({queryKey:O2(b)}).catch(()=>{})}catch(X){console.error("[Market] Failed to apply charts to report:",X)}}:Ir?async P=>{const X=$z(P);na(X),vr(TT,{images:X,signature:ma}),m({title:`${P.length} chart${P.length===1?"":"s"}
53 applied`,description:"Charts will appear in the next PDF export."})}:void 0,onAutoCaptureSave:Ir&&!Ea?(P,X)=>{na(P),vr(TT,{images:P,signature:X||ma})}:void 0,marketDataSignature:ma}),jo&&e.jsx(t$,{open:$c,onOpenChange:Bc,orderId:b}),e.jsx(uz,{open:eo,onOpenChange:Wr,inspectionData:ii,orderId:b||"",lastPushedToInspection:C?.order?.lastPushedToInspection,readOnly:!ci&&Ea,verifyFieldSelections:ot.fieldSelections||{},onVerifyFieldEdit:!ci&&Ea?void 0:P=>{const X=Object.entries(P).filter(([,ke])=>String(ke).trim()!=="");if(X.length===0)return;const xe=ot.fieldSelections||{},Ye={};for(const[ke,jt]of X)Ye[ke]={...xe[ke]||{},selectedSource:"manual",manualValue:jt};xa(ke=>({...ke,fieldSelections:{...ke.fieldSelections||{},...Ye}})),Gs(ke=>({seq:(ke?.seq??0)+1,selections:Ye}))},onUseField:(P,X,xe)=>{if(!Bb(xe??ii)){console.warn("[WizardPage] InspectionPanel onUseField suppressed — no captured inspection");return}ye(Ye=>X4(Ye,P,X))},onRefresh:()=>{b&&AO(()=>JS(b)).then(P=>{P.conclusive&&Gm(P.inspection)})},onBoxliFieldsMerged:P=>{ye(X=>pz(X,P))}}),e.jsx(xi,{open:Ma,onOpenChange:Xn,children:e.jsxs(bi,{className:"max-w-lg",children:[e.jsxs($i,{children:[e.jsx(si,{children:"Select Evaluation Template"}),e.jsx(pl,{children:"Choose a report template for your IAEG evaluation. The template determines required fields, photo slots, and partner overlay sections."})]}),e.jsx("div",{className:"space-y-3 mt-2",children:ec.map(P=>{const X=typeof P.displayName=="string"&&P.displayName.trim()?P.displayName.trim():typeof P.templateKey=="string"&&P.templateKey.trim()?P.templateKey.trim().replace(/[-_]+/g," ").replace(/\b\w/g,xe=>xe.toUpperCase()):"Evaluation Template";return e.jsx("button",{onClick:()=>{lu(P.templateKey),Xn(!1)},className:`w-full text-left p-4 rounded-lg border-2 transition-colors ${Mg===P.templateKey?"border-[#293757] bg-[#293757]/5":"border-slate-200 hover:border-slate-300"}`,"data-testid":`eval-template-option-${P.templateKey}`,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center text-white font-bold text-sm",style:{backgroundColor:P.primaryColor},children:X.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold text-slate-900",children:X}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:P.description})]}),Mg===P.templateKey&&e.jsx(Bs,{className:"w-5 h-5 text-[#293757]"})]})},P.templateKey)})})]})}),Ir&&(()=>{const P=ke=>{rt(ke==="eval"),Fe(ke==="str"),ya(ke==="1004"),St(ke)},X=[];Ir&&X.push({key:"eval",label:"Eval",onSwitch:()=>P("eval")}),xr&&X.push({key:"str",label:"STR",onSwitch:()=>P("str")});const xe=se.form?.value||"";return no&&(xe==="1004"||xe===""||xe.includes("1004"))&&X.push({key:"1004",label:"1004",onSwitch:()=>P("1004")}),Oe?e.jsx(o.Suspense,{fallback:null,children:e.jsx(AX,{open:Oe,onClose:()=>{rt(!1),St(null)},subjectAddress:se.subjectAddress?.value||"",subjectState:Jn,subjectDetails:jf,subjectPhotos:mr,cleanedComps:qe,marketLabState:Ot,compsMapSnapshot:Ee,latitude:Os?.lat,longitude:Os?.lng,reportTabs:X.length>1?X:void 0})}):null})(),e.jsx(L2,{}),Ea&&e.jsxs(e.Fragment,{children:[e.jsx(NV,{open:yo,onKeepEditing:Cd,onRelease:Fg}),e.jsx(AV,{open:Kr,adminForced:cu,onClaim:_g,onDecline:eh}),bb&&e.jsx("div",{className:"fixed top-4 left-1/2 -translate-x-1/2 z-50 bg-amber-50 border border-amber-300 text-amber-800 text-sm px-4 py-2 rounded-md shadow-md",children:"An admin released your editing session. You are now in view mode."}),!ci&&!um&&e.jsx(jV,{lockedBy:jp,presenceRoster:Wc,acquireError:ei,sessionExpired:bc&&!jp,isAdmin:Vg,onRetry:_g,onAdminTakeover:Ug})]})]})});return Ir?e.jsx(JJ,{orderId:_r,onCompGridRowsChange:Mr,onSubjectVehicleStorageItemsChange:nt,onRegisterCompGridFieldEdit:xs,onCustomComparisonFactorsChange:ds,onRegisterCustomComparisonFactorsSetter:Sn,children:Ni}):Ni}const u0={intake:{label:"In Progress",borderColor:"border-[#A18A60]",textColor:"text-[#A18A60]",icon:Pu},in_progress:{label:"In Progress",borderColor:"border-[#A18A60]",textColor:"text-[#A18A60]",icon:Pu},review:{label:"In Progress",borderColor:"border-[#A18A60]",textColor:"text-[#A18A60]",icon:Pu},completed:{label:"Complete",borderColor:"border-emerald-500",textColor:"text-emerald-600",icon:pc},cancelled:{label:"Canceled",borderColor:"border-gray-400",textColor:"text-gray-500",icon:Di},draft:{label:"In Progress",borderColor:"border-[#A18A60]",textColor:"text-[#A18A60]",icon:Pu},archived:{label:"Archived",borderColor:"border-gray-400",textColor:"text-gray-500",icon:Di}},p0={label:"In Progress",borderColor:"border-[#A18A60]",textColor:"text-[#A18A60]",icon:Pu},Rx=(t,a,s,r)=>
53{if(s==="portal")return nE(r,t)||"Portal";const n=nE(r,t);if(!a||a.length===0)return n;const i=a.map(l=>z2(l)).join(" + ");return`${n} + ${i}`};function HX(){const[,t]=bI(),a=iL(),s=ku(),r=ne=>{s.ensureQueryData({queryKey:kx(ne),queryFn:()=>JS(ne,{slim:!0}),staleTime:mL}).catch(()=>{}),$2(ne)},{toast:n}=hc(),{authStatus:i}=jI(),{profile:l}=ly(),c=F2(),d=i?.isPlatformAdmin??!1,p=i?.isImpersonating||!!i?.impersonation,u=i?.impersonation,m=p&&u?.userName?u.userName:l?.firstName?`${l.firstName}${l.lastName?" "+l.lastName:""}`:i?.user?.name||"User",h=_2(m),f=p&&u?.effectiveRole?u.effectiveRoleLabel||u.effectiveRole.split("-").map(ne=>ne.charAt(0).toUpperCase()+ne.slice(1)).join(" "):d?"Platform Admin":"Appraiser",v=o.useMemo(()=>new URLSearchParams(a),[a]),S=v.get("orderId"),N=v.get("tab")||"orders",[x,y]=o.useState(N),[b,j]=o.useState(""),[T,O]=o.useState("all"),[E,R]=o.useState("all"),[G,U]=o.useState("lastAccessed"),[C,F]=o.useState("desc"),[A,M]=o.useState("all"),[B,oe]=o.useState("all"),[ae,D]=o.useState(null),[_,$]=o.useState(!1),{enabled:z}=H2("vault","new_order");o.useEffect(()=>{const Me=new URLSearchParams(a).get("tab");Me&&["orders","searches","comps","change-requests"].includes(Me)&&y(Me)},[a]);const{data:V=[],isLoading:le}=Vr({queryKey:["orders"],queryFn:async()=>{const ne=await fetch("/api/v2/orders?appId=vault,vault-d",{credentials:"include"});if(!ne.ok)throw new Error("Failed to fetch orders");const Me=await ne.json();return Me.rows??Me}}),{data:W=[],isLoading:me}=Vr({queryKey:["market-library"],queryFn:async()=>{const ne=await fetch("/api/market-library",{credentials:"include"});if(!ne.ok)throw new Error("Failed to fetch market library");return ne.json()},enabled:x==="searches"}),{data:Z=[],isLoading:pe}=Vr({queryKey:["comp-library"],queryFn:async()=>{const ne=await fetch("/api/comp-library",{credentials:"include"});if(!ne.ok)throw new Error("Failed to fetch comp library");return ne.json()},enabled:x==="comps"}),{data:se=[],isLoading:fe}=Vr({queryKey:["change-requests"],queryFn:async()=>{const ne=await fetch("/api/change-requests",{credentials:"include"});if(!ne.ok)throw new Error("Failed to fetch change requests");return(await ne.json()).requests??[]}}),ue=Yd({mutationFn:async ne=>{if(!(await fetch(`/api/market-library/${ne}`,{method:"DELETE",credentials:"include"})).ok)throw new Error("Failed to delete search")},onSuccess:()=>{s.invalidateQueries({queryKey:["market-library"]}),n({title:"Search deleted"})}}),be=Yd({mutationFn:async ne=>{if(!(await fetch(`/api/comp-library/${ne}`,{method:"DELETE",credentials:"include"})).ok)throw new Error("Failed to remove comp")},onSuccess:()=>{s.invalidateQueries({queryKey:["comp-library"]}),n({title:"Comp removed from library"})}}),H=Yd({mutationFn:async({id:ne,status:Me})=>{const lt=await fetch(`/api/change-requests/${ne}/status`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:Me}),credentials:"include"});if(!lt.ok)throw new Error("Failed to update status");return lt.json()},onSuccess:()=>{s.invalidateQueries({queryKey:["change-requests"]}),n({title:"Change request updated"})}}),ye=Yd({mutationFn:({id:ne,reason:Me})=>B2(ne,{reason:Me}),onSuccess:()=>{s.invalidateQueries({queryKey:["orders"]}),D(null),n({title:"Order deleted"})},onError:()=>{n({title:"Failed to delete order",variant:"destructive"})}}),de=o.useMemo(()=>{const ne=new Map;return V.forEach(Me=>{const lt=Rx(Me.productType,Me.addOns,Me._source,Me.appId);ne.set(lt,lt)}),Array.from(ne.entries()).sort((Me,lt)=>Me[0].localeCompare(lt[0]))},[V]),ge=o.useMemo(()=>{if(!d)return[];const ne=new Set;return V.forEach(Me=>{Me.clientName&&ne.add(Me.clientName)}),Array.from(ne).sort()},[V,d]),Be=o.useMemo(()=>{if(!d)return[];const ne=new Set;return V.forEach(Me=>{const lt=lx(Me.participants)?sS(Me.participants):null;lt&&ne.add(lt)}),Array.from(ne).sort()},[V,d]),He=ne=>{G===ne?F(Me=>Me==="asc"?"desc":"asc"):(U(ne),F(ne==="lastAccessed"||ne==="created"?"desc":"asc"))},Ie=ne=>{if(!ne)return"-";const Me=new Date(ne),lt=String(Me.getMonth()+1).padStart(2,"0"),Tt=String(Me.getDate()).padStart(2,"0"),je=String(Me.getFullYear()).slice(-2),Le=String(Me.getHours()).padStart(2,"0"),ut=String(Me.getMinutes()).padStart(2,"0");return`${lt}/${Tt}/${je} ${Le}:${ut}`},ce=({column:ne})=>G!==ne?e.jsx(hN,{className:"h-3 w-3 ml-1 opacity-40"}):C==="asc"?e.jsx(xN,{className:"h-3 w-3 ml-1"}):e.jsx(gN,{className:"h-3 w-3 ml-1"}),Pe=o.useMemo(()=>{let ne=V.filter(Me=>{if(b){const lt=b.toLowerCase();if(!(Me.orderNumber?.toLowerCase().includes(lt)||Me.subjectAddress?.toLowerCase().includes(lt)||Me.clientName?.toLowerCase().includes(lt)||lx(Me.participants)?.toLowerCase().includes(lt)))return!1}if(T!=="all"){const lt=(u0[Me.status]||p0).label;if(T==="in_progress"&&lt!=="In Progress"||T==="completed"&&lt!=="Complete")return!1}if(E!=="all"&&Rx(Me.productType,Me.addOns,Me._source,Me.appId)!==E)return!1;if(d){if(A!=="all"&&(Me.clientName||"")!==A)return!1;const lt=lx(Me.participants)?sS(Me.participants):"";if(B!=="all"&&lt!==B)return!1}return!0});return ne.sort((Me,lt)=>{const Tt=C==="asc"?1:-1;switch(G){case"created":{const je=Me.createdAt?new Date(Me.createdAt).getTime():0,Le=lt.createdAt?new Date(lt.createdAt).getTime():0;return(je-Le)*Tt}case"orderNumber":return(Me.orderNumber||"").localeCompare(lt.orderNumber||"")*Tt;case"client":return(Me.clientName||"").localeCompare(lt.clientName||"")*Tt;case"appraiser":return(lx(Me.participants)||"").localeCompare(lx(lt.participants)||"")*Tt;case"address":return(Me.subjectAddress||"").localeCompare(lt.subjectAddress||"")*Tt;case"product":{const je=Rx(Me.productType,Me.addOns,Me._source,Me.appId),Le=Rx(lt.productType,lt.addOns,lt._source,lt.appId);return je.localeCompare(Le)*Tt}case"status":{const je=(u0[Me.status]||p0).label,Le=(u0[lt.status]||p0).label;return je.localeCompare(Le)*Tt}case"lastAccessed":{const je=Me.lastAccessedAt?new Date(Me.lastAccessedAt).getTime():0,Le=lt.lastAccessedAt?new Date(lt.lastAccessedAt).getTime():0;return je===0&&Le===0?0:je===0?1:Le===0?-1:(je-Le)*Tt}default:return 0}}),ne},[V,b,T,E,G,C,A,B,d]),We=ne=>{const Me=new Date(ne),Tt=new Date().getTime()-Me.getTime(),je=Math.floor(Tt/6e4),Le=Math.floor(je/60),ut=Math.floor(Le/24);return ut>0?`${ut}d ago`:Le>0?`${Le}h ago`:je>0?`${je}m ago`:"Just now"},Re=ne=>{y(ne),t(ne==="orders"?"/vault":`/vault?tab=${ne}`)};return S?e.jsx(pL,{fallbackMessage:"The order wizard encountered an error",showDashboardLink:!0,context:{orderId:S},children:e.jsx(GX,{})}):e.jsxs("div",{className:"min-h-screen bg-[#FAF9F7] text-[#1E1E1E]","data-testid":"dashboard-page",children:[e.jsxs("header",{className:"shrink-0 bg-white border-b border-[#
53E8E0D8]",children:[e.jsxs("div",{className:"max-w-7xl mx-auto h-14 flex items-center justify-between px-3 sm:px-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("a",{href:"https://www.banksvaluation.com/",target:"_blank",rel:"noopener noreferrer","data-testid":"link-banks-valuation",children:e.jsx("img",{src:G2,alt:"Banks Valuation",className:"h-7","data-testid":"header-logo"})}),e.jsx("div",{className:"h-5 w-px bg-[#E8E0D8]"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(XR,{className:"w-4 h-4 text-[#A18A60]"}),e.jsx("span",{className:"text-[#4B5563] font-medium text-sm hidden sm:inline",children:"Dashboard"})]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(U2,{label:"Back",mode:"history",fallback:"/portal",portalAware:!0,variant:"ghost",size:"sm",className:"text-[#9CA3AF] hover:text-[#1E1E1E] hover:bg-[#FAF9F7] transition-colors"}),e.jsxs(Qh,{children:[e.jsx(Zh,{asChild:!0,children:e.jsxs("button",{className:"hidden sm:flex items-center gap-2.5 cursor-pointer","data-testid":"button-user-menu",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-[#072034] flex items-center justify-center text-[#C5A572] font-semibold text-sm border-2 border-[#C5A572]/40","data-testid":"avatar-user-initial",children:h}),e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"text-sm font-medium text-[#1E1E1E] leading-tight","data-testid":"text-user-name",children:m}),e.jsx("span",{className:"text-[11px] text-[#9CA3AF] leading-tight","data-testid":"text-user-role",children:f})]})]})}),e.jsxs(Jh,{align:"end",className:"w-48",children:[e.jsxs(Yl,{onClick:()=>t("/profile"),"data-testid":"menu-account-settings",children:[e.jsx(rT,{className:"h-4 w-4 mr-2"}),"Account Settings"]}),d&&!p&&e.jsxs(e.Fragment,{children:[e.jsx(f0,{}),e.jsxs(Yl,{onClick:c.openDialog,"data-testid":"menu-impersonate",children:[e.jsx(of,{className:"h-4 w-4 mr-2"}),"Impersonate"]})]}),e.jsx(f0,{}),e.jsxs(Yl,{onClick:()=>{rE()},"data-testid":"menu-logout",children:[e.jsx(nT,{className:"h-4 w-4 mr-2"}),"Log out"]})]})]}),e.jsx("button",{onClick:()=>$(!_),className:"sm:hidden flex items-center justify-center w-9 h-9 rounded text-[#9CA3AF] hover:text-[#1E1E1E] hover:bg-[#FAF9F7]","data-testid":"button-mobile-menu",children:_?e.jsx(ur,{className:"w-5 h-5"}):e.jsx(oL,{className:"w-5 h-5"})})]})]}),_&&e.jsxs("div",{className:"sm:hidden border-t border-[#E8E0D8] bg-white px-3 py-3 space-y-1","data-testid":"mobile-nav-menu",children:[e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-[#072034] flex items-center justify-center text-[#C5A572] font-semibold text-sm",children:h}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-sm font-medium text-[#1E1E1E] leading-tight",children:m}),e.jsx("span",{className:"text-xs text-[#9CA3AF] leading-tight",children:f})]})]}),e.jsx("div",{className:"border-t border-[#E8E0D8] my-1"}),e.jsxs("button",{onClick:()=>{t("/vault"),$(!1)},className:"w-full flex items-center gap-3 px-3 py-2.5 rounded text-sm font-medium text-[#A18A60] bg-[#A18A60]/10","data-testid":"mobile-nav-dashboard",children:[e.jsx(XR,{className:"w-4 h-4"}),"Dashboard"]}),z===!0&&e.jsxs("button",{onClick:()=>{t("/vault/new"),$(!1)},className:"w-full flex items-center gap-3 px-3 py-2.5 rounded text-sm font-medium text-[#4B5563] hover:text-[#1E1E1E] hover:bg-[#FAF9F7]","data-testid":"mobile-nav-new-order",children:[e.jsx(un,{className:"w-4 h-4"}),"New Order"]}),e.jsxs("button",{onClick:()=>{t("/profile"),$(!1)},className:"w-full flex items-center gap-3 px-3 py-2.5 rounded text-sm font-medium text-[#4B5563] hover:text-[#1E1E1E] hover:bg-[#FAF9F7]","data-testid":"mobile-nav-profile",children:[e.jsx(rT,{className:"w-4 h-4"}),"Account Settings"]}),e.jsx("div",{className:"border-t border-[#E8E0D8] my-1"}),e.jsxs("button",{onClick:()=>{rE()},className:"w-full flex items-center gap-3 px-3 py-2.5 rounded text-sm font-medium text-[#9CA3AF] hover:text-[#1E1E1E] hover:bg-[#FAF9F7]","data-testid":"mobile-nav-logout",children:[e.jsx(nT,{className:"w-4 h-4"}),"Log out"]})]})]}),e.jsxs("main",{className:"max-w-7xl mx-auto px-3 sm:px-6 pt-6 pb-10",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:gap-0 justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-['Playfair_Display'] text-2xl sm:text-3xl font-semibold text-[#1E1E1E] mb-0.5","data-testid":"text-page-title",children:"Dashboard"}),e.jsx("p",{className:"text-sm text-[#9CA3AF]",children:"Manage your appraisal orders and research."})]}),z===!0&&e.jsxs(De,{className:"bg-[#072034] hover:bg-[#0a2d4a] text-white px-5 h-10 shadow-sm text-sm rounded-lg",onClick:()=>t("/vault/new"),"data-testid":"button-new-order",children:[e.jsx(un,{className:"w-4 h-4 mr-2"}),"New Order"]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 mb-5",children:[e.jsxs("div",{className:"bg-white border border-[#
53E8E0D8] px-4 py-3 rounded-xl","data-testid":"stat-card-total-orders",children:[e.jsx("p",{className:"text-[11px] text-[#9CA3AF] uppercase tracking-wide font-medium mb-0.5",children:"Total Orders"}),e.jsx("p",{className:"text-2xl font-semibold text-[#1E1E1E]",children:V.length})]}),e.jsxs("div",{className:"bg-[#A18A60]/5 border border-[#E8E0D8] px-4 py-3 rounded-xl","data-testid":"stat-card-in-progress",children:[e.jsx("p",{className:"text-[11px] text-[#9CA3AF] uppercase tracking-wide font-medium mb-0.5",children:"In Progress"}),e.jsx("p",{className:"text-2xl font-semibold text-[#A18A60]",children:V.filter(ne=>["intake","in_progress","review","draft"].includes(ne.status)).length})]}),e.jsxs("div",{className:"bg-blue-50/60 border border-[#E8E0D8] px-4 py-3 rounded-xl","data-testid":"stat-card-pending-review",children:[e.jsx("p",{className:"text-[11px] text-[#9CA3AF] uppercase tracking-wide font-medium mb-0.5",children:"Pending Review"}),e.jsx("p",{className:"text-2xl font-semibold text-blue-600",children:V.filter(ne=>ne.status==="review").length})]}),e.jsxs("div",{className:"bg-emerald-50/60 border border-[#E8E0D8] px-4 py-3 rounded-xl","data-testid":"stat-card-complete",children:[e.jsx("p",{className:"text-[11px] text-[#9CA3AF] uppercase tracking-wide font-medium mb-0.5",children:"Complete"}),e.jsx("p",{className:"text-2xl font-semibold text-emerald-600",children:V.filter(ne=>ne.status==="completed").length})]})]}),e.jsxs("div",{className:"flex flex-col gap-4 mb-4 sm:mb-6",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-[#E8E0D8]",children:[e.jsxs("button",{onClick:()=>Re("orders"),className:`flex items-center gap-1.5 px-4 py-2.5 text-xs sm:text-sm font-medium border-b-2 transition-colors -mb-px whitespace-nowrap ${x==="orders"?"border-[#A18A60] text-[#A18A60]":"border-transparent text-[#9CA3AF] hover:text-[#4B5563]"}`,"data-testid":"tab-orders",children:[e.jsx(gn,{className:"w-3.5 h-3.5"}),"Orders"]}),e.jsxs("button",{onClick:()=>Re("searches"),className:`flex items-center gap-1.5 px-4 py-2.5 text-xs sm:text-sm font-medium border-b-2 transition-colors -mb-px whitespace-nowrap ${x==="searches"?"border-[#A18A60] text-[#A18A60]":"border-transparent text-[#9CA3AF] hover:text-[#4B5563]"}`,"data-testid":"tab-searches",children:[e.jsx(Eu,{className:"w-3.5 h-3.5"}),"Saved Searches"]}),e.jsxs("button",{onClick:()=>Re("comps"),className:`flex items-center gap-1.5 px-4 py-2.5 text-xs sm:text-sm font-medium border-b-2 transition-colors -mb-px whitespace-nowrap ${x==="comps"?"border-[#A18A60] text-[#A18A60]":"border-transparent text-[#9CA3AF] hover:text-[#4B5563]"}`,"data-testid":"tab-comps",children:[e.jsx(gn,{className:"w-3.5 h-3.5"}),"My Comps"]}),e.jsxs("button",{onClick:()=>Re("change-requests"),className:`flex items-center gap-1.5 px-4 py-2.5 text-xs sm:text-sm font-medium border-b-2 transition-colors -mb-px whitespace-nowrap ${x==="change-requests"?"border-[#A18A60] text-[#A18A60]":"border-transparent text-[#9CA3AF] hover:text-[#4B5563]"}`,"data-testid":"tab-change-requests",children:[e.jsx(Di,{className:"w-3.5 h-3.5"}),"Change Requests",se.filter(ne=>ne.status==="pending").length>0&&e.jsx("span",{className:"ml-1 bg-amber-500 text-white text-[10px] font-bold rounded-full w-5 h-5 flex items-center justify-center","data-testid":"badge-pending-requests",children:se.filter(ne=>ne.status==="pending").length})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Eu,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[#9CA3AF]"}),e.jsx(ze,{placeholder:"Search orders...",value:b,onChange:ne=>j(ne.target.value),className:"pl-8 w-full sm:w-48 h-8 bg-white border-[#E8E0D8] text-sm rounded-lg focus-visible:ring-[#C5A572]","data-testid":"input-search"})]}),e.jsxs(sr,{value:E,onValueChange:R,children:[e.jsx(rr,{className:"w-full sm:w-[180px] h-8 bg-white border-[#E8E0D8] text-[#4B5563] rounded-lg text-sm","data-testid":"filter-product",children:e.jsx(or,{placeholder:"Product"})}
53),e.jsxs(nr,{className:"bg-white border-[#E8E0D8]",children:[e.jsx(vs,{value:"all",children:"All Products"}),de.map(([ne,Me])=>e.jsx(vs,{value:ne,children:Me},ne))]})]}),e.jsxs(sr,{value:T,onValueChange:O,children:[e.jsx(rr,{className:"w-full sm:w-[130px] h-8 bg-white border-[#E8E0D8] text-[#4B5563] rounded-lg text-sm","data-testid":"filter-status",children:e.jsx(or,{placeholder:"Status"})}),e.jsxs(nr,{className:"bg-white border-[#E8E0D8]",children:[e.jsx(vs,{value:"all",children:"All Status"}),e.jsx(vs,{value:"in_progress",children:"In Progress"}),e.jsx(vs,{value:"completed",children:"Complete"})]})]}),d&&e.jsxs(sr,{value:A,onValueChange:M,children:[e.jsx(rr,{className:"w-full sm:w-[180px] h-8 bg-white border-[#E8E0D8] text-[#4B5563] rounded-lg text-sm","data-testid":"filter-client",children:e.jsx(or,{placeholder:"Client"})}),e.jsxs(nr,{className:"bg-white border-[#E8E0D8]",children:[e.jsx(vs,{value:"all",children:"All Clients"}),ge.map(ne=>e.jsx(vs,{value:ne,children:ne},ne))]})]}),d&&e.jsxs(sr,{value:B,onValueChange:oe,children:[e.jsx(rr,{className:"w-full sm:w-[180px] h-8 bg-white border-[#E8E0D8] text-[#4B5563] rounded-lg text-sm","data-testid":"filter-appraiser",children:e.jsx(or,{placeholder:"Appraiser"})}),e.jsxs(nr,{className:"bg-white border-[#E8E0D8]",children:[e.jsx(vs,{value:"all",children:"All Appraisers"}),Be.map(ne=>e.jsx(vs,{value:ne,children:ne},ne))]})]})]})]}),x==="orders"&&e.jsx("div",{className:"bg-white rounded-xl border border-[#E8E0D8] shadow-sm overflow-hidden",children:le?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(za,{className:"h-8 w-8 animate-spin text-[#A18A60]"})}):Pe.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(gn,{className:"h-12 w-12 text-[#E8E0D8] mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-[#1E1E1E] mb-2",children:"No orders yet"}),e.jsx("p",{className:"text-[#9CA3AF] mb-4",children:z===!0?"Create your first order to get started":"No orders to display"}),z===!0&&e.jsxs(De,{onClick:()=>t("/vault/new"),className:"bg-[#072034] hover:bg-[#0a2d4a] text-white","data-testid":"button-create-first-order",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Create Order"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden sm:block",children:e.jsxs(Gd,{children:[e.jsx(Hd,{children:e.jsxs(gi,{className:"border-[#E8E0D8] hover:bg-transparent bg-[#FAF9F7]",children:[e.jsx(Ds,{className:"text-[#9CA3AF] font-medium text-[10px] uppercase tracking-wider cursor-pointer select-none hover:text-[#4B5563]",onClick:()=>He("created"),"data-testid":"sort-created",children:e.jsxs("span",{className:"flex items-center",children:["Created",e.jsx(ce,{column:"created"})]})}),e.jsx(Ds,{className:"text-[#9CA3AF] font-medium text-[10px] uppercase tracking-wider cursor-pointer select-none hover:text-[#4B5563]",onClick:()=>He("orderNumber"),"data-testid":"sort-order-number",children:e.jsxs("span",{className:"flex items-center",children:["Order #",e.jsx(ce,{column:"orderNumber"})]})}),d&&e.jsx(Ds,{className:"text-[#9CA3AF] font-medium text-[10px] uppercase tracking-wider cursor-pointer select-none hover:text-[#4B5563]",onClick:()=>He("client"),"data-testid":"sort-client",children:e.jsxs("span",{className:"flex items-center",children:["Client",e.jsx(ce,{column:"client"})]})}),d&&e.jsx(Ds,{className:"text-[#9CA3AF] font-medium text-[10px] uppercase tracking-wider cursor-pointer select-none hover:text-[#4B5563]",onClick:()=>He("appraiser"),"data-testid":"sort-appraiser",children:e.jsxs("span",{className:"flex items-center",children:["Appraiser",e.jsx(ce,{column:"appraiser"})]})}),e.jsx(Ds,{className:"text-[#9CA3AF] font-medium text-[10px] uppercase tracking-wider cursor-pointer select-none hover:text-[#4B5563]",onClick:()=>He("address"),"data-testid":"sort-address",children:e.jsxs("span",{className:"flex items-center",children:["Address",e.jsx(ce,{column:"address"})]})}),e.jsx(Ds,{className:"text-[#9CA3AF] font-medium text-[10px] uppercase tracking-wider cursor-pointer select-none hover:text-[#4B5563]",onClick:()=>He("product"),"data-testid":"sort-product",children:e.jsxs("span",{className:"flex items-center",children:["Product",e.jsx(ce,{column:"product"})]})}),e.jsx(Ds,{className:"text-[#9CA3AF] font-medium text-[10px] uppercase tracking-wider cursor-pointer select-none hover:text-[#4B5563]",onClick:()=>He("status"),"data-testid":"sort-status",children:e.jsxs("span",{className:"flex items-center",children:["Status",e.jsx(ce,{column:"status"})]})}),e.jsx(Ds,{className:"text-[#9CA3AF] font-medium text-[10px] uppercase tracking-wider cursor-pointer select-none hover:text-[#4B5563]",onClick:()=>He("lastAccessed"),"data-testid":"sort-last-accessed",children:e.jsxs("span",{className:"flex items-center",children:["Last Accessed",e.jsx(ce,{column:"lastAccessed"})]})}),e.jsx(Ds,{className:"text-[#9CA3AF] font-medium text-[10px] uppercase tracking-wider w-[80px]"})]})}),e.jsx(Wd,{children:Pe.map(ne=>{const Me=u0[ne.status]||p0;
53return Me.icon,e.jsxs(gi,{className:`border-[#E8E0D8] hover:bg-[#FAF9F7]/50 transition-colors ${ne._source!=="portal"?"cursor-pointer":""}`,onClick:()=>ne._source!=="portal"&&t(ax(ne)),onMouseEnter:()=>ne._source!=="portal"&&r(ne.id),onFocus:()=>ne._source!=="portal"&&r(ne.id),"data-testid":`row-order-${ne.id}`,children:[e.jsx(ws,{className:"text-[#9CA3AF] text-[11px]",children:ne.createdAt?new Date(ne.createdAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"-"}),e.jsx(ws,{className:"text-sm font-medium text-[#A18A60]",children:ne.orderNumber||"-"}),d&&e.jsx(ws,{className:"text-xs text-[#4B5563]","data-testid":`cell-client-${ne.id}`,children:ne.clientName||"-"}),d&&e.jsx(ws,{className:"text-xs text-[#4B5563]","data-testid":`cell-appraiser-${ne.id}`,children:sS(ne.participants)}),e.jsx(ws,{children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[#1E1E1E]",children:Mx({street:ne.subjectAddress},{emptyFallback:"No address"})}),ne.city&&ne.state&&e.jsx("p",{className:"text-[11px] text-[#9CA3AF] mt-0.5",children:Mx({city:ne.city,state:ne.state},{emptyFallback:"",includeZip:!1})})]})}),e.jsx(ws,{className:"text-xs text-[#4B5563]",children:Rx(ne.productType,ne.addOns,ne._source,ne.appId)}),e.jsx(ws,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${Me.borderColor.replace("border-","bg-")}`}),e.jsx("span",{className:`text-xs font-medium ${Me.textColor}`,children:Me.label})]})}),e.jsx(ws,{className:"text-[#9CA3AF] text-[11px]","data-testid":`cell-last-accessed-${ne.id}`,children:Ie(ne.lastAccessedAt)}),e.jsx(ws,{children:ne._source!=="portal"?e.jsxs(Qh,{children:[e.jsx(Zh,{asChild:!0,onClick:lt=>lt.stopPropagation(),children:e.jsx(De,{variant:"ghost",size:"icon",className:"h-7 w-7 text-[#9CA3AF] hover:text-[#1E1E1E]","data-testid":`button-order-menu-${ne.id}`,children:e.jsx(eE,{className:"h-4 w-4"})})}),e.jsxs(Jh,{align:"end",children:[e.jsx(Yl,{onClick:lt=>{lt.stopPropagation(),t(ax(ne))},"data-testid":`menu-open-order-${ne.id}`,children:"Open Order"}),e.jsx(Yl,{onClick:lt=>{lt.stopPropagation(),t(ax(ne))},"data-testid":`menu-order-details-${ne.id}`,children:"Order details"}),e.jsx(f0,{}),e.jsxs(Yl,{onClick:lt=>{lt.stopPropagation(),D(ne)},className:"text-red-500 focus:text-red-500",children:[e.jsx(Ci,{className:"w-4 h-4 mr-2"}),"Delete Order"]})]})]}):e.jsx("span",{className:"text-[10px] text-[#9CA3AF] px-2",children:"Portal"})})]},ne.id)})})]})}),e.jsx("div",{className:"sm:hidden divide-y divide-[#E8E0D8]",children:Pe.map(ne=>{const Me=u0[ne.status]||p0;return Me.icon,e.jsxs("div",{className:`flex items-start justify-between p-4 hover:bg-[#FAF9F7] ${ne._source!=="portal"?"cursor-pointer":""}`,onClick:()=>ne._source!=="portal"&&t(ax(ne)),onMouseEnter:()=>ne._source!=="portal"&&r(ne.id),onFocus:()=>ne._source!=="portal"&&r(ne.id),"data-testid":`card-order-${ne.id}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-[#1E1E1E] truncate",children:Mx({street:ne.subjectAddress},{emptyFallback:"No address"})}),ne.city&&ne.state&&e.jsx("p",{className:"text-xs text-[#9CA3AF]",children:Mx({city:ne.city,state:ne.state},{emptyFallback:"",includeZip:!1})}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[e.jsx("span",{className:"text-xs text-[#A18A60] font-medium",children:ne.orderNumber||"-"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${Me.borderColor.replace("border-","bg-")}`}),e.jsx("span",{className:`text-xs font-medium ${Me.textColor}`,children:Me.label})]}),ne._source==="portal"&&e.jsx("span",{className:"text-[10px] text-[#9CA3AF] px-1.5 py-0.5 border border-[#E8E0D8] rounded",children:"Portal"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#9CA3AF]",children:[e.jsxs("span",{children:["Created: ",ne.createdAt?new Date(ne.createdAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"-"]}),e.jsx("span",{children:Rx(ne.productType,ne.addOns,ne._source,ne.appId)})]}),e.jsx("div",{className:"flex items-center gap-3 mt-0.5 text-xs text-[#9CA3AF]","data-testid":`mobile-last-accessed-${ne.id}`,children:e.jsxs("span",{children:["Last Accessed: ",Ie(ne.lastAccessedAt)]})}),d&&e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-[#9CA3AF]",children:[ne.clientName&&e.jsxs("span",{"data-testid":`mobile-client-${ne.id}`,children:["Client: ",ne.clientName]}),lx(ne.participants)&&e.jsxs("span",{"data-testid":`mobile-appraiser-${ne.id}`,children:["Appraiser: ",sS(ne.participants)]})]})]}),ne._source!=="portal"?e.jsxs(Qh,{children:[e.jsx(Zh,{asChild:!0,onClick:lt=>lt.stopPropagation(),children:e.jsx(De,{variant:"ghost",size:"icon",className:"h-7 w-7 text-[#9CA3AF] hover:text-[#1E1E1E] shrink-0 ml-2","data-testid":`button-order-menu-mobile-${ne.id}`,children:e.jsx(eE,{className:"h-4 w-4"})})}),e.jsxs(Jh,{align:"end",children:[e.jsx(Yl,{onClick:lt=>{lt.stopPropagation(),t(ax(ne))},"data-testid":`menu-open-order-mobile-${ne.id}`,children:"Open Order"}),e.jsx(Yl,{onClick:lt=>{lt.stopPropagation(),t(ax(ne))},"data-testid":`menu-order-details-mobile-${ne.id}`,children:"Order details"}),e.jsx(f0,{}),e.jsxs(Yl,{onClick:lt=>{lt.stopPropagation(),D(ne)},className:"text-red-500 focus:text-red-500",children:[e.jsx(Ci,{className:"w-4 h-4 mr-2"}),"Delete Order"]})]})]}):null]},ne.id)})})]})}),x==="searches"&&e.jsx("div",{className:"space-y-4",children:me?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(za,{className:"h-8 w-8 animate-spin text-[#A18A60]"})}):W.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-[#
53E8E0D8] text-center py-12",children:[e.jsx(Eu,{className:"h-12 w-12 text-[#E8E0D8] mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-[#1E1E1E] mb-2",children:"No saved market searches yet"}),e.jsx("p",{className:"text-[#9CA3AF]",children:"Save searches from Property Lab to reuse them across orders."})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:W.map(ne=>e.jsxs("div",{className:"bg-white rounded-xl border border-[#E8E0D8] p-4 hover:border-[#C5A572]/50 transition-colors","data-testid":`market-search-${ne.id}`,children:[e.jsx("h3",{className:"font-semibold text-[#1E1E1E] mb-2",children:ne.name}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[ne.radiusMiles&&e.jsxs(kt,{variant:"outline",className:"text-xs border-[#E8E0D8] text-[#4B5563]",children:[ne.radiusMiles," mi radius"]}),ne.salesCount!==null&&e.jsxs(kt,{variant:"outline",className:"text-xs border-[#E8E0D8] text-[#4B5563]",children:[ne.salesCount," sales"]}),ne.useCount>0&&e.jsxs(kt,{variant:"outline",className:"text-xs border-[#A18A60]/50 text-[#A18A60]",children:["Used ",ne.useCount,"x"]})]}),e.jsxs("p",{className:"text-xs text-[#9CA3AF] mb-3",children:["Saved ",We(ne.createdAt)]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(De,{size:"sm",className:"flex-1 bg-[#A18A60] hover:bg-[#8B7650] text-white",onClick:()=>{const Me=ne.radiusMiles?parseFloat(ne.radiusMiles):null,lt=ne.center&&Me?[{id:`library-radius-${ne.id}`,type:"radius",label:`${Me} mi radius`,center:ne.center,radiusMiles:Me}]:ne.boundaries||[];sessionStorage.setItem("applySavedMarketSearch",JSON.stringify({parsedFilters:ne.filters||{},boundaries:lt,polygon:ne.polygon,center:ne.center,radiusMiles:Me})),t("/vault/comps-database")},"data-testid":`button-apply-market-search-${ne.id}`,children:[e.jsx(aL,{className:"w-3 h-3 mr-1"}),"Open in Comps Database"]}),e.jsx(De,{variant:"ghost",size:"icon",className:"text-red-400 hover:text-red-500 hover:bg-red-50",onClick:()=>ue.mutate(ne.id),"data-testid":`button-delete-market-search-${ne.id}`,children:e.jsx(Ci,{className:"w-4 h-4"})})]})]},ne.id))})}),x==="comps"&&e.jsx("div",{children:pe?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(za,{className:"h-8 w-8 animate-spin text-[#A18A60]"})}):Z.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-[#E8E0D8] text-center py-12",children:[e.jsx(QO,{className:"h-12 w-12 text-[#E8E0D8] mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-[#1E1E1E] mb-2",children:"No comps saved"}),e.jsx("p",{className:"text-[#9CA3AF] mb-4",children:"Add comps to your library from Property Lab or Comps Database"}),e.jsxs(De,{onClick:()=>t("/vault/comps-database"),className:"bg-[#072034] hover:bg-[#0a2d4a] text-white","data-testid":"button-browse-comps",children:[e.jsx(Eu,{className:"h-4 w-4 mr-2"}),"Browse Comps"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Z.map(ne=>e.jsxs("div",{className:"bg-white rounded-xl border border-[#E8E0D8] overflow-hidden hover:border-[#C5A572]/50 transition-colors","data-testid":`comp-library-${ne.id}`,children:[ne.comp?.primaryPhotoUrl?e.jsx("div",{className:"h-32 bg-[#FAF9F7]",children:e.jsx("img",{src:ne.comp.primaryPhotoUrl,alt:ne.comp.address,className:"w-full h-full object-cover"})}):e.jsx("div",{className:"h-32 bg-[#FAF9F7] flex items-center justify-center",children:e.jsx(Fo,{className:"w-10 h-10 text-[#E8E0D8]"})}),e.jsxs("div",{className:"p-4",children:[e.jsx("p",{className:"font-medium text-[#1E1E1E] truncate",children:ne.comp?.address||"Unknown Address"}),e.jsx("p",{className:"text-sm text-[#9CA3AF] truncate",children:[ne.comp?.city,ne.comp?.state].filter(Boolean).join(", ")||"Location unknown"}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-[#4B5563]",children:[ne.comp?.bedrooms&&e.jsxs("span",{children:[ne.comp.bedrooms," bd"]}),ne.comp?.bathrooms&&e.jsxs("span",{children:[parseFloat(ne.comp.bathrooms)," ba"]}),ne.comp?.sqft&&e.jsxs("span",{children:[ne.comp.sqft.toLocaleString()," sqft"]})]}),ne.comp?.salePrice&&e.jsxs("p",{className:"text-lg font-bold text-[#A18A60] mt-2",children:["$",parseFloat(ne.comp.salePrice).toLocaleStr
53ing()]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 pt-3 border-t border-[#E8E0D8]",children:[e.jsx(kt,{variant:"outline",className:"text-xs border-[#E8E0D8] text-[#4B5563]",children:ne.source==="favorite"?"Favorite":ne.source==="selection"?"Selected":"Imported"}),e.jsx(De,{variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400 hover:text-red-500 hover:bg-red-50",onClick:()=>be.mutate(ne.id),"data-testid":`button-remove-comp-${ne.id}`,children:e.jsx(Ci,{className:"w-4 h-4"})})]})]})]},ne.id))})}),x==="change-requests"&&e.jsx("div",{children:fe?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(za,{className:"h-8 w-8 animate-spin text-[#A18A60]"})}):se.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-[#E8E0D8] text-center py-12","data-testid":"empty-change-requests",children:[e.jsx(pc,{className:"h-12 w-12 text-emerald-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-[#1E1E1E] mb-2",children:"No change requests"}),e.jsx("p",{className:"text-[#9CA3AF]",children:"When clients request changes to your digital reports, they will appear here."})]}):e.jsx("div",{className:"space-y-3",children:se.map(ne=>{const Me={pending:{bg:"bg-amber-50",text:"text-amber-700",label:"Pending"},reviewed:{bg:"bg-blue-50",text:"text-blue-700",label:"Reviewed"},resolved:{bg:"bg-emerald-50",text:"text-emerald-700",label:"Resolved"}},lt=Me[ne.status]||Me.pending;return e.jsx("div",{className:"bg-white rounded-xl border border-[#E8E0D8] p-5 hover:border-[#C5A572]/50 transition-colors","data-testid":`change-request-${ne.id}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h4",{className:"font-medium text-[#1E1E1E] truncate",children:ne.propertyAddress||"Unknown Property"}),e.jsx(kt,{className:`${lt.bg} ${lt.text} border-0 text-[10px]`,"data-testid":`status-${ne.id}`,children:lt.label})]}),e.jsx("p",{className:"text-sm text-[#4B5563] mb-3 whitespace-pre-wrap","data-testid":`message-${ne.id}`,children:ne.message}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-[#9CA3AF]",children:[ne.requesterName&&e.jsxs("span",{"data-testid":`requester-name-${ne.id}`,children:["From: ",ne.requesterName]}),ne.requesterEmail&&e.jsx("span",{"data-testid":`requester-email-${ne.id}`,children:ne.requesterEmail}),e.jsx("span",{children:new Date(ne.createdAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})})]})]}),ne.status!=="resolved"&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[ne.status==="pending"&&e.jsxs(De,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>H.mutate({id:ne.id,status:"reviewed"}),"data-testid":`button-mark-reviewed-${ne.id}`,children:[e.jsx(of,{className:"w-3.5 h-3.5 mr-1"}),"Mark Reviewed"]}),e.jsxs(De,{size:"sm",className:"text-xs bg-emerald-600 hover:bg-emerald-700",onClick:()=>H.mutate({id:ne.id,status:"resolved"}),"data-testid":`button-resolve-${ne.id}`,children:[e.jsx(pc,{className:"w-3.5 h-3.5 mr-1"}),"Resolve"]})]})]})},ne.id)})})})]}),e.jsx(Y2,{open:!!ae,onOpenChange:ne=>!ne&&D(null),orderNumber:ae?.orderNumber,orderAddress:ae?.subjectAddress,isPending:ye.isPending,onConfirm:ne=>{ae&&ye.mutate({id:ae.id,reason:ne})}}),e.jsx(V2,{open:c.open,onOpenChange:c.setOpen})]})}const Ste=Object.freeze(Object.defineProperty({__proto__:null,default:HX},Symbol.toStringTag,{value:"Module"}));export{aN as A,nte as B,sY as C,YM as D,cte as E,YJ as F,pte as G,cN as H,mte as I,fte as J,ete as K,_J as L,y0 as M,WM as N,HI as O,ate as P,hb as Q,dte as R,FN as S,df as T,Mv as U,HJ as V,BJ as W,zJ as X,ste as Y,Ste as Z,rY as a,LN as b,py as c,ok as d,GI as e,kc as f,tf as g,lX as h,ute as i,gte as j,iX as k,ote as l,tte as m,oN as n,bte as o,xte as p,sX as q,Yz as r,XI as s,yte as t,hte as u,UJ as v,ite as w,fD as x,lte as y,rte as z};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.