@everfur/sdk 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +11 -10
  3. package/dist/{Chat.d-Dts8u_1a.d.cts → Chat.d-aycmX1CA.d.cts} +12 -4
  4. package/dist/{Chat.d-DUNTfzqC.d.ts → Chat.d-puminpyi.d.ts} +12 -4
  5. package/dist/{DepthViews.d-CubkMPbU.d.ts → DepthViews.d-BdvFZgPs.d.cts} +1 -1
  6. package/dist/{DepthViews.d-Ce2Zhnrb.d.ts → DepthViews.d-DIvxzLDf.d.ts} +1 -1
  7. package/dist/{DepthViews.d-BMU2jFPw.d.cts → DepthViews.d-Dy0Zl-s-.d.ts} +1 -1
  8. package/dist/{DepthViews.d-BIp599lz.d.cts → DepthViews.d-wLNkzk9f.d.cts} +1 -1
  9. package/dist/RecordsPage.d-9Ank15PT.d.ts +93 -0
  10. package/dist/RecordsPage.d-DMKU0IKc.d.cts +93 -0
  11. package/dist/animations/index.d.cts +5 -5
  12. package/dist/animations/index.d.ts +5 -5
  13. package/dist/{attachments.d-D1yhJjcZ.d.ts → attachments.d--sIsfk6e.d.ts} +2 -2
  14. package/dist/{attachments.d-Bp2qbHxn.d.cts → attachments.d-DNUCiyy5.d.cts} +6 -24
  15. package/dist/{attachments.d-DisnvB9R.d.cts → attachments.d-ZEpTUeWN.d.cts} +2 -2
  16. package/dist/{attachments.d-Djy9z_0Z.d.ts → attachments.d-rp3xs-Q3.d.ts} +6 -24
  17. package/dist/{bookingCopy.d-BJF6gd1A.d.ts → bookingCopy.d-D0uIIFAJ.d.ts} +2 -2
  18. package/dist/{bookingCopy.d-BlBmhAJc.d.cts → bookingCopy.d-DUrmVcLs.d.cts} +2 -2
  19. package/dist/{branding.d-DI8S400y.d.cts → branding.d-CTXTUg_8.d.cts} +1 -1
  20. package/dist/{branding.d-OIGLbQeM.d.ts → branding.d-DxJSoFce.d.ts} +1 -1
  21. package/dist/{casesRepository.d-CT2LTicS.d.cts → casesRepository.d-DCnix2pT.d.cts} +1 -1
  22. package/dist/{casesRepository.d-UsWOz9bv.d.ts → casesRepository.d-DbirgbyH.d.ts} +1 -1
  23. package/dist/chat/index.cjs +43 -41
  24. package/dist/chat/index.d.cts +26 -13
  25. package/dist/chat/index.d.ts +26 -13
  26. package/dist/chat/index.js +43 -41
  27. package/dist/client/index.cjs +2 -2
  28. package/dist/client/index.d.cts +10 -10
  29. package/dist/client/index.d.ts +10 -10
  30. package/dist/client/index.js +2 -2
  31. package/dist/clinicBatch.d-Ccmrngcu.d.cts +71 -0
  32. package/dist/clinicBatch.d-D9Ci7IpP.d.ts +71 -0
  33. package/dist/clinicModels.d-BXgKZqDb.d.cts +68 -0
  34. package/dist/clinicModels.d-CaS64-P-.d.ts +68 -0
  35. package/dist/clinicRequestProps.d-1dCtouGA.d.cts +65 -0
  36. package/dist/clinicRequestProps.d-CjsMg_OD.d.ts +65 -0
  37. package/dist/{config.d-BR3DT9ho.d.cts → config.d-DJ4mvf_w.d.cts} +1 -1
  38. package/dist/{config.d-Dy6igYlH.d.ts → config.d-MX7IKP2f.d.ts} +1 -1
  39. package/dist/consent/index.d.cts +5 -5
  40. package/dist/consent/index.d.ts +5 -5
  41. package/dist/{context.d-QcCgguzA.d.ts → context.d-BdnBe8Oe.d.ts} +7 -7
  42. package/dist/{context.d-Cwks0p3C.d.cts → context.d-C6MJsMpN.d.cts} +7 -7
  43. package/dist/{copy.d-CiMn2IIt.d.ts → copy.d-BIfQOoDB.d.ts} +2 -2
  44. package/dist/{copy.d-DLJTyRfT.d.cts → copy.d-C_u7shha.d.cts} +2 -2
  45. package/dist/core/index.cjs +3 -3
  46. package/dist/core/index.d.cts +20 -18
  47. package/dist/core/index.d.ts +20 -18
  48. package/dist/core/index.js +3 -3
  49. package/dist/{depth.d-OSALbYM7.d.ts → depth.d-COFxYWLU.d.ts} +6 -133
  50. package/dist/{depth.d-CjPGVPDL.d.cts → depth.d-D2e5WZuE.d.cts} +6 -133
  51. package/dist/{entitlementRepository.d-CVQa1DA1.d.cts → entitlementRepository.d-BP15dFbe.d.cts} +4 -4
  52. package/dist/{entitlementRepository.d-Cf3LbTwD.d.ts → entitlementRepository.d-DLuxnGi5.d.ts} +4 -4
  53. package/dist/{features.d-fNsGcg0R.d.ts → features.d-DrQxTw3-.d.cts} +1 -1
  54. package/dist/{features.d-fNsGcg0R.d.cts → features.d-DrQxTw3-.d.ts} +1 -1
  55. package/dist/{focus.d-DMg2ngHI.d.ts → focus.d-C0Tr0oVJ.d.ts} +109 -348
  56. package/dist/{focus.d-az9cqUz3.d.cts → focus.d-jQWp0hdK.d.cts} +109 -348
  57. package/dist/health-plan/index.cjs +165 -151
  58. package/dist/health-plan/index.d.cts +53 -11
  59. package/dist/health-plan/index.d.ts +53 -11
  60. package/dist/health-plan/index.js +169 -155
  61. package/dist/{idempotency.d-D461_DPD.d.cts → idempotency.d-DXb1BN2A.d.ts} +151 -6
  62. package/dist/{idempotency.d-WpXx9zQo.d.ts → idempotency.d-HF6fyRt2.d.cts} +151 -6
  63. package/dist/{identity.d-DzTijonw.d.ts → identity.d-BePPZ7Uv.d.ts} +1 -1
  64. package/dist/{identity.d-60LeJt_s.d.cts → identity.d-CJfnWOdH.d.cts} +1 -1
  65. package/dist/index.cjs +46 -44
  66. package/dist/index.d.cts +19 -18
  67. package/dist/index.d.ts +19 -18
  68. package/dist/index.js +46 -44
  69. package/dist/introEvents.d-BkGDT_kG.d.cts +175 -0
  70. package/dist/introEvents.d-DHlMvmC7.d.ts +175 -0
  71. package/dist/introEvents.d-dS3fJCH1.d.cts +5 -0
  72. package/dist/introEvents.d-dS3fJCH1.d.ts +5 -0
  73. package/dist/{models.d-BnLm3VAA.d.cts → models.d-BSqvbTE1.d.cts} +8 -1
  74. package/dist/{models.d-BagXhafD.d.ts → models.d-DOwnr8fi.d.ts} +8 -1
  75. package/dist/notifications/index.d.cts +4 -4
  76. package/dist/notifications/index.d.ts +4 -4
  77. package/dist/{optInView.d-CEyHR6PK.d.cts → optInView.d-0iI5JoAf.d.cts} +119 -3
  78. package/dist/{optInView.d-acKpV8V2.d.ts → optInView.d-s-w4aGN3.d.ts} +119 -3
  79. package/dist/{parse.d-C8CXyS58.d.ts → parse.d-COt1qVA6.d.ts} +1 -1
  80. package/dist/{parse.d-tEzufgJX.d.cts → parse.d-EmsgOUMQ.d.cts} +1 -1
  81. package/dist/{pets.d-C_53_fzo.d.ts → pets.d-BFT_b53y.d.ts} +1 -1
  82. package/dist/{pets.d-NbJvP_kh.d.cts → pets.d-nNAVnw7f.d.cts} +1 -1
  83. package/dist/{petsRepository.d-lp1BHRqM.d.cts → petsRepository.d-B2TpRE7r.d.cts} +1 -1
  84. package/dist/{petsRepository.d-BuGHymNx.d.ts → petsRepository.d-RGwSZcYl.d.ts} +1 -1
  85. package/dist/planSignals.d-BDbp2e-k.d.cts +126 -0
  86. package/dist/planSignals.d-DSnxKoWe.d.ts +126 -0
  87. package/dist/{ports.d-COIyN624.d.ts → ports.d-D2n4HRUy.d.ts} +4 -4
  88. package/dist/{ports.d-CEROoqnA.d.cts → ports.d-DBA_gsq5.d.cts} +4 -4
  89. package/dist/{presentation.d-DMbdad7G.d.cts → presentation.d-vy8kTGfR.d.cts} +6 -0
  90. package/dist/{presentation.d-DMbdad7G.d.ts → presentation.d-vy8kTGfR.d.ts} +6 -0
  91. package/dist/quickPrompts.d-NM_81Jc1.d.cts +19 -0
  92. package/dist/quickPrompts.d-NM_81Jc1.d.ts +19 -0
  93. package/dist/records/depth/index.d.cts +13 -9
  94. package/dist/records/depth/index.d.ts +13 -9
  95. package/dist/records/index.cjs +252 -138
  96. package/dist/records/index.d.cts +88 -23
  97. package/dist/records/index.d.ts +88 -23
  98. package/dist/records/index.js +253 -139
  99. package/dist/{requestFunnel.d-CXUMPw1K.d.ts → requestFunnel.d-D9edIEjZ.d.ts} +2 -2
  100. package/dist/{requestFunnel.d-DWQQpjFR.d.cts → requestFunnel.d-RZex94XX.d.cts} +2 -2
  101. package/dist/{resolve.d-jI8FmBj3.d.cts → resolve.d-CoQWUy1Y.d.cts} +1 -1
  102. package/dist/{resolve.d-jI8FmBj3.d.ts → resolve.d-CoQWUy1Y.d.ts} +1 -1
  103. package/dist/{runtimeTypes.d-4yFNNuYR.d.ts → runtimeTypes.d-BYq38b17.d.ts} +6 -6
  104. package/dist/{runtimeTypes.d-D6N_fhxx.d.cts → runtimeTypes.d-LkwZaF7z.d.cts} +6 -6
  105. package/dist/{useRecordsDepth.d-DFcCfiXm.d.ts → screenProps.d-BVzRzowC.d.ts} +5 -91
  106. package/dist/{useRecordsDepth.d-sAq2Qkhr.d.cts → screenProps.d-CQ0qZJkr.d.cts} +5 -91
  107. package/dist/server/events/index.cjs +1 -1
  108. package/dist/server/events/index.d.cts +2 -2
  109. package/dist/server/events/index.d.ts +2 -2
  110. package/dist/server/events/index.js +1 -1
  111. package/dist/server/index.cjs +1 -1
  112. package/dist/server/index.d.cts +3 -3
  113. package/dist/server/index.d.ts +3 -3
  114. package/dist/server/index.js +1 -1
  115. package/dist/{sheetSeam.d-Cviqk89n.d.ts → sheetSeam.d-B09jf4YC.d.ts} +8 -4
  116. package/dist/{sheetSeam.d-DCS3LW8g.d.cts → sheetSeam.d-BBuEIVsa.d.cts} +8 -4
  117. package/dist/shop/index.cjs +224 -58
  118. package/dist/shop/index.d.cts +23 -5
  119. package/dist/shop/index.d.ts +23 -5
  120. package/dist/shop/index.js +225 -59
  121. package/dist/tabs/index.cjs +195 -0
  122. package/dist/tabs/index.d.cts +174 -0
  123. package/dist/tabs/index.d.ts +174 -0
  124. package/dist/tabs/index.js +195 -0
  125. package/dist/tabsModel.d-BfIQg6yS.d.cts +31 -0
  126. package/dist/tabsModel.d-BfIQg6yS.d.ts +31 -0
  127. package/dist/televet/booking/index.d.cts +6 -6
  128. package/dist/televet/booking/index.d.ts +6 -6
  129. package/dist/testing/index.cjs +1 -1
  130. package/dist/testing/index.d.cts +1 -1
  131. package/dist/testing/index.d.ts +1 -1
  132. package/dist/testing/index.js +1 -1
  133. package/dist/testing/rn/index.cjs +1 -1
  134. package/dist/testing/rn/index.d.cts +11 -11
  135. package/dist/testing/rn/index.d.ts +11 -11
  136. package/dist/testing/rn/index.js +1 -1
  137. package/dist/testing/web/index.d.cts +12 -12
  138. package/dist/testing/web/index.d.ts +12 -12
  139. package/dist/texting/index.cjs +40 -5
  140. package/dist/texting/index.d.cts +40 -7
  141. package/dist/texting/index.d.ts +40 -7
  142. package/dist/texting/index.js +40 -5
  143. package/dist/threadOptions.d-9r4Csa7k.d.cts +458 -0
  144. package/dist/threadOptions.d-B6GA09aM.d.ts +458 -0
  145. package/dist/{timelineRows.d-CU5GvvLk.d.ts → timelineRows.d-Bes8ip2v.d.ts} +1 -1
  146. package/dist/{timelineRows.d-BNxgzYRW.d.cts → timelineRows.d-BvM2A7_G.d.cts} +1 -1
  147. package/dist/{typeStyle.d-C1HBRAI3.d.ts → typeStyle.d-Co5KF0up.d.ts} +1 -1
  148. package/dist/{typeStyle.d-Bl8pzbBy.d.cts → typeStyle.d-xIZj02Ru.d.cts} +1 -1
  149. package/dist/useIntroSeen.d-CTWFUthO.d.cts +35 -0
  150. package/dist/useIntroSeen.d-CTWFUthO.d.ts +35 -0
  151. package/dist/usePresentation.d-BGz32Vlm.d.ts +285 -0
  152. package/dist/usePresentation.d-DYTF_ZGf.d.cts +285 -0
  153. package/dist/{useRecords.d-Cb-36SF5.d.cts → useRecords.d-BYNX01El.d.cts} +2 -2
  154. package/dist/{useRecords.d-aQTzQZoV.d.ts → useRecords.d-DWk61a4c.d.ts} +2 -2
  155. package/dist/useRecordsDepth.d--LLA_4ga.d.cts +32 -0
  156. package/dist/useRecordsDepth.d-BQRL0Hez.d.ts +32 -0
  157. package/dist/{view.d-Dps5C8-s.d.cts → view.d-0yBjLTV3.d.cts} +6 -4
  158. package/dist/{view.d-C-SNpDJX.d.ts → view.d-DqbCADFa.d.ts} +6 -4
  159. package/dist/web/consent/index.d.cts +5 -5
  160. package/dist/web/consent/index.d.ts +5 -5
  161. package/dist/web/health-plan/index.cjs +50 -43
  162. package/dist/web/health-plan/index.d.cts +46 -192
  163. package/dist/web/health-plan/index.d.ts +46 -192
  164. package/dist/web/health-plan/index.js +65 -58
  165. package/dist/web/index.cjs +61 -45
  166. package/dist/web/index.d.cts +165 -25
  167. package/dist/web/index.d.ts +165 -25
  168. package/dist/web/index.js +62 -46
  169. package/dist/web/intro/index.cjs +167 -0
  170. package/dist/web/intro/index.d.cts +79 -0
  171. package/dist/web/intro/index.d.ts +79 -0
  172. package/dist/web/intro/index.js +167 -0
  173. package/dist/web/notifications/index.d.cts +3 -3
  174. package/dist/web/notifications/index.d.ts +3 -3
  175. package/dist/web/records/depth/index.d.cts +13 -9
  176. package/dist/web/records/depth/index.d.ts +13 -9
  177. package/dist/web/records/index.cjs +7 -7
  178. package/dist/web/records/index.d.cts +21 -82
  179. package/dist/web/records/index.d.ts +21 -82
  180. package/dist/web/records/index.js +7 -7
  181. package/dist/web/records-sheet/index.cjs +181 -127
  182. package/dist/web/records-sheet/index.d.cts +18 -16
  183. package/dist/web/records-sheet/index.d.ts +18 -16
  184. package/dist/web/records-sheet/index.js +181 -127
  185. package/dist/web/shop/index.cjs +191 -76
  186. package/dist/web/shop/index.d.cts +21 -4
  187. package/dist/web/shop/index.d.ts +21 -4
  188. package/dist/web/shop/index.js +191 -76
  189. package/dist/web/televet/booking/index.d.cts +6 -6
  190. package/dist/web/televet/booking/index.d.ts +6 -6
  191. package/dist/web/texting/index.cjs +36 -5
  192. package/dist/web/texting/index.d.cts +40 -7
  193. package/dist/web/texting/index.d.ts +40 -7
  194. package/dist/web/texting/index.js +36 -5
  195. package/package.json +35 -4
  196. package/tabs/package.json +8 -0
  197. package/web/intro/native-blocked.cjs +12 -0
  198. package/web/intro/package.json +8 -0
  199. package/dist/threadOptions.d-B1pTMmDF.d.cts +0 -260
  200. package/dist/threadOptions.d-B1pTMmDF.d.ts +0 -260
  201. package/dist/usePresentation.d-D6qsFzBz.d.cts +0 -9
  202. package/dist/usePresentation.d-DuGQe_Do.d.ts +0 -9
@@ -1,4 +1,4 @@
1
- import{createContext,forwardRef,createElement,useRef,useMemo,useState,useCallback,useEffect,useReducer,useContext,useSyncExternalStore,Component}from"react";import{z}from"zod";import{TextInput as TextInput$1,Platform,View,Pressable,ScrollView,ActivityIndicator,StyleSheet,PanResponder,KeyboardAvoidingView,Keyboard,Image,BackHandler,Text as Text$1,Dimensions,Modal,RefreshControl,Linking,AccessibilityInfo,Share,useColorScheme,PixelRatio}from"react-native";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import{useSafeAreaInsets}from"react-native-safe-area-context";var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
1
+ import{createContext,forwardRef,createElement,useRef,useMemo,useState,useCallback,useEffect,useReducer,useContext,useSyncExternalStore,Component}from"react";import{z}from"zod";import{TextInput as TextInput$1,Platform,View,Pressable,ScrollView,ActivityIndicator,StyleSheet,PanResponder,KeyboardAvoidingView,Keyboard,Image,AppState,BackHandler,Text as Text$1,Dimensions,Modal,RefreshControl,Linking,AccessibilityInfo,Share,Animated,Easing,useColorScheme,PixelRatio}from"react-native";import{jsx,jsxs,Fragment}from"react/jsx-runtime";import{useSafeAreaInsets}from"react-native-safe-area-context";var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
2
2
  /* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
3
3
  /* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
4
4
  /* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
@@ -96,28 +96,28 @@ return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
96
96
  return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var RECORD_SHARE_AUDIENCES=/* @__PURE__ */Object.freeze(["vet","groomer","boarding"]),https=/* @__PURE__ */z.string().min(1).refine(value=>value.startsWith("https://")),str=/* @__PURE__ */z.string().nullish(),audienceField=/* @__PURE__ */z.unknown().optional(),linkSchema=/* @__PURE__ */z.object({share_id:/* @__PURE__ */z.string().min(1),share_url:/* @__PURE__ */z.string().min(1),expires_at:str,audience:audienceField}),listSchema=/* @__PURE__ */z.object({shares:/* @__PURE__ */z.array(/* @__PURE__ */z.object({share_id:/* @__PURE__ */z.string().min(1),expires_at:str,created_at:str,view_count:/* @__PURE__ */z.number().int().nonnegative().nullish(),last_viewed_at:str,audience:audienceField})).optional()}),pdfSchema=/* @__PURE__ */z.object({download_url:https,expires_at:str}),emailSchema=/* @__PURE__ */z.object({share_id:/* @__PURE__ */z.string().min(1),expires_at:str,audience:audienceField}),scopeSchema=/* @__PURE__ */z.object({audience:/* @__PURE__ */z.string().min(1),sections:/* @__PURE__ */z.array(/* @__PURE__ */z.string()),entity_types:/* @__PURE__ */z.array(/* @__PURE__ */z.string()).nullable()}),SHARE_RECIPIENT_EMAIL_MAX=254;function isShareRecipientEmail(value){let trimmed=value.trim();return trimmed.length>0&&trimmed.length<=SHARE_RECIPIENT_EMAIL_MAX&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed)}var isAudience=value=>typeof value=="string"&&RECORD_SHARE_AUDIENCES.includes(value);function audienceOf(value){return isAudience(value)?value:null}function mapShareAudiences(wire){let parsed=z.array(scopeSchema).safeParse(wire);if(!parsed.success)/* @__PURE__ */return Object.freeze([]);let seen=/* @__PURE__ */new Set,scopes=[];for(let scope of parsed.data)!isAudience(scope.audience)||seen.has(scope.audience)||(seen.add(scope.audience),scopes.push(/* @__PURE__ */Object.freeze({audience:scope.audience,sections:/* @__PURE__ */Object.freeze([...scope.sections]),entityTypes:scope.entity_types===null?null:/* @__PURE__ */Object.freeze([...scope.entity_types])}))/* @__PURE__ */);return Object.freeze(scopes)}function resolveShareUrl(shareUrl,apiBaseUrl){let trimmed=shareUrl.trim();if(trimmed.length===0)return null;try{let absolute=/^[a-z][a-z0-9+.-]*:/i.test(trimmed)?new URL(trimmed):apiBaseUrl!==void 0?new URL(trimmed,apiBaseUrl):null;return absolute===null||absolute.protocol!=="https:"?null:absolute.toString()}catch{return null}}function mapRecordShareLink(wire,apiBaseUrl){let parsed=linkSchema.safeParse(wire);if(!parsed.success)return null;let shareUrl=resolveShareUrl(parsed.data.share_url,apiBaseUrl);return shareUrl===null?null:/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,shareUrl:shareUrl,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)})}function mapRecordShareList(wire){let parsed=listSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze((parsed.data.shares??[]).map(share=>/* @__PURE__ */Object.freeze({shareId:share.share_id,expiresAt:share.expires_at??null,createdAt:share.created_at??null,viewCount:share.view_count??0,lastViewedAt:share.last_viewed_at??null,audience:audienceOf(share.audience)}))):null}function mapRecordShareEmailReceipt(wire){let parsed=emailSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)}):null}function mapRecordPdfLink(wire){let parsed=pdfSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({downloadUrl:parsed.data.download_url,expiresAt:parsed.data.expires_at??null}):null}var RECORDS_PDF_CONTENT_TYPE="application/pdf",RECORDS_PHOTO_CONTENT_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),isPhotoType=value=>RECORDS_PHOTO_CONTENT_TYPES.includes(value);function isAcceptedUploadType(type,types){return type===RECORDS_PDF_CONTENT_TYPE||types!==void 0&&isPhotoType(type)&&types.includes(type)}var RECORDS_FEATURES_PDF_ONLY=/* @__PURE__ */Object.freeze({features:/* @__PURE__ */Object.freeze({}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE]),shareAudiences:/* @__PURE__ */Object.freeze([])}),featuresSchema=/* @__PURE__ */z.object({features:/* @__PURE__ */z.record(/* @__PURE__ */z.boolean()),upload_content_types:/* @__PURE__ */z.array(/* @__PURE__ */z.string()).nullish(),share_audiences:/* @__PURE__ */z.unknown().optional()});function mapRecordsFeatures(wire){let parsed=featuresSchema.safeParse(wire);if(!parsed.success)return RECORDS_FEATURES_PDF_ONLY;let listed=parsed.data.upload_content_types??[],photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>listed.includes(type));/* @__PURE__ */
97
97
  return Object.freeze({features:/* @__PURE__ */Object.freeze({...parsed.data.features}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE,...photos]),shareAudiences:mapShareAudiences(parsed.data.share_audiences)})}function acceptsPhotos(types){return types!==void 0&&types.some(isPhotoType)}var KNOWN_STATUSES=/* @__PURE__ */new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),STATUS_ALIASES=/* @__PURE__ */Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function normalizeStatus(raw){let aliased=Object.prototype.hasOwnProperty.call(STATUS_ALIASES,raw)?STATUS_ALIASES[raw]:void 0;if(aliased!==void 0)return aliased;let value=raw;return KNOWN_STATUSES.has(value)?value:"parsing"}function normalizeOrigin(raw){return raw==="owner_reported"||raw==="clinic_document"?raw:null}var requestSchema=/* @__PURE__ */z.object({request_id:/* @__PURE__ */z.string().min(1),pet_ref:/* @__PURE__ */z.string().min(1),status:/* @__PURE__ */z.string(),simple_status:/* @__PURE__ */z.string().nullish(),simple_status_detail:/* @__PURE__ */z.string().nullish(),status_label:/* @__PURE__ */z.string().optional(),dispatch_status:/* @__PURE__ */z.string().nullish(),can_retry_send:/* @__PURE__ */z.boolean().optional(),can_revoke:/* @__PURE__ */z.boolean().optional(),can_convert_to_upload:/* @__PURE__ */z.boolean().optional(),can_update_clinic_email:/* @__PURE__ */z.boolean().optional(),reminder_count:/* @__PURE__ */z.number().int().nonnegative().optional(),last_reminder_at:/* @__PURE__ */z.string().nullish(),waiting_expectation:/* @__PURE__ */z.string().nullish(),document_count:/* @__PURE__ */z.number().optional(),held_item_count:/* @__PURE__ */z.number().optional(),received_at:/* @__PURE__ */z.string().nullish(),parsing_started_at:/* @__PURE__ */z.string().nullish(),review_started_at:/* @__PURE__ */z.string().nullish(),created_at:/* @__PURE__ */z.string().optional(),updated_at:/* @__PURE__ */z.string().optional(),source:/* @__PURE__ */z.string().nullish().catch(null),action_needed_label:/* @__PURE__ */z.string().nullish().catch(null),failure_reason:/* @__PURE__ */z.string().nullish().catch(null),failure_code:/* @__PURE__ */z.string().nullish().catch(null),recovery_stage:/* @__PURE__ */z.string().nullish().catch(null),show_clinic_phone:/* @__PURE__ */z.boolean().optional().catch(void 0),clinic_name:/* @__PURE__ */z.string().nullish().catch(null),clinic_email:/* @__PURE__ */z.string().nullish().catch(null),clinic_phone:/* @__PURE__ */z.string().nullish().catch(null),converted_to_upload_at:/* @__PURE__ */z.string().nullish().catch(null),request_group_id:/* @__PURE__ */z.string().nullish().catch(null)}).passthrough();function mapRequestView(wire){let parsed=requestSchema.safeParse(wire);if(!parsed.success)return null;let w=parsed.data,simpleStatus=normalizeSimpleStatus(w.simple_status),status=simpleStatus==="requested"&&(w.status==="awaiting_upload"||w.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":simpleStatus==="parsing"&&(w.simple_status_detail==="in_review"||w.simple_status_detail==="review_email_failed")?"in_review":simpleStatus??normalizeStatus(w.status);/* @__PURE__ */
98
98
  return Object.freeze({id:w.request_id,petRef:w.pet_ref,status:status,simpleStatus:simpleStatus,simpleStatusDetail:w.simple_status_detail??null,statusLabel:w.status_label??"",dispatchStatus:w.dispatch_status??null,canRetrySend:w.can_retry_send===true,canRevoke:w.can_revoke===true,canConvertToUpload:w.can_convert_to_upload===true,canUpdateClinicEmail:w.can_update_clinic_email===true,reminderCount:w.reminder_count??0,lastReminderAt:w.last_reminder_at??null,waitingExpectation:w.waiting_expectation??null,documentCount:numberOr(w.document_count,0),heldItemCount:numberOr(w.held_item_count,0),receivedAt:w.received_at??null,parsingStartedAt:w.parsing_started_at??null,reviewStartedAt:w.review_started_at??null,createdAt:w.created_at??"",updatedAt:w.updated_at??"",wireStatus:w.status,source:w.source??null,actionNeededLabel:w.action_needed_label??null,failureReason:w.failure_reason??null,failureCode:w.failure_code??null,recoveryStage:w.recovery_stage??null,showClinicPhone:w.show_clinic_phone===true,clinicName:w.clinic_name??null,clinicEmail:w.clinic_email??null,clinicPhone:w.clinic_phone??null,convertedToUploadAt:w.converted_to_upload_at??null,requestGroupId:w.request_group_id??null})}var groupSchema=/* @__PURE__ */z.object({request_group_id:/* @__PURE__ */z.string().min(1),pet_ref:/* @__PURE__ */z.string().min(1),total:/* @__PURE__ */z.number().int().nonnegative(),responded:/* @__PURE__ */z.number().int().nonnegative(),pending:/* @__PURE__ */z.number().int().nonnegative(),members:/* @__PURE__ */z.array(/* @__PURE__ */z.unknown())});function mapRequestGroup(wire){let parsed=groupSchema.safeParse(wire);if(!parsed.success)return null;let g=parsed.data,members=mapRequestList(g.members);return members.some(member=>member.petRef!==g.pet_ref)?null:/* @__PURE__ */Object.freeze({requestGroupId:g.request_group_id,petRef:g.pet_ref,total:g.total,responded:g.responded,pending:g.pending,members:members})}function normalizeSimpleStatus(raw){return!raw||raw==="awaiting_upload"||raw==="in_review"?null:KNOWN_STATUSES.has(raw)?raw:null}function mapRequestList(wire){let list=Array.isArray(wire)?wire:[],out=[];for(let entry of list){let view=mapRequestView(entry);view!==null&&out.push(view)}/* @__PURE__ */
99
- return Object.freeze(out)}var acceptedSchema=/* @__PURE__ */z.object({source_doc_id:/* @__PURE__ */z.string().min(1),request_id:/* @__PURE__ */z.string().min(1)});function mapUploadedDocument(wire){let parsed=acceptedSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({documentId:parsed.data.source_doc_id,requestId:parsed.data.request_id,status:"received"}):null}var identitySchema=/* @__PURE__ */z.object({label:/* @__PURE__ */z.string(),value:/* @__PURE__ */z.string()}),entitySchema=/* @__PURE__ */z.object({key:/* @__PURE__ */z.string(),category:/* @__PURE__ */z.string().optional(),label:/* @__PURE__ */z.string().optional(),value:/* @__PURE__ */z.string().nullish(),unit:/* @__PURE__ */z.string().nullish(),observed_at:/* @__PURE__ */z.string().nullish(),status:/* @__PURE__ */z.string().nullish(),origin:/* @__PURE__ */z.string().nullish(),canonical_key:/* @__PURE__ */z.string().nullish()}),seriesPointSchema=/* @__PURE__ */z.object({at:/* @__PURE__ */z.string(),value:/* @__PURE__ */z.number().nullish(),display:/* @__PURE__ */z.string().nullish(),origin:/* @__PURE__ */z.string().nullish()}),seriesSchema=/* @__PURE__ */z.object({key:/* @__PURE__ */z.string(),label:/* @__PURE__ */z.string().optional(),points:/* @__PURE__ */z.array(seriesPointSchema).optional()}),forwardSchema=/* @__PURE__ */z.object({title:/* @__PURE__ */z.string(),detail:/* @__PURE__ */z.string().nullish(),due_at:/* @__PURE__ */z.string().nullish()}),documentSchema=/* @__PURE__ */z.object({doc_id:/* @__PURE__ */z.string(),title:/* @__PURE__ */z.string().nullish(),document_class:/* @__PURE__ */z.string().nullish(),page_count:/* @__PURE__ */z.number().nullish(),received_at:/* @__PURE__ */z.string().nullish()});function mapEntityRow(e){/* @__PURE__ */
99
+ return Object.freeze(out)}var acceptedSchema=/* @__PURE__ */z.object({source_doc_id:/* @__PURE__ */z.string().min(1),request_id:/* @__PURE__ */z.string().min(1)});function mapUploadedDocument(wire){let parsed=acceptedSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({documentId:parsed.data.source_doc_id,requestId:parsed.data.request_id,status:"received"}):null}var identitySchema=/* @__PURE__ */z.object({label:/* @__PURE__ */z.string(),value:/* @__PURE__ */z.string()}),entitySchema=/* @__PURE__ */z.object({key:/* @__PURE__ */z.string(),category:/* @__PURE__ */z.string().optional(),label:/* @__PURE__ */z.string().optional(),value:/* @__PURE__ */z.string().nullish(),unit:/* @__PURE__ */z.string().nullish(),observed_at:/* @__PURE__ */z.string().nullish(),status:/* @__PURE__ */z.string().nullish(),origin:/* @__PURE__ */z.string().nullish(),canonical_key:/* @__PURE__ */z.string().nullish()}),seriesPointSchema=/* @__PURE__ */z.object({at:/* @__PURE__ */z.string(),value:/* @__PURE__ */z.number().nullish(),display:/* @__PURE__ */z.string().nullish(),origin:/* @__PURE__ */z.string().nullish()}),seriesSchema=/* @__PURE__ */z.object({key:/* @__PURE__ */z.string(),label:/* @__PURE__ */z.string().optional(),points:/* @__PURE__ */z.array(seriesPointSchema).optional()}),forwardSchema=/* @__PURE__ */z.object({title:/* @__PURE__ */z.string(),detail:/* @__PURE__ */z.string().nullish(),due_at:/* @__PURE__ */z.string().nullish(),care_item_key:/* @__PURE__ */z.string().nullish(),due_date_source:/* @__PURE__ */z.string().nullish()}),documentSchema=/* @__PURE__ */z.object({doc_id:/* @__PURE__ */z.string(),title:/* @__PURE__ */z.string().nullish(),document_class:/* @__PURE__ */z.string().nullish(),page_count:/* @__PURE__ */z.number().nullish(),received_at:/* @__PURE__ */z.string().nullish()});function mapEntityRow(e){/* @__PURE__ */
100
100
  return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:normalizeOrigin(e.origin),canonicalKey:e.canonical_key??null})}function mapDocumentRow(d){/* @__PURE__ */
101
- return Object.freeze({docId:d.doc_id,title:d.title??null,documentClass:d.document_class??null,pageCount:d.page_count??null,receivedAt:d.received_at??null})}var contentSchema=/* @__PURE__ */z.object({identity:/* @__PURE__ */z.array(identitySchema).optional(),entities:/* @__PURE__ */z.array(entitySchema).optional(),entity_series:/* @__PURE__ */z.array(seriesSchema).optional(),forward_looking:/* @__PURE__ */z.array(forwardSchema).optional(),documents:/* @__PURE__ */z.array(documentSchema).optional()});function mapRecordView(petRef,wire){let w=isObject(wire)?wire:{},schemaVersion=strOr(w.schema_version,"epdf/1.0"),disclaimer=strOr(w.disclaimer,""),pet=typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef;if(w.withheld===true)return withheldView(pet,schemaVersion,disclaimer);let content=contentSchema.safeParse(w);if(!content.success)return withheldView(pet,schemaVersion,disclaimer);let c=content.data,identity=(c.identity??[]).map(i=>/* @__PURE__ */Object.freeze({label:i.label,value:i.value})),entities=(c.entities??[]).map(mapEntityRow),entitySeries=(c.entity_series??[]).map(s=>/* @__PURE__ */Object.freeze({key:s.key,label:s.label??s.key,points:/* @__PURE__ */Object.freeze((s.points??[]).map(p=>/* @__PURE__ */Object.freeze({at:p.at,value:p.value??null,display:p.display??null,origin:normalizeOrigin(p.origin)})))})),forwardLooking=(c.forward_looking??[]).map(f=>/* @__PURE__ */Object.freeze({title:f.title,detail:f.detail??null,dueAt:f.due_at??null})),documents={};for(let d of c.documents??[])documents[d.doc_id]=mapDocumentRow(d);let isEmpty=w.is_empty===true||identity.length===0&&entities.length===0&&entitySeries.length===0&&forwardLooking.length===0&&Object.keys(documents).length===0;/* @__PURE__ */
101
+ return Object.freeze({docId:d.doc_id,title:d.title??null,documentClass:d.document_class??null,pageCount:d.page_count??null,receivedAt:d.received_at??null})}var contentSchema=/* @__PURE__ */z.object({identity:/* @__PURE__ */z.array(identitySchema).optional(),entities:/* @__PURE__ */z.array(entitySchema).optional(),entity_series:/* @__PURE__ */z.array(seriesSchema).optional(),forward_looking:/* @__PURE__ */z.array(forwardSchema).optional(),documents:/* @__PURE__ */z.array(documentSchema).optional()});function mapRecordView(petRef,wire){let w=isObject(wire)?wire:{},schemaVersion=strOr(w.schema_version,"epdf/1.0"),disclaimer=strOr(w.disclaimer,""),pet=typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef;if(w.withheld===true)return withheldView(pet,schemaVersion,disclaimer);let content=contentSchema.safeParse(w);if(!content.success)return withheldView(pet,schemaVersion,disclaimer);let c=content.data,identity=(c.identity??[]).map(i=>/* @__PURE__ */Object.freeze({label:i.label,value:i.value})),entities=(c.entities??[]).map(mapEntityRow),entitySeries=(c.entity_series??[]).map(s=>/* @__PURE__ */Object.freeze({key:s.key,label:s.label??s.key,points:/* @__PURE__ */Object.freeze((s.points??[]).map(p=>/* @__PURE__ */Object.freeze({at:p.at,value:p.value??null,display:p.display??null,origin:normalizeOrigin(p.origin)})))})),forwardLooking=(c.forward_looking??[]).map(f=>/* @__PURE__ */Object.freeze({title:f.title,detail:f.detail??null,dueAt:f.due_at??null,careItemKey:f.care_item_key??null,dueDateSource:f.due_date_source==="vet_stated"||f.due_date_source==="derived_default_rule"?f.due_date_source:null})),documents={};for(let d of c.documents??[])documents[d.doc_id]=mapDocumentRow(d);let isEmpty=w.is_empty===true||identity.length===0&&entities.length===0&&entitySeries.length===0&&forwardLooking.length===0&&Object.keys(documents).length===0;/* @__PURE__ */
102
102
  return Object.freeze({petRef:pet,schemaVersion:schemaVersion,isEmpty:isEmpty,withheld:false,generatedAt:strOrNull(w.generated_at),identity:/* @__PURE__ */Object.freeze(identity),entities:/* @__PURE__ */Object.freeze(entities),entitySeries:/* @__PURE__ */Object.freeze(entitySeries),forwardLooking:/* @__PURE__ */Object.freeze(forwardLooking),documents:/* @__PURE__ */Object.freeze(documents),disclaimer:disclaimer})}function withheldView(petRef,schemaVersion,disclaimer){/* @__PURE__ */
103
103
  return Object.freeze({petRef:petRef,schemaVersion:schemaVersion,isEmpty:false,withheld:true,generatedAt:null,identity:/* @__PURE__ */Object.freeze([]),entities:/* @__PURE__ */Object.freeze([]),entitySeries:/* @__PURE__ */Object.freeze([]),forwardLooking:/* @__PURE__ */Object.freeze([]),documents:/* @__PURE__ */Object.freeze({}),disclaimer:disclaimer})}var consentSchema=/* @__PURE__ */z.object({pet_ref:/* @__PURE__ */z.string().optional(),granted:/* @__PURE__ */z.boolean().optional(),version:/* @__PURE__ */z.string().nullish(),granted_at:/* @__PURE__ */z.string().nullish()});function mapConsent(petRef,wire){let parsed=consentSchema.safeParse(wire),data=parsed.success?parsed.data:{};/* @__PURE__ */
104
- return Object.freeze({petRef:typeof data.pet_ref=="string"&&data.pet_ref.length>0?data.pet_ref:petRef,granted:data.granted===true,version:data.version??null,grantedAt:data.granted_at??null})}function isObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function numberOr(v,fallback){return typeof v=="number"&&Number.isFinite(v)?v:fallback}function strOr(v,fallback){return typeof v=="string"&&v.length>0?v:fallback}function strOrNull(v){return typeof v=="string"&&v.length>0?v:null}var RECORDS_TERMINAL=/* @__PURE__ */Object.freeze(["published","failed","revoked"]);function isTerminalStatus(status){return RECORDS_TERMINAL.includes(status)}function recordsDenialReasonOf(error){if(error===null)return null;let reason=error.recordsReason;return reason==="consent_required"||reason==="session_required"||reason==="entitlement"||reason==="pet_not_found"?reason:null}var RECORDS_CONSENT_REQUIRED_WIRE_CODE="records_consent_required";function recordsWireCodeOf(error){let raw=error.raw;if(raw===null||typeof raw!="object")return null;let body=raw,code=typeof body.error=="object"&&body.error!==null?body.error.code:body.code;return typeof code=="string"&&code.length>0?code:null}function isRecordsConsentRequired(error){return error===null||error.httpStatus!==409?false:recordsWireCodeOf(error)===RECORDS_CONSENT_REQUIRED_WIRE_CODE}var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var noopRecordsTelemetry=/* @__PURE__ */Object.freeze({record(){}}),MAX_UPLOAD_BYTES=25*1024*1024,CONSENT_VERSION_MAX=64,IDEMPOTENCY_KEY_MAX=128,PET_REF_MAX=128;var UPLOAD_DEADLINE_MS=9e4;function createRecordsController(deps){return new RecordsControllerImpl(deps)}var RecordsControllerImpl=class{constructor(deps){this.recordCache=/* @__PURE__ */new Map;this.consentEpoch=/* @__PURE__ */new Map;this.reportedGaps=/* @__PURE__ */new Set;this.features=RECORDS_FEATURES_PDF_ONLY;this.repository=deps.repository,this.uploads=deps.uploads,this.telemetry=deps.telemetry??noopRecordsTelemetry,this.newIdempotencyKey=deps.newIdempotencyKey??defaultIdempotencyFactory(),this.timers=deps.timers??defaultTimers,this.uploadDeadlineMs=deps.uploadDeadlineMs??UPLOAD_DEADLINE_MS}async createUploadRequest(input){let res=await this.repository.createRequest({pet_ref:input.petRef,idempotency_key:input.idempotencyKey});if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async getRequest(id){let res=await this.repository.getRequest(id);if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async listRequests(){let res=await this.repository.listRequests();if(!res.ok)return this.onRequestError(res.error);let views=mapRequestList(res.value);for(let view of views)this.observeRequest(view);return ok(views)}async readFeatures(){let read=this.repository.getFeatures;if(read===void 0)return this.features=RECORDS_FEATURES_PDF_ONLY;let features=RECORDS_FEATURES_PDF_ONLY;try{let res=await read.call(this.repository);res.ok&&(features=mapRecordsFeatures(res.value))}catch{}return this.features=features,features}async uploadDocument(input){let{requestId:requestId2,file:file}=input,rejection=validateFile(file,this.features.uploadContentTypes);if(rejection!==null)return this.telemetry.record("records.upload.rejected",{reason:rejection}),err(uploadFailed(`upload rejected: ${rejection}`));let initiated=await this.repository.initiateUpload(requestId2,{content_type:file.mimeType,file_size:file.sizeBytes});if(!initiated.ok)return this.onRequestError(initiated.error);let s3=await this.postToS3(initiated.value,file,input);if(!s3.ok)return this.telemetry.record("records.upload.failed",{reason:s3.reason}),err(uploadFailed(s3.reason));let completed=await this.repository.completeUpload(requestId2,{upload_id:initiated.value.upload_id});if(!completed.ok)return completed.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:reasonFromWire(completed.error)??"corrupt"}),this.onRequestError(completed.error);let doc=mapUploadedDocument(completed.value);return doc===null?err(internal()):ok(doc)}async postToS3(policy,file,input){let deadline=new AbortController,signal=mergeSignals(deadline.signal,input.signal),handle=this.timers.setTimeout(()=>deadline.abort(),this.uploadDeadlineMs);try{let opts={signal:signal};return input.onProgress&&(opts.onProgress=input.onProgress),await this.uploads.postMultipart(policy,file,opts),{ok:!0}}catch{return{ok:false,reason:deadline.signal.aborted&&input.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(handle)}}async getRecord(pet){let epoch=this.consentEpoch.get(pet)??0,res=await this.repository.getRecord(pet);if(epoch!==(this.consentEpoch.get(pet)??0))return err(/* @__PURE__ */Object.freeze({...makeEverfurError("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!res.ok){let reason=recordsDenialReasonOf(res.error);return reason==="consent_required"?(this.recordCache.delete(pet),this.telemetry.record("records.consent.denied",{pet_ref:pet})):reason==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:pet}),err(res.error)}let view=mapRecordView(pet,res.value);return view.petRef!==pet?err(internal()):view.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:pet}),this.recordCache.delete(pet),ok(view)):(this.recordCache.set(pet,view),ok(view))}peekCachedRecord(pet){return this.recordCache.get(pet)??null}async getConsent(pet){let res=await this.repository.getConsent(pet);return res.ok?ok(mapConsent(pet,res.value)):err(res.error)}async grantConsent(input){let res=await this.repository.putConsent(input.petRef,{consent_version:input.consentVersion,idempotency_key:input.idempotencyKey});return res.ok?ok(mapConsent(input.petRef,res.value)):(recordsDenialReasonOf(res.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:input.petRef}),err(res.error))}async revokeConsent(pet){let res=await this.repository.deleteConsent(pet);return res.ok?(this.consentEpoch.set(pet,(this.consentEpoch.get(pet)??0)+1),this.recordCache.delete(pet),ok(mapConsent(pet,res.value))):err(res.error)}reportCapabilityDenied(pet){this.telemetry.record("records.capability.denied",pet?{pet_ref:pet}:{})}observeRequest(view){view.reviewStartedAt!==null&&!this.reportedGaps.has(view.id)&&(this.reportedGaps.add(view.id),this.telemetry.record("records.parse.gap",{request_id:view.id}))}onRequestError(error){return recordsDenialReasonOf(error)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),err(error)}};function validateFile(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported_format";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"oversize":null}function reasonFromWire(error){let raw=error.wireMessage;return raw==="unsupported_format"||raw==="oversize"||raw==="corrupt"?raw:null}function uploadFailed(wireMessage){return makeEverfurError("mediaUploadFailed",{retryable:false,wireMessage:wireMessage})}function internal(){return makeEverfurError("internalError",{retryable:true})}var defaultTimers={setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle)};function mergeSignals(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}function defaultIdempotencyFactory(){let counter=0;return()=>`records-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
105
- return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms)=>setTimeout(handler,ms),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms,signal)=>delayAbortable(ms,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals2(deadline.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp2({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
104
+ return Object.freeze({petRef:typeof data.pet_ref=="string"&&data.pet_ref.length>0?data.pet_ref:petRef,granted:data.granted===true,version:data.version??null,grantedAt:data.granted_at??null})}function isObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function numberOr(v,fallback){return typeof v=="number"&&Number.isFinite(v)?v:fallback}function strOr(v,fallback){return typeof v=="string"&&v.length>0?v:fallback}function strOrNull(v){return typeof v=="string"&&v.length>0?v:null}var RECORDS_TERMINAL=/* @__PURE__ */Object.freeze(["published","failed","revoked"]);function isTerminalStatus(status){return RECORDS_TERMINAL.includes(status)}function recordsDenialReasonOf(error){if(error===null)return null;let reason=error.recordsReason;return reason==="consent_required"||reason==="session_required"||reason==="entitlement"||reason==="pet_not_found"?reason:null}var RECORDS_CONSENT_REQUIRED_WIRE_CODE="records_consent_required";function recordsWireCodeOf(error){let raw=error.raw;if(raw===null||typeof raw!="object")return null;let body=raw,code=typeof body.error=="object"&&body.error!==null?body.error.code:body.code;return typeof code=="string"&&code.length>0?code:null}function isRecordsConsentRequired(error){return error===null||error.httpStatus!==409?false:recordsWireCodeOf(error)===RECORDS_CONSENT_REQUIRED_WIRE_CODE}var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var noopRecordsTelemetry=/* @__PURE__ */Object.freeze({record(){}}),MAX_UPLOAD_BYTES=25*1024*1024,CONSENT_VERSION_MAX=64,IDEMPOTENCY_KEY_MAX=128,PET_REF_MAX=128;var UPLOAD_DEADLINE_MS=9e4;function createRecordsController(deps){return new RecordsControllerImpl(deps)}var RecordsControllerImpl=class{constructor(deps){this.recordCache=/* @__PURE__ */new Map;this.consentEpoch=/* @__PURE__ */new Map;this.reportedGaps=/* @__PURE__ */new Set;this.features=RECORDS_FEATURES_PDF_ONLY;this.repository=deps.repository,this.uploads=deps.uploads,this.telemetry=deps.telemetry??noopRecordsTelemetry,this.newIdempotencyKey=deps.newIdempotencyKey??defaultIdempotencyFactory(),this.timers=deps.timers??defaultTimers,this.uploadDeadlineMs=deps.uploadDeadlineMs??UPLOAD_DEADLINE_MS}async createUploadRequest(input){let res=await this.repository.createRequest({pet_ref:input.petRef,idempotency_key:input.idempotencyKey});if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async getRequest(id){let res=await this.repository.getRequest(id);if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async listRequests(){let res=await this.repository.listRequests();if(!res.ok)return this.onRequestError(res.error);let views=mapRequestList(res.value);for(let view of views)this.observeRequest(view);return ok(views)}async readFeatures(){let read=this.repository.getFeatures;if(read===void 0)return this.features=RECORDS_FEATURES_PDF_ONLY;let features=RECORDS_FEATURES_PDF_ONLY;try{let res=await read.call(this.repository);res.ok&&(features=mapRecordsFeatures(res.value))}catch{}return this.features=features,features}async uploadDocument(input){let{requestId:requestId2,file:file}=input,rejection=validateFile(file,this.features.uploadContentTypes);if(rejection!==null)return this.telemetry.record("records.upload.rejected",{reason:rejection}),err(uploadFailed(`upload rejected: ${rejection}`));let initiated=await this.repository.initiateUpload(requestId2,{content_type:file.mimeType,file_size:file.sizeBytes});if(!initiated.ok)return this.onRequestError(initiated.error);let s3=await this.postToS3(initiated.value,file,input);if(!s3.ok)return this.telemetry.record("records.upload.failed",{reason:s3.reason}),err(uploadFailed(s3.reason));let completed=await this.repository.completeUpload(requestId2,{upload_id:initiated.value.upload_id});if(!completed.ok)return completed.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:reasonFromWire(completed.error)??"corrupt"}),this.onRequestError(completed.error);let doc=mapUploadedDocument(completed.value);return doc===null?err(internal()):ok(doc)}async postToS3(policy,file,input){let deadline=new AbortController,signal=mergeSignals(deadline.signal,input.signal),handle=this.timers.setTimeout(()=>deadline.abort(),this.uploadDeadlineMs);try{let opts={signal:signal};return input.onProgress&&(opts.onProgress=input.onProgress),await this.uploads.postMultipart(policy,file,opts),{ok:!0}}catch{return{ok:false,reason:deadline.signal.aborted&&input.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(handle)}}async getRecord(pet){let epoch=this.consentEpoch.get(pet)??0,res=await this.repository.getRecord(pet);if(epoch!==(this.consentEpoch.get(pet)??0))return err(/* @__PURE__ */Object.freeze({...makeEverfurError("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!res.ok){let reason=recordsDenialReasonOf(res.error);return reason==="consent_required"?(this.recordCache.delete(pet),this.telemetry.record("records.consent.denied",{pet_ref:pet})):reason==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:pet}),err(res.error)}let view=mapRecordView(pet,res.value);return view.petRef!==pet?err(internal()):view.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:pet}),this.recordCache.delete(pet),ok(view)):(this.recordCache.set(pet,view),ok(view))}peekCachedRecord(pet){return this.recordCache.get(pet)??null}async getConsent(pet){let res=await this.repository.getConsent(pet);return res.ok?ok(mapConsent(pet,res.value)):err(res.error)}async grantConsent(input){let res=await this.repository.putConsent(input.petRef,{consent_version:input.consentVersion,idempotency_key:input.idempotencyKey});return res.ok?ok(mapConsent(input.petRef,res.value)):(recordsDenialReasonOf(res.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:input.petRef}),err(res.error))}async revokeConsent(pet){let res=await this.repository.deleteConsent(pet);return res.ok?(this.consentEpoch.set(pet,(this.consentEpoch.get(pet)??0)+1),this.recordCache.delete(pet),ok(mapConsent(pet,res.value))):err(res.error)}reportCapabilityDenied(pet){this.telemetry.record("records.capability.denied",pet?{pet_ref:pet}:{})}observeRequest(view){view.reviewStartedAt!==null&&!this.reportedGaps.has(view.id)&&(this.reportedGaps.add(view.id),this.telemetry.record("records.parse.gap",{request_id:view.id}))}onRequestError(error){return recordsDenialReasonOf(error)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),err(error)}};function validateFile(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported_format";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"oversize":null}function reasonFromWire(error){let raw=error.wireMessage;return raw==="unsupported_format"||raw==="oversize"||raw==="corrupt"?raw:null}function uploadFailed(wireMessage){return makeEverfurError("mediaUploadFailed",{retryable:false,wireMessage:wireMessage})}function internal(){return makeEverfurError("internalError",{retryable:true})}var defaultTimers={setTimeout:(handler,ms2)=>setTimeout(handler,ms2),clearTimeout:handle=>clearTimeout(handle)};function mergeSignals(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}function defaultIdempotencyFactory(){let counter=0;return()=>`records-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
105
+ return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms2)=>setTimeout(handler,ms2),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms2,signal)=>delayAbortable(ms2,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals2(deadline.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp2({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
106
106
  /* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
107
- return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals2(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms,timers,signal){return ms<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var BASE="/widget/v1/records";function createHttpRecordsRepository(deps){let{auth:auth}=deps,mode=auth.mode,funnel=deps.funnel??createRequestFunnel({auth:auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=async(call,req,kind)=>{let res=await funnel.send(call,req);return res.ok?res:err(tagReason(plainNotFound(res.error),mode,kind))},segmentError=(field,value)=>typeof value!="string"||value.length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is required and must be a non-empty string`}):hasLoneSurrogate(value)?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} contains an unpaired surrogate and cannot be encoded`}):null,boundsError=(field,value,max)=>{let unusable=segmentError(field,value);if(unusable!==null)return unusable;let length=[...value].length;return length>max?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is ${length} characters; the server accepts at most ${max}`}):null},firstError=(...checks)=>checks.find(c=>c!==null)??null;return{createRequest:body=>{let invalid5=firstError(boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",body.pet_ref,PET_REF_MAX));return invalid5?Promise.resolve(err(invalid5)):send("records.createRequest",post(`${BASE}/requests`,body),"request")},initiateUpload:(requestId2,body)=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.initiateUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/initiate`,body),"request")},completeUpload:(requestId2,body)=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.completeUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/complete`,body),"request")},getRequest:requestId2=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.getRequest",get(`${BASE}/requests/${encodeURIComponent(requestId2)}`),"request")},listRequests:async()=>{let res=await send("records.listRequests",get(`${BASE}/requests`),"request");if(!res.ok)return res;let value=res.value;return{ok:true,value:Array.isArray(value)?value:value.items??[]}},getRecord:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.getRecord",get(`${BASE}/pets/${encodeURIComponent(petRef)}/record`),"content")},getConsent:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.getConsent",get(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")},putConsent:(petRef,body)=>{let invalid5=firstError(boundsError("consent_version",body.consent_version,CONSENT_VERSION_MAX),boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",petRef,PET_REF_MAX));return invalid5?Promise.resolve(err(invalid5)):send("records.putConsent",put(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`,body),"consent")},getFeatures:()=>send("records.getFeatures",get(`${BASE}/features`),"request"),deleteConsent:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.deleteConsent",del(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")}}}function withReason(error,reason){let tagged={...error,recordsReason:reason};for(let key of["wireMessage","raw"]){let descriptor=Object.getOwnPropertyDescriptor(error,key);descriptor!==void 0&&Object.defineProperty(tagged,key,descriptor)}/* @__PURE__ */
108
- return Object.freeze(tagged)}var PET_NOT_REGISTERED="pet_not_registered";function recordsErrorReasonFor(error){return error.httpStatus!==404?null:error.reasonCode===PET_NOT_REGISTERED?"pet_not_found":"entitlement"}function tagReason(error,mode,kind){let notFound=recordsErrorReasonFor(error);return notFound!==null?withReason(error,notFound):error.code!=="accessDenied"?error:withReason(error,mode==="anonymous"?"session_required":kind==="content"?"consent_required":"entitlement")}function get(path){return{method:"GET",path:path}}function post(path,body){return{method:"POST",path:path,body:body}}function put(path,body){return{method:"PUT",path:path,body:body}}function del(path){return{method:"DELETE",path:path}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var epochs=/* @__PURE__ */new Map,listeners=/* @__PURE__ */new Set;function notifyRecordsConsentWithdrawn(petRef){epochs.set(petRef,(epochs.get(petRef)??0)+1);for(let listener of[...listeners])listener()}function recordsConsentEpochOf(petRef){return epochs.get(petRef)??0}function subscribe(onStoreChange){return listeners.add(onStoreChange),()=>{listeners.delete(onStoreChange)}}function useRecordsConsentEpoch(petRef){let snapshot=useCallback(()=>recordsConsentEpochOf(petRef),[petRef]);return useSyncExternalStore(subscribe,snapshot,snapshot)}var INITIAL={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[],uploadContentTypes:RECORDS_FEATURES_PDF_ONLY.uploadContentTypes},POLL_INTERVAL_MS=4e3,MAX_POLLS=30;function useEverfurRecords(opts){let{petRef:petRef}=opts,ownTransport=useRef(opts.uploadTransport);ownTransport.current=opts.uploadTransport;let hasOwnTransport=opts.uploadTransport!==void 0,{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),scope=useMemo(()=>({}),[runtime,userRef,petRef,scopeEpoch,opts.controller]),activeScope=useRef(scope),[binding,setBinding]=useState({scope:scope,controller:opts.controller??null}),controller=opts.controller??(binding.scope===scope?binding.controller:null),[snapshot,setSnapshot]=useState({scope:scope,value:INITIAL}),snap=snapshot.scope===scope?snapshot.value:INITIAL,setSnap=useCallback(update=>{setSnapshot(current=>current.scope===scope?{scope:scope,value:update(current.value)}:current)},[scope]),generation=useRef(0);useEffect(()=>(activeScope.current=scope,setSnapshot({scope:scope,value:INITIAL}),()=>{activeScope.current=null,generation.current+=1}),[scope]),useEffect(()=>{if(opts.controller)return;let{services:services}=runtime.registry,telemetry={record:(event,props)=>services.telemetry.track(event,props)},acquired=runtime.registry.acquire("records",`${userRef??""}|${petRef}${hasOwnTransport?"|own-upload":""}`,()=>createRecordsController({repository:createHttpRecordsRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),uploads:hasOwnTransport?{postMultipart:(policy,file,o)=>(ownTransport.current??services.uploadTransport).postMultipart(policy,file,o)}:services.uploadTransport,telemetry:telemetry}),()=>{});return setBinding({scope:scope,controller:acquired}),()=>{runtime.registry.release(acquired)}},[runtime,userRef,petRef,opts.controller,scopeEpoch,scope,hasOwnTransport]);let patch=useCallback(partial=>{setSnap(current=>({...current,...partial}))},[setSnap]),load=useCallback(async()=>{if(!controller||activeScope.current!==scope)return;let gen=generation.current+=1;pollsRef.current=0,rearmPolls(),patch({loading:true,error:null,denialReason:null,withheld:false});let[consentRes,listRes]=await Promise.all([controller.getConsent(petRef),controller.listRequests()]);if(gen!==generation.current)return;let consent=consentRes.ok?consentRes.value:null,requests=listRes.ok?listRes.value.filter(request=>request.petRef===petRef):[],listError=listRes.ok?null:listRes.error;if(consent&&consent.granted){let recordRes=await controller.getRecord(petRef);if(gen!==generation.current)return;if(recordRes.ok){patch({consent:consent,requests:requests,record:recordRes.value,withheld:recordRes.value.withheld,error:recordRes.value.withheld?withheldSentinel():listError,denialReason:null,loading:false});return}patch({consent:consent,requests:requests,record:null,error:recordRes.error,denialReason:recordsDenialReasonOf(recordRes.error),withheld:false,loading:false});return}patch({consent:consent,requests:requests,record:null,error:consentRes.ok?listError:consentRes.error,denialReason:consent?"consent_required":consentDenial(consentRes),withheld:false,loading:false})},[controller,petRef,patch,scope]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let readUploadFeatures=opts.readUploadFeatures===true;useEffect(()=>{if(!readUploadFeatures||!controller?.readFeatures)return;let live=true;return controller.readFeatures().then(features=>{live&&activeScope.current===scope&&patch({uploadContentTypes:features.uploadContentTypes})}),()=>{live=false}},[controller,readUploadFeatures,patch,scope]);let activeRequest=useMemo(()=>newestRequest(snap.requests),[snap.requests]),activeId=activeRequest?.id??null,activeStatus=activeRequest?.status??null,pollsRef=useRef(0),polledIdRef=useRef(null),[pollEpoch,rearmPolls]=useReducer(n=>n+1,0);useEffect(()=>{if(!controller||activeId===null||activeStatus===null||isTerminalStatus(activeStatus)||activeStatus==="in_review")return;polledIdRef.current!==String(activeId)&&(polledIdRef.current=String(activeId),pollsRef.current=0);let cancelled=false,tick=async()=>{if(cancelled||pollsRef.current>=MAX_POLLS)return;pollsRef.current+=1;let res=await controller.getRequest(activeId);if(!cancelled){if(res.ok&&res.value.petRef===petRef){if(setSnap(current=>({...current,requests:replaceRequest(current.requests,res.value)})),isTerminalStatus(res.value.status)){res.value.status==="published"&&load();return}if(res.value.status==="in_review")return}handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS)}},handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS);return()=>{cancelled=true,clearTimeout(handle)}},[controller,activeId,activeStatus,load,pollEpoch,petRef,setSnap]);let createRequest=useCallback(async idempotencyKey=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.createUploadRequest({petRef:petRef,idempotencyKey:idempotencyKey});return activeScope.current===scope&&res.ok&&res.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,res.value)})),res},[controller,petRef,scope,setSnap]),patchItem=useCallback((key,update)=>{setSnap(c=>({...c,uploadQueue:c.uploadQueue.map(item=>item.key===key?update(item):item)}))},[setSnap]),uploadDocuments=useCallback(async(requestId2,files)=>{let batch=Date.now().toString(36),queue=files.map((file,index)=>{let skipReason=skipReasonFor(file,snap.uploadContentTypes);return{key:`${batch}-${index}`,name:file.name??null,status:skipReason===null?"queued":"skipped",progress:0,skipReason:skipReason,error:null}}),settled=[...queue];if(!controller||activeScope.current!==scope)/* @__PURE__ */return Object.freeze(settled);setSnap(c=>({...c,uploadQueue:queue,isUploading:true,uploadProgress:0}));for(let[index,file]of files.entries()){let item=queue[index];if(item.status==="skipped")continue;if(activeScope.current!==scope)break;patchItem(item.key,current=>({...current,status:"uploading",progress:0})),patch({uploadProgress:0});let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{if(activeScope.current!==scope)return;let bounded=Math.min(1,Math.max(0,fraction));patchItem(item.key,current=>({...current,progress:Math.max(current.progress,bounded)})),patch({uploadProgress:bounded})}});if(activeScope.current!==scope)break;let next=res.ok?{...item,status:"done",progress:1}:{...item,status:"failed",error:res.error};if(settled[index]=next,patchItem(item.key,()=>next),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}}return activeScope.current===scope&&patch({isUploading:false,uploadProgress:null}),/* @__PURE__ */Object.freeze(settled)},[controller,patch,patchItem,petRef,scope,setSnap,snap.uploadContentTypes]),uploadDocument=useCallback(async(requestId2,file)=>{if(!controller||activeScope.current!==scope)return notReady();let key=`${Date.now().toString(36)}-0`;setSnap(c=>({...c,isUploading:true,uploadProgress:0,uploadQueue:[{key:key,name:file.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{activeScope.current===scope&&(patch({uploadProgress:fraction}),patchItem(key,current=>({...current,progress:Math.max(current.progress,Math.min(1,fraction))})))}});if(activeScope.current!==scope)return res;if(patch({isUploading:false,uploadProgress:null}),patchItem(key,current=>res.ok?{...current,status:"done",progress:1}:{...current,status:"failed",error:res.error}),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}return res},[controller,patch,patchItem,petRef,scope,setSnap]),grantConsent=useCallback(async(consentVersion,idempotencyKey)=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.grantConsent({petRef:petRef,consentVersion:consentVersion,idempotencyKey:idempotencyKey});return res.ok&&activeScope.current===scope&&load(),res},[controller,petRef,load,scope]),revokeConsent=useCallback(async()=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.revokeConsent(petRef);return res.ok&&notifyRecordsConsentWithdrawn(petRef),res.ok&&activeScope.current===scope&&(generation.current+=1,patch({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:res.value})),res},[controller,petRef,patch,scope]),refresh=useCallback(()=>load(),[load]),status=selectStatus(snap,controller!==null);return useMemo(()=>({status:status,record:snap.record,requests:snap.requests,activeRequest:activeRequest,consent:snap.consent,error:snap.error,denialReason:snap.denialReason,withheld:snap.withheld,isUploading:snap.isUploading,uploadProgress:snap.uploadProgress,uploadQueue:snap.uploadQueue,uploadContentTypes:snap.uploadContentTypes,createRequest:createRequest,uploadDocument:uploadDocument,uploadDocuments:uploadDocuments,grantConsent:grantConsent,revokeConsent:revokeConsent,refresh:refresh}),[status,snap,activeRequest,createRequest,uploadDocument,uploadDocuments,grantConsent,revokeConsent,refresh])}function skipReasonFor(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"too_large":null}function classifyPick(files,types){let uploadable=[],skipped=[];for(let file of files){let reason=skipReasonFor(file,types);reason===null?uploadable.push(file):skipped.push({name:file.name??null,reason:reason})}return{uploadable:uploadable,skipped:skipped}}function selectStatus(snap,hasController){return snap.loading||!hasController?"loading":snap.withheld||snap.denialReason!==null||snap.error!==null?"error":snap.record!==null&&!snap.record.isEmpty||snap.requests.length>0?"populated":"empty"}function newestRequest(requests){if(requests.length===0)return null;let newest=requests[0];for(let r of requests)r.updatedAt>newest.updatedAt&&(newest=r);return newest}function replaceRequest(requests,next){let filtered=requests.filter(r=>r.id!==next.id);return[next,...filtered]}function consentDenial(res){return res.ok?"consent_required":recordsDenialReasonOf(res.error)??"consent_required"}function withheldSentinel(){return makeEverfurError("internalError",{retryable:false})}function notReady(){return{ok:false,error:makeEverfurError("internalError",{retryable:true})}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var RECORDS_DASHBOARD=/* @__PURE__ */Object.freeze({name:"dashboard"});function initialRecordsNav(initial=RECORDS_DASHBOARD){/* @__PURE__ */
107
+ return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms2,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms2);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals2(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms2,timers,signal){return ms2<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms2),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var BASE="/widget/v1/records";function createHttpRecordsRepository(deps){let{auth:auth}=deps,mode=auth.mode,funnel=deps.funnel??createRequestFunnel({auth:auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=async(call,req,kind)=>{let res=await funnel.send(call,req);return res.ok?res:err(tagReason(plainNotFound(res.error),mode,kind))},segmentError=(field,value)=>typeof value!="string"||value.length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is required and must be a non-empty string`}):hasLoneSurrogate(value)?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} contains an unpaired surrogate and cannot be encoded`}):null,boundsError=(field,value,max)=>{let unusable=segmentError(field,value);if(unusable!==null)return unusable;let length=[...value].length;return length>max?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is ${length} characters; the server accepts at most ${max}`}):null},firstError=(...checks)=>checks.find(c=>c!==null)??null;return{createRequest:body=>{let invalid5=firstError(boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",body.pet_ref,PET_REF_MAX));return invalid5?Promise.resolve(err(invalid5)):send("records.createRequest",post(`${BASE}/requests`,body),"request")},initiateUpload:(requestId2,body)=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.initiateUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/initiate`,body),"request")},completeUpload:(requestId2,body)=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.completeUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/complete`,body),"request")},getRequest:requestId2=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.getRequest",get(`${BASE}/requests/${encodeURIComponent(requestId2)}`),"request")},listRequests:async()=>{let res=await send("records.listRequests",get(`${BASE}/requests`),"request");if(!res.ok)return res;let value=res.value;return{ok:true,value:Array.isArray(value)?value:value.items??[]}},getRecord:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.getRecord",get(`${BASE}/pets/${encodeURIComponent(petRef)}/record`),"content")},getConsent:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.getConsent",get(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")},putConsent:(petRef,body)=>{let invalid5=firstError(boundsError("consent_version",body.consent_version,CONSENT_VERSION_MAX),boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",petRef,PET_REF_MAX));return invalid5?Promise.resolve(err(invalid5)):send("records.putConsent",put(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`,body),"consent")},getFeatures:()=>send("records.getFeatures",get(`${BASE}/features`),"request"),deleteConsent:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.deleteConsent",del(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")}}}function withReason(error,reason){let tagged={...error,recordsReason:reason};for(let key of["wireMessage","raw"]){let descriptor=Object.getOwnPropertyDescriptor(error,key);descriptor!==void 0&&Object.defineProperty(tagged,key,descriptor)}/* @__PURE__ */
108
+ return Object.freeze(tagged)}var PET_NOT_REGISTERED="pet_not_registered";function recordsErrorReasonFor(error){return error.httpStatus!==404?null:error.reasonCode===PET_NOT_REGISTERED?"pet_not_found":"entitlement"}function tagReason(error,mode,kind){let notFound=recordsErrorReasonFor(error);return notFound!==null?withReason(error,notFound):error.code!=="accessDenied"?error:withReason(error,mode==="anonymous"?"session_required":kind==="content"?"consent_required":"entitlement")}function get(path){return{method:"GET",path:path}}function post(path,body){return{method:"POST",path:path,body:body}}function put(path,body){return{method:"PUT",path:path,body:body}}function del(path){return{method:"DELETE",path:path}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var epochs=/* @__PURE__ */new Map,listeners=/* @__PURE__ */new Set;function notifyRecordsConsentWithdrawn(petRef){epochs.set(petRef,(epochs.get(petRef)??0)+1);for(let listener of[...listeners])listener()}function recordsConsentEpochOf(petRef){return epochs.get(petRef)??0}function subscribe(onStoreChange){return listeners.add(onStoreChange),()=>{listeners.delete(onStoreChange)}}function useRecordsConsentEpoch(petRef){let snapshot=useCallback(()=>recordsConsentEpochOf(petRef),[petRef]);return useSyncExternalStore(subscribe,snapshot,snapshot)}var INITIAL={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[],uploadContentTypes:RECORDS_FEATURES_PDF_ONLY.uploadContentTypes},POLL_INTERVAL_MS=4e3,MAX_POLLS=30;function useEverfurRecords(opts){let{petRef:petRef}=opts,ownTransport=useRef(opts.uploadTransport);ownTransport.current=opts.uploadTransport;let hasOwnTransport=opts.uploadTransport!==void 0,{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),scope=useMemo(()=>({}),[runtime,userRef,petRef,scopeEpoch,opts.controller]),activeScope=useRef(scope),[binding,setBinding]=useState({scope:scope,controller:opts.controller??null}),controller=opts.controller??(binding.scope===scope?binding.controller:null),[snapshot,setSnapshot]=useState({scope:scope,value:INITIAL}),snap=snapshot.scope===scope?snapshot.value:INITIAL,setSnap=useCallback(update=>{setSnapshot(current=>current.scope===scope?{scope:scope,value:update(current.value)}:current)},[scope]),generation=useRef(0);useEffect(()=>(activeScope.current=scope,setSnapshot({scope:scope,value:INITIAL}),()=>{activeScope.current=null,generation.current+=1}),[scope]),useEffect(()=>{if(opts.controller)return;let{services:services}=runtime.registry,telemetry={record:(event,props)=>services.telemetry.track(event,props)},acquired=runtime.registry.acquire("records",`${userRef??""}|${petRef}${hasOwnTransport?"|own-upload":""}`,()=>createRecordsController({repository:createHttpRecordsRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),uploads:hasOwnTransport?{postMultipart:(policy,file,o)=>(ownTransport.current??services.uploadTransport).postMultipart(policy,file,o)}:services.uploadTransport,telemetry:telemetry}),()=>{});return setBinding({scope:scope,controller:acquired}),()=>{runtime.registry.release(acquired)}},[runtime,userRef,petRef,opts.controller,scopeEpoch,scope,hasOwnTransport]);let patch=useCallback(partial=>{setSnap(current=>({...current,...partial}))},[setSnap]),load=useCallback(async()=>{if(!controller||activeScope.current!==scope)return;let gen=generation.current+=1;pollsRef.current=0,rearmPolls(),patch({loading:true,error:null,denialReason:null,withheld:false});let[consentRes,listRes]=await Promise.all([controller.getConsent(petRef),controller.listRequests()]);if(gen!==generation.current)return;let consent=consentRes.ok?consentRes.value:null,requests=listRes.ok?listRes.value.filter(request=>request.petRef===petRef):[],listError=listRes.ok?null:listRes.error;if(consent&&consent.granted){let recordRes=await controller.getRecord(petRef);if(gen!==generation.current)return;if(recordRes.ok){patch({consent:consent,requests:requests,record:recordRes.value,withheld:recordRes.value.withheld,error:recordRes.value.withheld?withheldSentinel():listError,denialReason:null,loading:false});return}patch({consent:consent,requests:requests,record:null,error:recordRes.error,denialReason:recordsDenialReasonOf(recordRes.error),withheld:false,loading:false});return}patch({consent:consent,requests:requests,record:null,error:consentRes.ok?listError:consentRes.error,denialReason:consent?"consent_required":consentDenial(consentRes),withheld:false,loading:false})},[controller,petRef,patch,scope]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let readUploadFeatures=opts.readUploadFeatures===true;useEffect(()=>{if(!readUploadFeatures||!controller?.readFeatures)return;let live=true;return controller.readFeatures().then(features=>{live&&activeScope.current===scope&&patch({uploadContentTypes:features.uploadContentTypes})}),()=>{live=false}},[controller,readUploadFeatures,patch,scope]);let activeRequest=useMemo(()=>newestRequest(snap.requests),[snap.requests]),activeId=activeRequest?.id??null,activeStatus=activeRequest?.status??null,pollsRef=useRef(0),polledIdRef=useRef(null),[pollEpoch,rearmPolls]=useReducer(n2=>n2+1,0);useEffect(()=>{if(!controller||activeId===null||activeStatus===null||isTerminalStatus(activeStatus)||activeStatus==="in_review")return;polledIdRef.current!==String(activeId)&&(polledIdRef.current=String(activeId),pollsRef.current=0);let cancelled=false,tick=async()=>{if(cancelled||pollsRef.current>=MAX_POLLS)return;pollsRef.current+=1;let res=await controller.getRequest(activeId);if(!cancelled){if(res.ok&&res.value.petRef===petRef){if(setSnap(current=>({...current,requests:replaceRequest(current.requests,res.value)})),isTerminalStatus(res.value.status)){res.value.status==="published"&&load();return}if(res.value.status==="in_review")return}handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS)}},handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS);return()=>{cancelled=true,clearTimeout(handle)}},[controller,activeId,activeStatus,load,pollEpoch,petRef,setSnap]);let createRequest=useCallback(async idempotencyKey=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.createUploadRequest({petRef:petRef,idempotencyKey:idempotencyKey});return activeScope.current===scope&&res.ok&&res.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,res.value)})),res},[controller,petRef,scope,setSnap]),patchItem=useCallback((key,update)=>{setSnap(c=>({...c,uploadQueue:c.uploadQueue.map(item=>item.key===key?update(item):item)}))},[setSnap]),uploadDocuments=useCallback(async(requestId2,files)=>{let batch=Date.now().toString(36),queue=files.map((file,index)=>{let skipReason=skipReasonFor(file,snap.uploadContentTypes);return{key:`${batch}-${index}`,name:file.name??null,status:skipReason===null?"queued":"skipped",progress:0,skipReason:skipReason,error:null}}),settled=[...queue];if(!controller||activeScope.current!==scope)/* @__PURE__ */return Object.freeze(settled);setSnap(c=>({...c,uploadQueue:queue,isUploading:true,uploadProgress:0}));for(let[index,file]of files.entries()){let item=queue[index];if(item.status==="skipped")continue;if(activeScope.current!==scope)break;patchItem(item.key,current=>({...current,status:"uploading",progress:0})),patch({uploadProgress:0});let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{if(activeScope.current!==scope)return;let bounded=Math.min(1,Math.max(0,fraction));patchItem(item.key,current=>({...current,progress:Math.max(current.progress,bounded)})),patch({uploadProgress:bounded})}});if(activeScope.current!==scope)break;let next=res.ok?{...item,status:"done",progress:1}:{...item,status:"failed",error:res.error};if(settled[index]=next,patchItem(item.key,()=>next),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}}return activeScope.current===scope&&patch({isUploading:false,uploadProgress:null}),/* @__PURE__ */Object.freeze(settled)},[controller,patch,patchItem,petRef,scope,setSnap,snap.uploadContentTypes]),uploadDocument=useCallback(async(requestId2,file)=>{if(!controller||activeScope.current!==scope)return notReady();let key=`${Date.now().toString(36)}-0`;setSnap(c=>({...c,isUploading:true,uploadProgress:0,uploadQueue:[{key:key,name:file.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{activeScope.current===scope&&(patch({uploadProgress:fraction}),patchItem(key,current=>({...current,progress:Math.max(current.progress,Math.min(1,fraction))})))}});if(activeScope.current!==scope)return res;if(patch({isUploading:false,uploadProgress:null}),patchItem(key,current=>res.ok?{...current,status:"done",progress:1}:{...current,status:"failed",error:res.error}),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}return res},[controller,patch,patchItem,petRef,scope,setSnap]),grantConsent=useCallback(async(consentVersion,idempotencyKey)=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.grantConsent({petRef:petRef,consentVersion:consentVersion,idempotencyKey:idempotencyKey});return res.ok&&activeScope.current===scope&&load(),res},[controller,petRef,load,scope]),revokeConsent=useCallback(async()=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.revokeConsent(petRef);return res.ok&&notifyRecordsConsentWithdrawn(petRef),res.ok&&activeScope.current===scope&&(generation.current+=1,patch({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:res.value})),res},[controller,petRef,patch,scope]),refresh=useCallback(()=>load(),[load]),status=selectStatus(snap,controller!==null);return useMemo(()=>({status:status,record:snap.record,requests:snap.requests,activeRequest:activeRequest,consent:snap.consent,error:snap.error,denialReason:snap.denialReason,withheld:snap.withheld,isUploading:snap.isUploading,uploadProgress:snap.uploadProgress,uploadQueue:snap.uploadQueue,uploadContentTypes:snap.uploadContentTypes,createRequest:createRequest,uploadDocument:uploadDocument,uploadDocuments:uploadDocuments,grantConsent:grantConsent,revokeConsent:revokeConsent,refresh:refresh}),[status,snap,activeRequest,createRequest,uploadDocument,uploadDocuments,grantConsent,revokeConsent,refresh])}function skipReasonFor(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"too_large":null}function classifyPick(files,types){let uploadable=[],skipped=[];for(let file of files){let reason=skipReasonFor(file,types);reason===null?uploadable.push(file):skipped.push({name:file.name??null,reason:reason})}return{uploadable:uploadable,skipped:skipped}}function selectStatus(snap,hasController){return snap.loading||!hasController?"loading":snap.withheld||snap.denialReason!==null||snap.error!==null?"error":snap.record!==null&&!snap.record.isEmpty||snap.requests.length>0?"populated":"empty"}function newestRequest(requests){if(requests.length===0)return null;let newest=requests[0];for(let r of requests)r.updatedAt>newest.updatedAt&&(newest=r);return newest}function replaceRequest(requests,next){let filtered=requests.filter(r=>r.id!==next.id);return[next,...filtered]}function consentDenial(res){return res.ok?"consent_required":recordsDenialReasonOf(res.error)??"consent_required"}function withheldSentinel(){return makeEverfurError("internalError",{retryable:false})}function notReady(){return{ok:false,error:makeEverfurError("internalError",{retryable:true})}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var RECORDS_DASHBOARD=/* @__PURE__ */Object.freeze({name:"dashboard"});function initialRecordsNav(initial=RECORDS_DASHBOARD){/* @__PURE__ */
109
109
  return Object.freeze({stack:/* @__PURE__ */Object.freeze([initial])})}function currentRecordsScreen(state){return state.stack[state.stack.length-1]??RECORDS_DASHBOARD}function pushRecordsNav(state,screen){/* @__PURE__ */
110
110
  return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack,screen])})}function replaceRecordsNav(state,screen){/* @__PURE__ */
111
- return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack.slice(0,-1),screen])})}function resetRecordsNav(screen){return initialRecordsNav(screen)}function popRecordsNav(state){return state.stack.length<=1?{state:state,handled:false}:{state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,-1))}),handled:true}}function transitionRecordsNav(state,to){return to.name==="dashboard"?resetRecordsNav(to):currentRecordsScreen(state).name==="upload"&&to.name==="request"?replaceRecordsNav(state,to):pushRecordsNav(state,to)}function recordsNavReducer(state,action){switch(action.type){case"push":return pushRecordsNav(state,action.screen);case"pop":return popRecordsNav(state).state;case"replace":return replaceRecordsNav(state,action.screen);case"reset":return resetRecordsNav(action.screen);case"navigate":return transitionRecordsNav(state,action.screen);default:return state}}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function recordCardSlot(slots){return slots.recordCard??slots.card}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var CLINIC_REQUEST_COPY=/* @__PURE__ */Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you’re authorizing",send:"Send request",sending:"Sending…",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:name=>`Typed signature: ${name}`,missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"});var CLINIC_PICKER_COPY=/* @__PURE__ */Object.freeze({title:CLINIC_REQUEST_COPY.title,titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Request ${name}’s records`:CLINIC_REQUEST_COPY.title},leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:petName=>[{title:"We send a secure request",body:"With your permission, straight to the clinic’s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${petName}’s records.`}],placeholder:CLINIC_REQUEST_COPY.placeholder,searchA11y:CLINIC_REQUEST_COPY.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload…",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:CLINIC_REQUEST_COPY.recentlyUsed,noMatch:query=>`No clinics match “${query}”. You can still request records using the option above.`,loadingMore:"Loading more…",loadMoreFailed:"Couldn’t load more. Tap to retry.",selectA11y:summary=>`Request records from ${summary}`,resultsCount:count=>count===1?"Showing 1 clinic":`Showing ${String(count)} clinics`,fallback:/* @__PURE__ */Object.freeze({title:"Can’t find your clinic?",subtitle:"Add it by email and we’ll request your records.",nameLabel:"Clinic name",namePlaceholder:"Your clinic’s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue"})});function clinicEmailStatusBadge(status){switch(status){case"verified":return{label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case"unverified":return{label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return{label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}var KM_PER_MILE=1.609344;function milesLabel(km){return km===null||!Number.isFinite(km)?null:(km/KM_PER_MILE).toFixed(1)}function formatClinicDistanceLabel(km){let miles=milesLabel(km);return miles===null?"":`${miles} mi`}function formatClinicDistanceForA11y(km){let miles=milesLabel(km);return miles===null?"":`${miles} ${miles==="1.0"?"mile":"miles"} away`}var CLINIC_SEARCH_DEBOUNCE_MS=300,CLINIC_SEARCH_MIN_CHARS=2;var RECORDS_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"}),RECORDS_FOOTNOTE="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";var NAMELESS_PET="your pet";function petNameOr(petName){let trimmed=petName?.trim()??"";return trimmed.length>0?trimmed:NAMELESS_PET}var DASHBOARD_COPY=/* @__PURE__ */Object.freeze({title:"Health records",titleWeb:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Health records"},titleNative:petName=>{let name=petName?.trim()??"";return name.length>0?name:"Health records"},openTimeline:"Open timeline",loading:"Loading health records",lead:petName=>`${petNameOr(petName)}’s lab trends`,retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:disclaimer=>`Important: ${disclaimer}`}),MARKER_SUMMARY_COPY=/* @__PURE__ */Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet’s biomarkers",ask:"Ask about these markers",a11y:(total,inRange,outOfRange2,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange2} out of range${unknown>0?`, ${unknown} without a range`:""}.`}),MARKER_CAROUSEL_COPY=/* @__PURE__ */Object.freeze({counter:(index,total)=>`${index+1} of ${total}`,a11y:(name,index,total)=>name!==null?`${name}, marker ${index+1} of ${total}. Swipe left or right to see more markers.`:`Marker ${index+1} of ${total}`}),MARKER_CARD_COPY=/* @__PURE__ */Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we’ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:name=>{let trimmed=name?.trim()??"";return trimmed.length>0?`Ask about ${trimmed}`:"Ask about this marker"},status:label=>`Status: ${label}`,latestA11y:(reading,status,date2)=>`Latest reading ${reading}, ${status}, collected ${date2}`,readingsA11y:name=>`${name} readings, oldest to newest`}),PROVENANCE_COPY=/* @__PURE__ */Object.freeze({title:"Where this comes from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn’t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading"}),IN_PROGRESS_COPY=/* @__PURE__ */Object.freeze({title:petName=>`${petNameOr(petName)}’s records are on the way`,anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:petName=>`We’re requesting ${petNameOr(petName)}’s records from your vet. This usually takes a few days; we’ll show lab trends here as soon as they arrive.`,a11y:petName=>`Records request in progress for ${petNameOr(petName)}.`,ask:"Ask about this request"}),REQUEST_PROMPT_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Add ${petNameOr(petName)}’s records`,firstRecordTitle:petName=>`Add ${petNameOr(petName)}’s first record`,body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",uploadDocument:"Upload a document"});function isRecordsInProgress(request){return!isTerminalStatus(request.status)}function pickPetRecordsRequest(requests,petRef){if(petRef===null)return null;let forPet=requests.filter(r=>r.petRef===petRef);if(forPet.length===0)return null;let published=forPet.find(r=>r.status==="published");return published!==void 0?published:forPet.filter(isRecordsInProgress).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0]??null}function deriveRecordsDashboardState(args){if(args.hasMarkers)return"published";let request=pickPetRecordsRequest(args.requests,args.petRef);return request===null?"none":request.status==="published"||isRecordsInProgress(request)?"in_progress":"none"}function selectDashboardLoading(input){return input.recordLoading?true:input.hasFullRecord?false:input.markersLoading||!input.hasMarkers&&input.requestsLoading}function selectDashboardView(input){return selectDashboardLoading(input)?"loading":input.hasFullRecord?"record":input.markersError||input.recordError&&!input.hasMarkers?"error":input.dashboardState==="in_progress"&&input.drivingRequest!==null?"in_progress":input.dashboardState==="none"?"none":"labs_only"}function recordsEmptyVariantForError(error){return error?.httpStatus===429?"rate_limited":error?.httpStatus===502?"service_unavailable":"error"}var REQUEST_SCREEN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:(clinicName,petName)=>`${clinicName} has the request. We’ll let you know when ${petName}’s file arrives.`,sentLeadNative:petName=>`We’ll let you know when ${petName}’s file arrives.`,whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there’s no reply by day 14.",waitingBanner:elapsedDays=>`It’s been ${elapsedDays} ${elapsedDays===1?"day":"days"}. Some clinics take a little longer; we’ve been following up automatically and are still on it. If there’s no reply by day 14, we’ll let you know.`,viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",convert:"Upload my own records instead",converting:"Switching…",convertHint:"We’ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we’ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting…",cancel:"Cancel request",cancelling:"Cancelling…",resend:"Resend email",resending:"Resending…",errors:/* @__PURE__ */Object.freeze({cancel:"We couldn’t cancel this request. Please try again.",retry:"We couldn’t retry this request. Please try again.",email:"We couldn’t update the clinic email. Please try again.",convert:"We couldn’t switch this to an upload. Please try again.",start:"We couldn’t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function fallbackFailureTitle(request){if(request.wireStatus==="clinic_declined")return"The clinic declined to release the records.";if(request.wireStatus==="clinic_responded_no_records")return"The clinic replied but didn’t include your records.";switch(request.failureCode){case"no_response":return"The clinic didn’t reply after several reminders over 14 days.";case"parse_timeout":case"parse_error":return"We received the records but couldn’t read them. Uploading a clean copy usually fixes this.";case"hard_bounce":case"dispatch_failed":return"We couldn’t deliver the email to the clinic.";default:return"This request didn’t go through."}}function failureTitle(request){let reason=request.failureReason?.trim()??"";return reason.length>0?reason:fallbackFailureTitle(request)}var MS_PER_DAY=1440*60*1e3;function requestElapsedDays(request,nowMs){if(!request.createdAt)return 0;let created=Date.parse(request.createdAt);if(Number.isNaN(created))return 0;let diff=nowMs-created;return diff<=0?0:Math.floor(diff/MS_PER_DAY)}var RECORDS_WAITING_LONG_DAYS=7;function requestWaitingTooLong(request,nowMs){return request.wireStatus!=="awaiting_response"?false:requestElapsedDays(request,nowMs)>=RECORDS_WAITING_LONG_DAYS}function isTerminalFailure(request){return request.status==="failed"}function shouldOfferRecovery(request){return isTerminalFailure(request)||request.canUpdateClinicEmail===true||request.canRetrySend===true}function useClinicPicker(controller,location){let[query,setQueryValue]=useState(""),[debouncedQuery,setDebounced]=useState(""),[clinics,setClinics]=useState([]),[cursor,setCursor]=useState(null),[recent,setRecent]=useState([]),[recentLoading,setRecentLoading]=useState(true),[initialLoading,setInitialLoading]=useState(false),[loadingMore,setLoadingMore]=useState(false),[error,setError]=useState(null),[pageError,setPageError]=useState(null),[attempt,setAttempt]=useState(0),generation=useRef(0),live=useRef(true),lat=location?.latitude,lng=location?.longitude,bias=useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),useEffect(()=>{let alive=true;return setRecentLoading(true),controller.recentClinics({limit:5}).then(result=>{alive&&(result.ok&&setRecent(result.value.clinics),setRecentLoading(false))}).catch(()=>{alive&&setRecentLoading(false)}),()=>{alive=false}},[controller]),useEffect(()=>{let trimmed=query.trim();if(trimmed.length<CLINIC_SEARCH_MIN_CHARS){setDebounced("");return}let handle=setTimeout(()=>setDebounced(trimmed),CLINIC_SEARCH_DEBOUNCE_MS);return()=>clearTimeout(handle)},[query]);let isSearchActive=debouncedQuery.length>=CLINIC_SEARCH_MIN_CHARS;useEffect(()=>{let revision=generation.current+=1;if(setClinics([]),setCursor(null),setError(null),setPageError(null),!isSearchActive){setInitialLoading(false);return}setInitialLoading(true),controller.searchClinics({query:debouncedQuery,limit:25,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(result.value.clinics),setCursor(result.value.nextCursor)):setError(result.error),setInitialLoading(false))}).catch(()=>{live.current&&revision===generation.current&&setInitialLoading(false)})},[controller,debouncedQuery,isSearchActive,bias,attempt]);let loadMore=useCallback(()=>{if(!isSearchActive||cursor===null||loadingMore)return;let revision=generation.current;setLoadingMore(true),setPageError(null),controller.searchClinics({query:debouncedQuery,limit:25,cursor:cursor,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(current=>[...current,...result.value.clinics]),setCursor(result.value.nextCursor)):setPageError(result.error),setLoadingMore(false))}).catch(()=>{live.current&&revision===generation.current&&setLoadingMore(false)})},[controller,cursor,debouncedQuery,isSearchActive,loadingMore,bias]),setQuery=useCallback(value=>setQueryValue(value),[]),retry=useCallback(()=>setAttempt(n=>n+1),[]);return useMemo(()=>({query:query,debouncedQuery:debouncedQuery,isSearchActive:isSearchActive,clinics:clinics,recent:recent,recentLoading:recentLoading,initialLoading:initialLoading,loadingMore:loadingMore,hasNextPage:cursor!==null,error:error,pageError:pageError,setQuery:setQuery,loadMore:loadMore,retry:retry}),[query,debouncedQuery,isSearchActive,clinics,recent,recentLoading,initialLoading,loadingMore,cursor,error,pageError,setQuery,loadMore,retry])}function clinicDraftFor(clinic,freeText,email2,idempotencyKey){/* @__PURE__ */
111
+ return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack.slice(0,-1),screen])})}function resetRecordsNav(screen){return initialRecordsNav(screen)}function popRecordsNav(state){return state.stack.length<=1?{state:state,handled:false}:{state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,-1))}),handled:true}}function transitionRecordsNav(state,to){return to.name==="dashboard"?resetRecordsNav(to):currentRecordsScreen(state).name==="upload"&&to.name==="request"?replaceRecordsNav(state,to):pushRecordsNav(state,to)}function recordsNavReducer(state,action){switch(action.type){case"push":return pushRecordsNav(state,action.screen);case"pop":return popRecordsNav(state).state;case"replace":return replaceRecordsNav(state,action.screen);case"reset":return resetRecordsNav(action.screen);case"navigate":return transitionRecordsNav(state,action.screen);default:return state}}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function recordCardSlot(slots){return slots.recordCard??slots.card}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var CLINIC_REQUEST_COPY=/* @__PURE__ */Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you’re authorizing",send:"Send request",sending:"Sending…",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:name=>`Typed signature: ${name}`,missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"});var CLINIC_PICKER_COPY=/* @__PURE__ */Object.freeze({title:CLINIC_REQUEST_COPY.title,titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Request ${name}’s records`:CLINIC_REQUEST_COPY.title},leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:petName=>[{title:"We send a secure request",body:"With your permission, straight to the clinic’s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${petName}’s records.`}],placeholder:CLINIC_REQUEST_COPY.placeholder,searchA11y:CLINIC_REQUEST_COPY.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload…",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:CLINIC_REQUEST_COPY.recentlyUsed,noMatch:query=>`No clinics match “${query}”. You can still request records using the option above.`,loadingMore:"Loading more…",loadMoreFailed:"Couldn’t load more. Tap to retry.",selectA11y:summary=>`Request records from ${summary}`,resultsCount:count=>count===1?"Showing 1 clinic":`Showing ${String(count)} clinics`,fallback:/* @__PURE__ */Object.freeze({title:"Can’t find your clinic?",subtitle:"Add it by email and we’ll request your records.",nameLabel:"Clinic name",namePlaceholder:"Your clinic’s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue"})});function clinicEmailStatusBadge(status){switch(status){case"verified":return{label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case"unverified":return{label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return{label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}var KM_PER_MILE=1.609344;function milesLabel(km){return km===null||!Number.isFinite(km)?null:(km/KM_PER_MILE).toFixed(1)}function formatClinicDistanceLabel(km){let miles=milesLabel(km);return miles===null?"":`${miles} mi`}function formatClinicDistanceForA11y(km){let miles=milesLabel(km);return miles===null?"":`${miles} ${miles==="1.0"?"mile":"miles"} away`}var CLINIC_SEARCH_DEBOUNCE_MS=300,CLINIC_SEARCH_MIN_CHARS=2;var RECORDS_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"}),RECORDS_FOOTNOTE="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";var NAMELESS_PET="your pet";function petNameOr(petName){let trimmed=petName?.trim()??"";return trimmed.length>0?trimmed:NAMELESS_PET}var DASHBOARD_COPY=/* @__PURE__ */Object.freeze({title:"Health records",titleWeb:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Health records"},titleNative:petName=>{let name=petName?.trim()??"";return name.length>0?name:"Health records"},openTimeline:"Open timeline",loading:"Loading health records",lead:petName=>`${petNameOr(petName)}’s lab trends`,retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:disclaimer=>`Important: ${disclaimer}`}),MARKER_SUMMARY_COPY=/* @__PURE__ */Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet’s biomarkers",ask:"Ask about these markers",a11y:(total,inRange,outOfRange2,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange2} out of range${unknown>0?`, ${unknown} without a range`:""}.`}),MARKER_CAROUSEL_COPY=/* @__PURE__ */Object.freeze({counter:(index,total)=>`${index+1} of ${total}`,a11y:(name,index,total)=>name!==null?`${name}, marker ${index+1} of ${total}. Swipe left or right to see more markers.`:`Marker ${index+1} of ${total}`}),MARKER_CARD_COPY=/* @__PURE__ */Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we’ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:name=>{let trimmed=name?.trim()??"";return trimmed.length>0?`Ask about ${trimmed}`:"Ask about this marker"},status:label=>`Status: ${label}`,latestA11y:(reading,status,date2)=>`Latest reading ${reading}, ${status}, collected ${date2}`,readingsA11y:name=>`${name} readings, oldest to newest`}),PROVENANCE_COPY=/* @__PURE__ */Object.freeze({title:"Where this comes from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn’t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading"}),IN_PROGRESS_COPY=/* @__PURE__ */Object.freeze({title:petName=>`${petNameOr(petName)}’s records are on the way`,anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:petName=>`We’re requesting ${petNameOr(petName)}’s records from your vet. This usually takes a few days; we’ll show lab trends here as soon as they arrive.`,a11y:petName=>`Records request in progress for ${petNameOr(petName)}.`,ask:"Ask about this request"}),REQUEST_PROMPT_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Add ${petNameOr(petName)}’s records`,firstRecordTitle:petName=>`Add ${petNameOr(petName)}’s first record`,body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",uploadDocument:"Upload a document"});function isRecordsInProgress(request){return!isTerminalStatus(request.status)}function pickPetRecordsRequest(requests,petRef){if(petRef===null)return null;let forPet=requests.filter(r=>r.petRef===petRef);if(forPet.length===0)return null;let published=forPet.find(r=>r.status==="published");return published!==void 0?published:forPet.filter(isRecordsInProgress).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0]??null}function deriveRecordsDashboardState(args){if(args.hasMarkers)return"published";let request=pickPetRecordsRequest(args.requests,args.petRef);return request===null?"none":request.status==="published"||isRecordsInProgress(request)?"in_progress":"none"}function selectDashboardLoading(input){return input.recordLoading?true:input.hasFullRecord?false:input.markersLoading||!input.hasMarkers&&input.requestsLoading}function selectDashboardView(input){return selectDashboardLoading(input)?"loading":input.hasFullRecord?"record":input.markersError||input.recordError&&!input.hasMarkers?"error":input.dashboardState==="in_progress"&&input.drivingRequest!==null?"in_progress":input.dashboardState==="none"?"none":"labs_only"}function recordsEmptyVariantForError(error){return error?.httpStatus===429?"rate_limited":error?.httpStatus===502?"service_unavailable":"error"}var REQUEST_SCREEN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:(clinicName,petName)=>`${clinicName} has the request. We’ll let you know when ${petName}’s file arrives.`,sentLeadNative:petName=>`We’ll let you know when ${petName}’s file arrives.`,whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there’s no reply by day 14.",waitingBanner:elapsedDays=>`It’s been ${elapsedDays} ${elapsedDays===1?"day":"days"}. Some clinics take a little longer; we’ve been following up automatically and are still on it. If there’s no reply by day 14, we’ll let you know.`,viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",convert:"Upload my own records instead",converting:"Switching…",convertHint:"We’ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we’ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting…",cancel:"Cancel request",cancelling:"Cancelling…",resend:"Resend email",resending:"Resending…",errors:/* @__PURE__ */Object.freeze({cancel:"We couldn’t cancel this request. Please try again.",retry:"We couldn’t retry this request. Please try again.",email:"We couldn’t update the clinic email. Please try again.",convert:"We couldn’t switch this to an upload. Please try again.",start:"We couldn’t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function fallbackFailureTitle(request){if(request.wireStatus==="clinic_declined")return"The clinic declined to release the records.";if(request.wireStatus==="clinic_responded_no_records")return"The clinic replied but didn’t include your records.";switch(request.failureCode){case"no_response":return"The clinic didn’t reply after several reminders over 14 days.";case"parse_timeout":case"parse_error":return"We received the records but couldn’t read them. Uploading a clean copy usually fixes this.";case"hard_bounce":case"dispatch_failed":return"We couldn’t deliver the email to the clinic.";default:return"This request didn’t go through."}}function failureTitle(request){let reason=request.failureReason?.trim()??"";return reason.length>0?reason:fallbackFailureTitle(request)}var MS_PER_DAY=1440*60*1e3;function requestElapsedDays(request,nowMs){if(!request.createdAt)return 0;let created=Date.parse(request.createdAt);if(Number.isNaN(created))return 0;let diff=nowMs-created;return diff<=0?0:Math.floor(diff/MS_PER_DAY)}var RECORDS_WAITING_LONG_DAYS=7;function requestWaitingTooLong(request,nowMs){return request.wireStatus!=="awaiting_response"?false:requestElapsedDays(request,nowMs)>=RECORDS_WAITING_LONG_DAYS}function isTerminalFailure(request){return request.status==="failed"}function shouldOfferRecovery(request){return isTerminalFailure(request)||request.canUpdateClinicEmail===true||request.canRetrySend===true}function useClinicPicker(controller,location){let[query,setQueryValue]=useState(""),[debouncedQuery,setDebounced]=useState(""),[clinics,setClinics]=useState([]),[cursor,setCursor]=useState(null),[recent,setRecent]=useState([]),[recentLoading,setRecentLoading]=useState(true),[initialLoading,setInitialLoading]=useState(false),[loadingMore,setLoadingMore]=useState(false),[error,setError]=useState(null),[pageError,setPageError]=useState(null),[attempt,setAttempt]=useState(0),generation=useRef(0),live=useRef(true),lat=location?.latitude,lng=location?.longitude,bias=useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),useEffect(()=>{let alive=true;return setRecentLoading(true),controller.recentClinics({limit:5}).then(result=>{alive&&(result.ok&&setRecent(result.value.clinics),setRecentLoading(false))}).catch(()=>{alive&&setRecentLoading(false)}),()=>{alive=false}},[controller]),useEffect(()=>{let trimmed=query.trim();if(trimmed.length<CLINIC_SEARCH_MIN_CHARS){setDebounced("");return}let handle=setTimeout(()=>setDebounced(trimmed),CLINIC_SEARCH_DEBOUNCE_MS);return()=>clearTimeout(handle)},[query]);let isSearchActive=debouncedQuery.length>=CLINIC_SEARCH_MIN_CHARS;useEffect(()=>{let revision=generation.current+=1;if(setClinics([]),setCursor(null),setError(null),setPageError(null),!isSearchActive){setInitialLoading(false);return}setInitialLoading(true),controller.searchClinics({query:debouncedQuery,limit:25,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(result.value.clinics),setCursor(result.value.nextCursor)):setError(result.error),setInitialLoading(false))}).catch(()=>{live.current&&revision===generation.current&&setInitialLoading(false)})},[controller,debouncedQuery,isSearchActive,bias,attempt]);let loadMore=useCallback(()=>{if(!isSearchActive||cursor===null||loadingMore)return;let revision=generation.current;setLoadingMore(true),setPageError(null),controller.searchClinics({query:debouncedQuery,limit:25,cursor:cursor,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(current=>[...current,...result.value.clinics]),setCursor(result.value.nextCursor)):setPageError(result.error),setLoadingMore(false))}).catch(()=>{live.current&&revision===generation.current&&setLoadingMore(false)})},[controller,cursor,debouncedQuery,isSearchActive,loadingMore,bias]),setQuery=useCallback(value=>setQueryValue(value),[]),retry=useCallback(()=>setAttempt(n2=>n2+1),[]);return useMemo(()=>({query:query,debouncedQuery:debouncedQuery,isSearchActive:isSearchActive,clinics:clinics,recent:recent,recentLoading:recentLoading,initialLoading:initialLoading,loadingMore:loadingMore,hasNextPage:cursor!==null,error:error,pageError:pageError,setQuery:setQuery,loadMore:loadMore,retry:retry}),[query,debouncedQuery,isSearchActive,clinics,recent,recentLoading,initialLoading,loadingMore,cursor,error,pageError,setQuery,loadMore,retry])}function clinicDraftFor(clinic,freeText,email2,idempotencyKey){/* @__PURE__ */
112
112
  return Object.freeze({key:clinic?.id??`free:${freeText??""}`,clinic:clinic,freeText:freeText,email:email2,idempotencyKey:idempotencyKey})}var RECORDS_CLINIC_BATCH_MAX=10,uuid=/* @__PURE__ */z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text=(max,min=1)=>z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),clinicSchema=/* @__PURE__ */z.object({clinicId:/* @__PURE__ */uuid.optional(),clinicFreeText:text(200).refine(value=>value.trim().length>0).optional(),clinicEmail:text(320,3).refine(value=>!hasControl(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())).optional(),signatureId:/* @__PURE__ */uuid.optional(),signaturePngBase64:/* @__PURE__ */z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0)),inputSchema=/* @__PURE__ */z.object({petRef:text(128),ownerName:text(200).refine(value=>value.trim().length>0&&!hasControl(value)),authorizationVersion:text(64),clinics:/* @__PURE__ */z.array(clinicSchema).min(1).max(RECORDS_CLINIC_BATCH_MAX)}).strict(),responseSchema=/* @__PURE__ */z.object({request_group_id:uuid,pet_ref:/* @__PURE__ */z.string(),created_count:/* @__PURE__ */z.number().int().nonnegative(),failed_count:/* @__PURE__ */z.number().int().nonnegative(),results:/* @__PURE__ */z.array(/* @__PURE__ */z.object({idempotency_key:/* @__PURE__ */z.string(),clinic_id:/* @__PURE__ */uuid.nullable().optional(),clinic_free_text:/* @__PURE__ */z.string().nullable().optional(),created:/* @__PURE__ */z.boolean(),request:/* @__PURE__ */z.unknown().optional(),failure_code:/* @__PURE__ */z.string().nullable().optional(),failure_reason:/* @__PURE__ */z.string().nullable().optional()}))});function createRecordsClinicBatchClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async createClinicRequestBatch(input){if(!inputSchema.safeParse(input).success)return err(makeEverfurError("validationFailed",{retryable:false}));let result=await funnel.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,clinics:input.clinics.map(clinic=>({...clinic.clinicId!==void 0?{clinic_id:clinic.clinicId}:{clinic_free_text:clinic.clinicFreeText},...clinic.clinicEmail!==void 0?{clinic_email:clinic.clinicEmail}:{},...clinic.signatureId!==void 0?{signature_id:clinic.signatureId}:{signature_png_base64:clinic.signaturePngBase64},idempotency_key:clinic.idempotencyKey}))}});if(!result.ok)return result;let parsed=responseSchema.safeParse(result.value);if(!parsed.success||parsed.data.pet_ref!==input.petRef)return malformed();let results=[];for(let row of parsed.data.results){let request=row.request===void 0||row.request===null?null:mapRequestView(row.request);if(row.created!==(request!==null))return malformed();results.push(/* @__PURE__ */Object.freeze({idempotencyKey:row.idempotency_key,clinicId:row.clinic_id??null,clinicFreeText:row.clinic_free_text??null,created:row.created,request:request,failureCode:row.failure_code??null,failureReason:row.failure_reason??null}))}return ok(/* @__PURE__ */Object.freeze({requestGroupId:parsed.data.request_group_id,petRef:parsed.data.pet_ref,results:/* @__PURE__ */Object.freeze(results),createdCount:parsed.data.created_count,failedCount:parsed.data.failed_count}))}}}function malformed(){return err(makeEverfurError("internalError",{retryable:false}))}var uuid2=/* @__PURE__ */z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),clinicPageSchema=/* @__PURE__ */z.object({clinics:/* @__PURE__ */z.array(/* @__PURE__ */z.object({clinic_id:uuid2,name:/* @__PURE__ */z.string().min(1),address:/* @__PURE__ */z.string().nullable(),phone:/* @__PURE__ */z.string().nullable(),email_status:/* @__PURE__ */z.string(),distance_km:/* @__PURE__ */z.number().finite().nonnegative().nullable()})),next_cursor:/* @__PURE__ */z.string().nullable().optional()}),copySchema=/* @__PURE__ */z.object({authorization_version:/* @__PURE__ */z.string().min(1),scope_template:/* @__PURE__ */z.string().min(1),authorization_template:/* @__PURE__ */z.string().min(1)}),signaturePolicySchema=/* @__PURE__ */z.object({upload_id:/* @__PURE__ */z.string().min(1),upload_url:/* @__PURE__ */z.string().url().refine(value=>value.startsWith("https://")),upload_fields:/* @__PURE__ */z.record(/* @__PURE__ */z.string())});function createRecordsClinicController(deps){let{repository:repository}=deps,request=async pending=>{let result=await pending;if(!result.ok)return result;let mapped=mapRequestView(result.value);return mapped===null?malformed2():ok(mapped)},page=async pending=>{let result=await pending;if(!result.ok)return result;let parsed=clinicPageSchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({clinics:/* @__PURE__ */Object.freeze(parsed.data.clinics.map(clinic=>/* @__PURE__ */Object.freeze({id:clinic.clinic_id,name:clinic.name,address:clinic.address,phone:clinic.phone,emailStatus:clinic.email_status,distanceKm:clinic.distance_km}))),nextCursor:parsed.data.next_cursor??null})):malformed2()};return{searchClinics:(input={})=>page(repository.searchClinics(input)),recentClinics:(input={})=>page(repository.recentClinics(input)),async getRequestGroup(requestGroupId){let result=await repository.getRequestGroup(requestGroupId);if(!result.ok)return result;let group=mapRequestGroup(result.value);return group===null?malformed2():ok(group)},async getAuthorizationCopy(){let result=await repository.getAuthorizationCopy();if(!result.ok)return result;let parsed=copySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({authorizationVersion:parsed.data.authorization_version,scopeTemplate:parsed.data.scope_template,authorizationTemplate:parsed.data.authorization_template})):malformed2()},async createClinicRequest(input){let result=await request(repository.createClinicRequest(input));return result.ok&&result.value.petRef!==input.petRef?malformed2():result},retryRequest:id=>request(repository.retryRequest(id)),revokeRequest:id=>request(repository.revokeRequest(id)),updateClinicEmail:(id,clinicEmail)=>request(repository.updateClinicEmail(id,clinicEmail)),convertToUpload:id=>request(repository.convertToUpload(id)),async initiateSignatureUpload(fileSize){let result=await repository.initiateSignatureUpload(fileSize);if(!result.ok)return result;let parsed=signaturePolicySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({uploadId:parsed.data.upload_id,uploadUrl:parsed.data.upload_url,uploadFields:/* @__PURE__ */Object.freeze(parsed.data.upload_fields)})):malformed2()},async completeSignatureUpload(uploadId){let result=await repository.completeSignatureUpload(uploadId);if(!result.ok)return result;let parsed=z.object({signature_id:uuid2}).safeParse(result.value);return parsed.success?ok(parsed.data.signature_id):malformed2()}}}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}var BASE2="/widget/v1/records",uuid3=/* @__PURE__ */z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text2=(max,min=1)=>z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl2=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),email=text2(320,3).refine(value=>!hasControl2(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())),requestId=text2(64),recentSchema=/* @__PURE__ */z.object({limit:/* @__PURE__ */z.number().int().min(1).max(25).optional()}).strict(),searchSchema=/* @__PURE__ */z.object({query:text2(200,0).optional(),location:/* @__PURE__ */z.object({latitude:/* @__PURE__ */z.number().finite().min(-90).max(90),longitude:/* @__PURE__ */z.number().finite().min(-180).max(180)}).strict().optional(),limit:/* @__PURE__ */z.number().int().min(1).max(100).optional(),cursor:text2(512,0).optional()}).strict(),createSchema=/* @__PURE__ */z.object({petRef:text2(128),ownerName:text2(200).refine(value=>value.trim().length>0&&!hasControl2(value)),authorizationVersion:text2(64),clinicId:/* @__PURE__ */uuid3.optional(),clinicFreeText:text2(200).refine(value=>value.trim().length>0).optional(),clinicEmail:email.optional(),signatureId:/* @__PURE__ */uuid3.optional(),signaturePngBase64:/* @__PURE__ */z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0));function createHttpRecordsClinicRepository(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=(call,request,deduplicated=false)=>funnel.send(`records.clinic.${call}`,request,request.method==="GET"||deduplicated?void 0:{idempotent:false,maxAttempts:1}),recover=(id,action,body)=>requestId.safeParse(id).success?send(action,{method:"POST",path:`${BASE2}/requests/${encodeURIComponent(id)}/${action}`,...body?{body:body}:{}}):invalid();return{searchClinics(input){return searchSchema.safeParse(input).success?send("search",{method:"GET",path:`${BASE2}/clinics/search`,query:{q:input.query??"",lat:input.location?.latitude,lng:input.location?.longitude,limit:input.limit,cursor:input.cursor}}):invalid()},recentClinics(input){return recentSchema.safeParse(input).success?send("recent",{method:"GET",path:`${BASE2}/clinics/recent`,query:{limit:input.limit}}):invalid()},getRequestGroup(requestGroupId){return requestId.safeParse(requestGroupId).success?send("requestGroup",{method:"GET",path:`${BASE2}/request-groups/${encodeURIComponent(requestGroupId)}`}):invalid()},getAuthorizationCopy:()=>send("authorizationCopy",{method:"GET",path:`${BASE2}/authorization-copy`}),createClinicRequest(input){return createSchema.safeParse(input).success?send("create",{method:"POST",path:`${BASE2}/clinic-requests`,body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,idempotency_key:input.idempotencyKey,...input.clinicId!==void 0?{clinic_id:input.clinicId}:{clinic_free_text:input.clinicFreeText},...input.clinicEmail!==void 0?{clinic_email:input.clinicEmail}:{},...input.signatureId!==void 0?{signature_id:input.signatureId}:{signature_png_base64:input.signaturePngBase64}}},true):invalid()},retryRequest:id=>recover(id,"retry"),revokeRequest:id=>recover(id,"revoke"),convertToUpload:id=>recover(id,"convert-to-upload"),updateClinicEmail(id,clinicEmail){return email.safeParse(clinicEmail).success?recover(id,"clinic-email",{clinic_email:clinicEmail}):invalid()},initiateSignatureUpload(fileSize){return!Number.isInteger(fileSize)||fileSize<=0||fileSize>2*1024*1024?invalid():send("signatureInitiate",{method:"POST",path:`${BASE2}/signatures/initiate`,body:{content_type:"image/png",file_size:fileSize}})},completeSignatureUpload(uploadId){return/^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(uploadId)?send("signatureComplete",{method:"POST",path:`${BASE2}/signatures/complete`,body:{upload_id:uploadId}}):invalid()}}}function invalid(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsClinic(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),controller=useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicController({repository:createHttpRecordsClinicRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})})},[runtime,userRef,scopeEpoch]),active=useRef(controller);return useEffect(()=>(active.current=controller,()=>{active.current=null}),[controller]),useMemo(()=>{let run=async operation=>{if(userRef===null||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation();return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{searchClinics:input=>run(()=>controller.searchClinics(input)),recentClinics:input=>run(()=>controller.recentClinics(input)),getRequestGroup:id=>run(()=>controller.getRequestGroup(id)),getAuthorizationCopy:()=>run(()=>controller.getAuthorizationCopy()),createClinicRequest:input=>run(()=>controller.createClinicRequest(input)),retryRequest:id=>run(()=>controller.retryRequest(id)),revokeRequest:id=>run(()=>controller.revokeRequest(id)),updateClinicEmail:(id,email2)=>run(()=>controller.updateClinicEmail(id,email2)),convertToUpload:id=>run(()=>controller.convertToUpload(id)),initiateSignatureUpload:size=>run(()=>controller.initiateSignatureUpload(size)),completeSignatureUpload:id=>run(()=>controller.completeSignatureUpload(id))}},[controller,userRef])}function useEverfurRecordsClinicBatch(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicBatchClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch]),active=useRef(client);return useEffect(()=>(active.current=client,()=>{active.current=null}),[client]),useMemo(()=>({async createClinicRequestBatch(input){if(userRef===null||active.current!==client)return err(makeEverfurError("accessDenied"));let result=await client.createClinicRequestBatch(input);return active.current===client?result:err(makeEverfurError("accessDenied"))}}),[client,userRef])}var HostRenderBoundary=class extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:createElement(RenderHost,{render:render})})}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
113
113
  return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
114
114
  return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base2={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base2.disabled=d.disabled),/* @__PURE__ */Object.freeze(base2)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
115
115
  return jsx(View,{style:[styles.offstate,style],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${capability}`,children:/* @__PURE__ */jsx(View,{style:styles.skeletonBar})})}function OffState({decision:decision,style:style}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
116
- return jsx(View,{style:[styles.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsx(Text,{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth:StyleSheet.hairlineWidth,borderColor:color.brandBorder},offstateText:{...face(theme,"regular"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.normal),color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}})}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar2={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
116
+ return jsx(View,{style:[styles.offstate,style],accessible:true,accessibilityRole:"text",accessibilityLabel:message,children:message.length>0?/* @__PURE__ */jsx(Text,{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return StyleSheet.create({offstate:{minHeight:MIN_OFFSTATE_HEIGHT,justifyContent:"center",paddingHorizontal:space.lg,paddingVertical:space.md,backgroundColor:color.surfaceCream,borderRadius:radius.md,borderWidth:StyleSheet.hairlineWidth,borderColor:color.brandBorder},offstateText:{...face(theme,"regular"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.normal),color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}})}var HIDDEN={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke(size,strokeWidth){return strokeWidth??Math.max(1.5,Math.round(size/11*10)/10)}function MenuGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),bar3={width:size*.82,height:w,borderRadius:w,backgroundColor:color};/* @__PURE__ */
117
117
  return jsxs(View,{style:[box(size),{gap:size*.22}],...HIDDEN,children:[
118
- /* @__PURE__ */jsx(View,{style:bar2}),
119
- /* @__PURE__ */jsx(View,{style:bar2}),
120
- /* @__PURE__ */jsx(View,{style:bar2})]})}function CheckGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
118
+ /* @__PURE__ */jsx(View,{style:bar3}),
119
+ /* @__PURE__ */jsx(View,{style:bar3}),
120
+ /* @__PURE__ */jsx(View,{style:bar3})]})}function CheckGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth);/* @__PURE__ */
121
121
  return jsx(View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsx(View,{style:{width:size*.36,height:size*.66,marginTop:-size*.14,borderBottomWidth:w,borderRightWidth:w,borderColor:color,transform:[{rotate:"45deg"}]}})})}var CHEVRON_POSE={down:{rotate:"45deg",marginTop:-.4,marginLeft:0},up:{rotate:"225deg",marginTop:.4,marginLeft:0},right:{rotate:"-45deg",marginTop:0,marginLeft:-.4}};function ChevronGlyph({size:size,color:color,strokeWidth:strokeWidth,direction:direction}){let w=stroke(size,strokeWidth),side=size*.46,pose=CHEVRON_POSE[direction];/* @__PURE__ */
122
122
  return jsx(View,{style:box(size),...HIDDEN,children:/* @__PURE__ */jsx(View,{style:{width:side,height:side,borderRightWidth:w,borderBottomWidth:w,borderColor:color,marginTop:side*pose.marginTop,marginLeft:side*pose.marginLeft,transform:[{rotate:pose.rotate}]}})})}function UploadGlyph({size:size,color:color,strokeWidth:strokeWidth}){let w=stroke(size,strokeWidth),head=size*.34;/* @__PURE__ */
123
123
  return jsxs(View,{style:box(size),...HIDDEN,children:[
@@ -151,10 +151,10 @@ return jsxs(View,{style:box2(size),...HIDDEN2,children:[
151
151
  /* @__PURE__ */jsx(View,{style:{position:"absolute",top:c-w/2,left:c-w/2,width:size*.22,height:w,borderRadius:w,backgroundColor:color}})]})}function ToolGlyph({size:size,color:color}){let w=stroke2(size),ring=size*.42;/* @__PURE__ */
152
152
  return jsxs(View,{style:box2(size),...HIDDEN2,children:[
153
153
  /* @__PURE__ */jsx(View,{style:bar(color,w*1.2,size*.62,{top:size*.62,left:size*.38},-45)}),
154
- /* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.06,right:size*.06,width:ring,height:ring,borderRadius:ring,borderWidth:w,borderColor:color,borderTopColor:"transparent",transform:[{rotate:"45deg"}]}})]})}function WifiOffGlyph({size:size,color:color}){let w=stroke2(size),arc=(diameter,top)=>({position:"absolute",top:size*top,left:(size-diameter)/2,width:diameter,height:diameter,borderRadius:diameter,borderWidth:w,borderColor:"transparent",borderTopColor:color});/* @__PURE__ */
154
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.06,right:size*.06,width:ring,height:ring,borderRadius:ring,borderWidth:w,borderColor:color,borderTopColor:"transparent",transform:[{rotate:"45deg"}]}})]})}function WifiOffGlyph({size:size,color:color}){let w=stroke2(size),arc2=(diameter,top)=>({position:"absolute",top:size*top,left:(size-diameter)/2,width:diameter,height:diameter,borderRadius:diameter,borderWidth:w,borderColor:"transparent",borderTopColor:color});/* @__PURE__ */
155
155
  return jsxs(View,{style:box2(size),...HIDDEN2,children:[
156
- /* @__PURE__ */jsx(View,{style:arc(size*.96,.12)}),
157
- /* @__PURE__ */jsx(View,{style:arc(size*.56,.38)}),
156
+ /* @__PURE__ */jsx(View,{style:arc2(size*.96,.12)}),
157
+ /* @__PURE__ */jsx(View,{style:arc2(size*.56,.38)}),
158
158
  /* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.78,left:size/2-w,width:w*2,height:w*2,borderRadius:w,backgroundColor:color}}),
159
159
  /* @__PURE__ */jsx(View,{style:bar(color,w,size*1.1,{top:size/2,left:size/2},45)})]})}function RefreshGlyph({size:size,color:color}){let w=stroke2(size),ring=size*.8,head=size*.26;/* @__PURE__ */
160
160
  return jsxs(View,{style:box2(size),...HIDDEN2,children:[
@@ -170,12 +170,12 @@ return jsx(WifiOffGlyph,{size:size,color:color});default:return null}}function R
170
170
  return jsxs(View,{style:styles.container,accessibilityRole:"summary",testID:testID,children:[
171
171
  /* @__PURE__ */jsx(View,{style:styles.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"records-empty-glyph",children:/* @__PURE__ */jsx(RecordsEmptyGlyph,{variant:variant,size:GLYPH_SIZE,color:theme.color.brandInk})}),
172
172
  /* @__PURE__ */jsx(Text,{style:styles.title,children:copy.title}),
173
- /* @__PURE__ */jsx(Text,{style:styles.body,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsx(Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsx(Text,{style:styles.actionLabel,children:label})}):null]})}function useStyles(){let theme=useEverfurTheme();return useMemo(()=>makeStyles3(theme),[theme])}var GLYPH_SIZE=22,GLYPH_BOX=48;function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return StyleSheet.create({container:{paddingVertical:space.xxl,paddingHorizontal:space.xl,alignItems:"center",gap:space.sm+space.xs/2},glyph:{width:GLYPH_BOX,height:GLYPH_BOX,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug)-1,color:color.brandInk,textAlign:"center"},body:{...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.normal),color:color.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:space.sm,minHeight:space.xxl+space.sm,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,backgroundColor:color.brand,alignItems:"center",justifyContent:"center",...slotBox(slots.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug)-1,...slotText(slots.primaryButton)}})}var RECORDS_SANDBOX_COPY=/* @__PURE__ */Object.freeze({note:"Test account: clinics are never contacted. Use records test mode to move a request forward.",clinicNotContacted:"Clinic not contacted",notEmailed:email2=>`This is a test account, so no email went to ${email2}.`,newClinicDirectSendNote:"This is a test account, so this clinic will not be emailed."});var NO_SUBSCRIPTION=()=>()=>{};function isSandboxSnapshot(snapshot){return snapshot?.livemode===false}function useEntitlementSource(){try{return useEverfurContext().runtime.entitlements??null}catch{return null}}function useRecordsSandboxTenant(){let source=useEntitlementSource(),subscribe2=useCallback(listener=>source===null?NO_SUBSCRIPTION():source.subscribe(listener),[source]),read=useCallback(()=>source===null?false:isSandboxSnapshot(source.getSnapshot()),[source]);return useSyncExternalStore(subscribe2,read,read)}function useBrandImage(uri){let[failed,setFailed]=useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsx(View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsx(Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var normalize=text4=>text4.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text4=normalize(disclaimer);return text4.length===0||text4===FOOTNOTE}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n){return n.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds){let worst=ink=>grounds.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds,pole,target){let first=grounds[0];if(first===void 0)return pole;let reads=candidate=>grounds.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same2=(a,b)=>parseColor(a)===parseColor(b);return{success:!same2(c.success,compiled.success),warning:!same2(c.warningStrong,compiled.warningStrong)||!same2(c.cautionAccent,compiled.cautionAccent),info:!(same2(c.info,c.brandInk)&&same2(c.badgeBgInfo,c.brandSoft)&&same2(c.infoEdge,c.structureEdge))}}var SLOT_MIN_CONTRAST=4.5;function brandedSuccessInk(theme){if(!brandedStatus(theme).success)return null;let grounds=[theme.color.surface];return pushToContrast(theme.color.success,grounds,poleForGrounds(grounds),SLOT_MIN_CONTRAST)}var BUTTON_HEIGHT=52,SHEET_SCRIM="rgba(0,0,0,0.4)";function useScreenStyles(){let theme=useEverfurTheme();return useMemo(()=>makeScreenStyles(theme),[theme])}function DisclaimerBand({disclaimer:disclaimer,style:style}){let styles=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxs(View,{style:[styles.band,style],accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(disclaimer),testID:"records-disclaimer-band",children:[
173
+ /* @__PURE__ */jsx(Text,{style:styles.body,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsx(Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsx(Text,{style:styles.actionLabel,children:label})}):null]})}function useStyles(){let theme=useEverfurTheme();return useMemo(()=>makeStyles3(theme),[theme])}var GLYPH_SIZE=22,GLYPH_BOX=48;function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return StyleSheet.create({container:{paddingVertical:space.xxl,paddingHorizontal:space.xl,alignItems:"center",gap:space.sm+space.xs/2},glyph:{width:GLYPH_BOX,height:GLYPH_BOX,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug)-1,color:color.brandInk,textAlign:"center"},body:{...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.normal),color:color.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:space.sm,minHeight:space.xxl+space.sm,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,backgroundColor:color.brand,alignItems:"center",justifyContent:"center",...slotBox(slots.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug)-1,...slotText(slots.primaryButton)}})}var RECORDS_SANDBOX_COPY=/* @__PURE__ */Object.freeze({note:"Test account: clinics are never contacted. Use records test mode to move a request forward.",clinicNotContacted:"Clinic not contacted",notEmailed:email2=>`This is a test account, so no email went to ${email2}.`,newClinicDirectSendNote:"This is a test account, so this clinic will not be emailed."});var NO_SUBSCRIPTION=()=>()=>{};function isSandboxSnapshot(snapshot){return snapshot?.livemode===false}function useEntitlementSource(){try{return useEverfurContext().runtime.entitlements??null}catch{return null}}function useRecordsSandboxTenant(){let source=useEntitlementSource(),subscribe2=useCallback(listener=>source===null?NO_SUBSCRIPTION():source.subscribe(listener),[source]),read=useCallback(()=>source===null?false:isSandboxSnapshot(source.getSnapshot()),[source]);return useSyncExternalStore(subscribe2,read,read)}function useBrandImage(uri){let[failed,setFailed]=useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsx(View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsx(Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var normalize=text4=>text4.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text4=normalize(disclaimer);return text4.length===0||text4===FOOTNOTE}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n2){if(!Number.isFinite(n2))return null;let int=Math.trunc(n2)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n2){return Number.isFinite(n2)?Math.min(255,Math.max(0,Math.round(n2))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n2){return n2.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds){let worst=ink=>grounds.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds,pole,target){let first=grounds[0];if(first===void 0)return pole;let reads=candidate=>grounds.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same2=(a,b)=>parseColor(a)===parseColor(b);return{success:!same2(c.success,compiled.success),warning:!same2(c.warningStrong,compiled.warningStrong)||!same2(c.cautionAccent,compiled.cautionAccent),info:!(same2(c.info,c.brandInk)&&same2(c.badgeBgInfo,c.brandSoft)&&same2(c.infoEdge,c.structureEdge))}}var SLOT_MIN_CONTRAST=4.5;function brandedSuccessInk(theme){if(!brandedStatus(theme).success)return null;let grounds=[theme.color.surface];return pushToContrast(theme.color.success,grounds,poleForGrounds(grounds),SLOT_MIN_CONTRAST)}var BUTTON_HEIGHT=52,SHEET_SCRIM="rgba(0,0,0,0.4)";function useScreenStyles(){let theme=useEverfurTheme();return useMemo(()=>makeScreenStyles(theme),[theme])}function DisclaimerBand({disclaimer:disclaimer,style:style}){let styles=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxs(View,{style:[styles.band,style],accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(disclaimer),testID:"records-disclaimer-band",children:[
174
174
  /* @__PURE__ */jsx(View,{style:styles.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(Text,{style:styles.infoGlyphText,children:"i"})}),
175
175
  /* @__PURE__ */jsx(Text,{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,onPress:onPress,kind:kind="primary",disabled:disabled=false,busy:busy=false,accessibilityLabel:accessibilityLabel,accessibilityHint:accessibilityHint,testID:testID,style:style}){let styles=useScreenStyles(),theme=useEverfurTheme(),still=theme.motion.reducedMotion,box3=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink,text4=kind==="primary"?styles.pillPrimaryLabel:kind==="danger"?styles.pillDangerLabel:kind==="ask"?styles.pillAskLabel:kind==="link"?styles.pillLinkLabel:styles.pillOutlineLabel;/* @__PURE__ */
176
176
  return jsxs(Pressable,{onPress:onPress,disabled:disabled||busy,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label,accessibilityHint:accessibilityHint,accessibilityState:{disabled:disabled||busy,busy:busy},style:({pressed:pressed})=>[styles.pill,box3,disabled?styles.pillDisabled:null,pressed&&!still?styles.pressed:null,style],testID:testID,children:[busy?/* @__PURE__ */jsx(ActivityIndicator,{size:"small",color:kind==="primary"?theme.color.onPrimary:theme.color.brandInk}):null,
177
- /* @__PURE__ */jsx(Text,{style:text4,children:label})]})}function Chip({label:label,tone:tone="neutral",testID:testID}){let styles=useScreenStyles(),{bg:bg,fg:fg}=styles.chipTones[tone],sentence=label.length>CHIP_WORD_MAX;/* @__PURE__ */
178
- return jsx(View,{style:[styles.chip,sentence?styles.chipSentence:null,bg],testID:testID,children:/* @__PURE__ */jsx(Text,{style:[styles.chipText,sentence?styles.chipSentenceText:null,fg],children:label})})}var CHIP_WORD_MAX=24;function SectionHeader({title:title,count:count}){let styles=useScreenStyles();/* @__PURE__ */
177
+ /* @__PURE__ */jsx(Text,{style:text4,children:label})]})}function Chip({label:label,tone:tone="neutral",testID:testID}){let styles=useScreenStyles(),{bg:bg,fg:fg}=styles.chipTones[tone],sentence2=label.length>CHIP_WORD_MAX;/* @__PURE__ */
178
+ return jsx(View,{style:[styles.chip,sentence2?styles.chipSentence:null,bg],testID:testID,children:/* @__PURE__ */jsx(Text,{style:[styles.chipText,sentence2?styles.chipSentenceText:null,fg],children:label})})}var CHIP_WORD_MAX=24;function SectionHeader({title:title,count:count}){let styles=useScreenStyles();/* @__PURE__ */
179
179
  return jsxs(View,{style:styles.sectionHeader,children:[
180
180
  /* @__PURE__ */jsx(Text,{style:styles.sectionTitle,accessibilityRole:"header",children:title}),count!==void 0?/* @__PURE__ */jsx(Text,{style:styles.sectionCount,children:count}):null]})}function Chevron({direction:direction="right"}){let styles=useScreenStyles(),rotate=direction==="right"?"45deg":direction==="down"?"135deg":"-45deg";/* @__PURE__ */
181
181
  return jsx(View,{style:[styles.chevron,{transform:[{rotate:rotate}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=StyleSheet.hairlineWidth,touch=space.xxl+space.md,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),recordCard=recordCardSlot(slots),cardText=slotText(recordCard),bannerText=slotText(slots.banner),bannerInk=slots.banner?.textColor,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,tone=(bg,fg)=>({bg:{backgroundColor:bg,borderColor:"transparent"},fg:{color:fg}}),edge=(line2,fg)=>({bg:{backgroundColor:color.surface,borderColor:line2},fg:{color:fg}});return{chipTones:{neutral:edge(color.brandBorderStrong,color.text.primary),info:tone(color.brandSoft,color.brandInk),warning:edge(color.cautionAccent,color.text.primary),critical:edge(color.danger,color.danger),positive:edge(color.success,brandedSuccessInk(theme)??color.brandInk)},...StyleSheet.create({root:{flex:1,backgroundColor:color.background},body:{flex:1},content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg},contentTight:{paddingHorizontal:space.sm,paddingBottom:space.xxl,gap:space.lg},inset:{paddingHorizontal:space.sm},section:{gap:space.sm+space.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.xs},sectionTitle:{...text4(size.subtitle,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4},sectionCount:{...text4(size.bodyTight,lineHeight.snug,color.text.muted,"medium")},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.xs,...slotBox(recordCard,hairline)},creamCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md,...slotBox(recordCard,hairline)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.md,paddingVertical:space.md},rowDivider:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:space.xs+space.xs/2},rowTitle:{...text4(size.body,lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text4(size.caption,lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text4(size.body+1,lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text4(size.caption,lineHeight.normal,color.text.muted),...cardText},chip:{minHeight:24,justifyContent:"center",borderRadius:radius.pill,borderWidth:1.5,paddingHorizontal:space.sm+space.xs/2,alignSelf:"flex-start"},chipText:{...text4(size.tiny+1,lineHeight.snug,color.text.primary,"monoBold"),letterSpacing:.7,textTransform:"uppercase"},chipSentence:{borderRadius:radius.md,paddingVertical:space.xs,alignSelf:"stretch"},chipSentenceText:{...text4(size.caption,lineHeight.normal,color.text.primary,"medium"),letterSpacing:0,textTransform:"none"},pill:{minHeight:BUTTON_HEIGHT,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm},pillPrimary:{backgroundColor:color.brand,...slotBox(slots.primaryButton)},pillPrimaryLabel:{...text4(size.body,lineHeight.snug,color.onPrimary,"bold"),...slotText(slots.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...text4(size.body,lineHeight.snug,color.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:color.danger,backgroundColor:color.surface},pillDangerLabel:{...text4(size.bodyTight,lineHeight.snug,color.danger,"bold")},pillAsk:{borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},pillAskLabel:{...text4(size.body,lineHeight.snug,color.text.primary,"bold")},pillLink:{minHeight:touch,backgroundColor:"transparent",paddingHorizontal:space.sm},pillLinkLabel:{...text4(size.body,lineHeight.snug,color.linkInk,"bold")},pillDisabled:{opacity:.5},pressed:{transform:[{scale:RECORDS_MOTION.pressScale}]},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2,...slotBox(slots.banner)},infoNoteText:{flex:1,...text4(size.bodyTight,lineHeight.normal,color.text.primary),...bannerText},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCaution,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2},cautionNoteText:{flex:1,...text4(size.bodyTight,lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},statusText:text4(size.bodyTight,lineHeight.relaxed,color.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCritical,padding:space.md},errorText:{flex:1,...text4(size.bodyTight,lineHeight.normal,errorColor)},band:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,...slotBox(slots.banner)},bandText:{flex:1,...text4(size.caption,lineHeight.normal,color.text.secondary),...bannerText},infoGlyph:{width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,borderWidth:1,borderColor:bannerInk??color.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...text4(size.small,lineHeight.tight,color.text.secondary,"bold"),...bannerText},chevron:{width:space.sm,height:space.sm,borderTopWidth:space.xs/2,borderRightWidth:space.xs/2,borderColor:color.text.muted},lead:{paddingHorizontal:space.sm,...text4(size.body+1,lineHeight.snug,color.text.primary,"bold")},field:{minHeight:touch,paddingHorizontal:space.md,paddingVertical:space.sm,borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...face(theme,"regular"),fontSize:size.body,...slotBox(slots.input,1),...slotText(slots.input)},fieldLabel:{...text4(size.bodyTight,lineHeight.normal,color.text.secondary,"medium")},muted:text4(size.caption,lineHeight.normal,color.text.muted),bodyText:text4(size.body,lineHeight.normal,color.text.primary)})}}var LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,BACK_LABEL="Back";function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let styles=useStyles2(),theme=useEverfurTheme(),logoUrl=theme.meta.logoUrl,row=/* @__PURE__ */jsxs(View,{style:logoUrl===null?styles.row:styles.rowUnderLogo,testID:testID,children:[onBack?/* @__PURE__ */jsx(Pressable,{onPress:onBack,accessibilityRole:"button",accessibilityLabel:BACK_LABEL,hitSlop:12,style:styles.back,testID:testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsx(View,{style:styles.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):/* @__PURE__ */jsx(View,{style:styles.back}),title.trim().length>0?/* @__PURE__ */jsx(Text,{style:variant==="document"?styles.documentTitle:styles.title,accessibilityRole:"header",numberOfLines:1,children:title}):/* @__PURE__ */jsx(View,{style:styles.spacer,accessibilityElementsHidden:true,importantForAccessibility:"no",testID:testID?`${testID}-spacer`:void 0}),
@@ -201,7 +201,7 @@ return jsxs(View,{style:styles.downloadGlyph,accessibilityElementsHidden:true,im
201
201
  /* @__PURE__ */jsx(View,{style:styles.downloadHead}),
202
202
  /* @__PURE__ */jsx(View,{style:styles.downloadTray})]})}function useStyles2(){let theme=useEverfurTheme();return useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type}=theme,header=theme.slots.header,ink=header?.textColor??color.brandInk,rowBase={flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md,gap:space.sm},touch=space.xxl+space.md,chevron=space.md,stroke3=space.xs/2,glyph=space.lg+space.xs+space.xs/2;return StyleSheet.create({row:{...rowBase,...slotBox(header)},rowUnderLogo:rowBase,bar:{...slotBox(header)},logoBar:{alignItems:"center",paddingTop:space.sm,paddingHorizontal:space.lg},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},back:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},chevron:{width:chevron,height:chevron,borderLeftWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginLeft:space.xs},title:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.heading,lineHeight:Math.round(type.size.heading*type.lineHeight.tight)+1,color:ink},spacer:{flex:1},sandboxNote:{marginHorizontal:space.lg,marginBottom:space.md},documentTitle:{flex:1,textAlign:"center",...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),color:color.text.primary,...slotText(header)},right:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2},listGlyph:{width:glyph,height:glyph,justifyContent:"space-evenly"},listBar:{height:stroke3,borderRadius:stroke3,backgroundColor:ink},shareGlyph:{width:glyph-space.xs,height:glyph-space.xs},shareDot:{position:"absolute",width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs,borderWidth:stroke3,borderColor:ink},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:space.xs+space.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:space.xs,top:space.sm,width:space.sm+space.xs/2,height:stroke3,backgroundColor:ink},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:glyph-space.xs,height:glyph-space.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],borderRadius:stroke3},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:stroke3,backgroundColor:ink},downloadGlyph:{width:glyph-space.xs,height:glyph-space.xs,alignItems:"center"},downloadStem:{width:stroke3,height:space.sm+space.xs/2,backgroundColor:ink},downloadHead:{width:space.sm,height:space.sm,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginTop:-space.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:space.xs+space.xs/2,borderLeftWidth:stroke3,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink}})}var MIN_HEIGHT=120,MIN_TARGET=44;function RecordsGateOffState({reason:reason,onExit:onExit,exitLabel:exitLabel,style:style}){let{color:color,space:space,radius:radius,type:type}=useEverfurTheme();/* @__PURE__ */
203
203
  return jsxs(View,{testID:"records-gate-off",style:[{minHeight:MIN_HEIGHT,justifyContent:"center",gap:space.md,padding:space.lg,borderRadius:radius.md,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surfaceCream},style],children:[reason.length>0?/* @__PURE__ */jsx(Text,{style:{fontSize:type.size.bodyTight,color:color.text.muted},children:reason}):null,
204
- /* @__PURE__ */jsx(Pressable,{onPress:onExit,accessibilityRole:"button",accessibilityLabel:exitLabel,testID:"records-gate-off-exit",style:{minHeight:MIN_TARGET,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.brandInk},children:/* @__PURE__ */jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null)return dayLabel(Number(iso[1]),Number(iso[2])-1,Number(iso[3]));let ms=Date.parse(at);if(Number.isNaN(ms))return"-";let date2=new Date(ms);return dayLabel(date2.getUTCFullYear(),date2.getUTCMonth(),date2.getUTCDate())}function dayLabel(year,month,day){let name=MONTHS[month];return name===void 0?"-":`${name} ${day}, ${year}`}function formatRecordsInstant(at){let parts=at?/^([\d-]{10}T[\d:]+)(\.\d+)?(.*)$/.exec(at):null,ms=parts?Date.parse(`${parts[1]}${(parts[2]??"").slice(0,4)}${parts[3]||"Z"}`):Number.NaN;if(Number.isNaN(ms))return formatRecordsDate(at);let date2=new Date(ms);return dayLabel(date2.getFullYear(),date2.getMonth(),date2.getDate())}function formatIdentityValue(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return value;let formatted=formatRecordsDate(value),day=Number(value.slice(8,10));return formatted==="-"||day<1||day>31?value:formatted}function documentsNewestFirst(documents){let at=doc=>{let ms=doc.receivedAt===null?Number.NaN:Date.parse(doc.receivedAt);return Number.isNaN(ms)?Number.NEGATIVE_INFINITY:ms};return Object.values(documents).map((doc,index)=>({doc:doc,index:index,ms:at(doc)})).sort((a,b)=>b.ms===a.ms?a.index-b.index:b.ms>a.ms?1:-1).map(entry=>entry.doc)}var DEPTH_COPY=/* @__PURE__ */Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:date2=>`Measured ${date2}`,uploadedDocument:"Uploaded document",kind:/* @__PURE__ */Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:name=>`Dr. ${name}`,lot:lot=>`Lot ${lot}`,expires:date2=>`Expires ${date2}`});function markerStatusLabel(status){switch(status){case"above":return{label:"Above range",outOfRange:true};case"below":return{label:"Below range",outOfRange:true};case"in_range":return{label:"In range",outOfRange:false};default:return{label:"No range on file",outOfRange:false}}}function trajectoryLabel(trajectory,visitCount){return visitCount<2?null:`${trajectory==="flat"?"Holding steady":`Trending ${trajectory==="down"?"down":trajectory==="up"?"up":"steady"}`} over ${visitCount} visits`}function humanize(key){let spaced=key.replace(/_/g," ").trim();return spaced.length===0?key:spaced.charAt(0).toUpperCase()+spaced.slice(1)}var BODY_SYSTEM_LABEL=/* @__PURE__ */Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function bodySystemLabel(system){return Object.prototype.hasOwnProperty.call(BODY_SYSTEM_LABEL,system)?BODY_SYSTEM_LABEL[system]:humanize(system)}var SOAP_SECTION_LABEL=/* @__PURE__ */Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function soapSectionLabel(section){return Object.prototype.hasOwnProperty.call(SOAP_SECTION_LABEL,section)?SOAP_SECTION_LABEL[section]:humanize(section)}function formatWeightKg(weightKg){return weightKg===null||!Number.isFinite(weightKg)?"-":`${weightKg.toFixed(3).replace(/\.?0+$/,"")} kg`}function formatMarkerReading(value,unit,qualitative){if((value===null||!Number.isFinite(value))&&qualitative)return qualitative;if(value===null||!Number.isFinite(value))return"-";let num5=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num5} ${unit}`:num5}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}var DOCUMENT_CLASS_LABELS=/* @__PURE__ */Object.freeze({lab_report:"Lab report",pims_export:"Practice export",vaccination_certificate:"Vaccination certificate",imaging_report:"Imaging report",discharge_summary:"Discharge summary",referral_letter:"Referral letter",clinician_note:"Clinician note",consent_form:"Consent form",invoice_estimate:"Invoice",prescription:"Prescription",genetic_report:"Genetic report"});function documentTitle(doc){let title=doc.title?.trim()??"";if(title.length>0)return title;let cls=doc.documentClass;return(cls&&Object.prototype.hasOwnProperty.call(DOCUMENT_CLASS_LABELS,cls)?DOCUMENT_CLASS_LABELS[cls]:void 0)??DEPTH_COPY.uploadedDocument}var RECORD_SCREEN_COPY=/* @__PURE__ */Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:count=>`${count} ${count===1?"document":"documents"} from your vet ${count===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,needsAttention:"Needs attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:/* @__PURE__ */Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:count=>`${count} ${count===1?"document":"documents"} on file`,inReviewChip:count=>`${count} in review`,beingVerified:count=>`${count} being verified`,beingVerifiedA11y:count=>`${count} ${count===1?"fact is":"facts are"} being verified`,pendingReview:"Pending review: ",dateRange:(from,to)=>`${formatRecordsDate(from)} to ${formatRecordsDate(to)}`,documents:"Sources on file",uploadedDocument:DEPTH_COPY.uploadedDocument,documentRowA11y:title=>`View what ${title} contributed to this record`,documentMeta:(pageCount,receivedAt)=>{let date2=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date2].filter(part=>part!==null);return parts.length>0?parts.join(" · "):null},identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:date2=>`Last done ${date2}`,overdue:"Overdue",due:date2=>`Due ${date2}`,askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:DEPTH_COPY.labResults,visits:DEPTH_COPY.visits,physicalExams:DEPTH_COPY.physicalExams,visitNotes:DEPTH_COPY.visitNotes,document:/* @__PURE__ */Object.freeze({title:"Health Record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s health record`:"Health Record"},download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:date2=>`Generated ${formatRecordsDate(date2)}`,identity:"Identity",labs:"Blood & Lab Work",ref:band=>`Ref ${band}`,noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),ENTITY_SECTION_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function entityTypeLabel(entityType){return Object.prototype.hasOwnProperty.call(ENTITY_SECTION_TITLE,entityType)?ENTITY_SECTION_TITLE[entityType]:humanize(entityType)}var ENTITY_SECTION_ORDER=/* @__PURE__ */Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function orderEntityTypes(types){let known=ENTITY_SECTION_ORDER.filter(type=>types.includes(type)),rest=types.filter(type=>!ENTITY_SECTION_ORDER.includes(type));return[...known,...rest]}function conflictSeverityMeta(severity){switch(severity){case"identity_risk":return{label:"Identity mismatch",rank:0,tone:"critical"};case"benign":return{label:"Minor difference",rank:2,tone:"neutral"};default:return{label:"Needs review",rank:1,tone:"warning"}}}function dueBadge(dueAt,nowMs){if(!dueAt)return null;let due=Date.parse(dueAt);if(Number.isNaN(due))return null;let overdue=due<nowMs-1440*60*1e3;return{label:overdue?RECORD_SCREEN_COPY.overdue:RECORD_SCREEN_COPY.due(formatRecordsDate(dueAt)),overdue:overdue}}function formatReferenceBand(point){return point===null?null:point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}`:point.refLow!==null?`≥ ${point.refLow}`:point.refHigh!==null?`≤ ${point.refHigh}`:null}var SHARE_COPY=/* @__PURE__ */Object.freeze({openA11y:"Share medical record",openA11yFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share ${name}’s record`:"Share medical record"},title:"Share medical record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Send ${name}’s record`:"Share medical record"},helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it’s for; we include the right pages.",leadWebFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share a snapshot of what ${name}’s vets recorded. Pick who it’s for and we include the right pages.`:"Pick who it’s for; we include the right pages."},audienceLabel:"Who it’s for",audiences:/* @__PURE__ */Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What’s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com…",send:"Send",sending:"Sending…",addEmailFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Add an email to send ${name}’s record.`:"Add an email to send the record."},emailInvalid:"That email doesn’t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn’t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",turnOff:"Turn off",turnOffA11y:context=>`Turn off share link, ${context}`,turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:url=>`View this medical record: ${url}`,consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:/* @__PURE__ */Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:url=>`Couldn’t copy. The link is ${url}`,turnedOff:"Link turned off.",sentTo:email2=>`Sent to ${email2}. The link works for 7 days.`})}),FULL_RECORD_LINES=/* @__PURE__ */Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),DEPTH_SECTIONS=/* @__PURE__ */Object.freeze([["encounters","encounters",DEPTH_COPY.visits],["lab_results","markers",DEPTH_COPY.labResults],["physical_exams","physical_exams",DEPTH_COPY.physicalExams]]);function shareIncludedLines(scope,features){let lines=[];scope.sections.includes("entities")&&(scope.entityTypes===null?lines.push(...FULL_RECORD_LINES):lines.push(...orderEntityTypes(scope.entityTypes).map(entityTypeLabel)));for(let[section,feature,label]of DEPTH_SECTIONS)scope.sections.includes(section)&&features[feature]===true&&lines.push(label);return scope.sections.includes("forward_looking")&&lines.push(RECORD_SCREEN_COPY.upcomingCare),/* @__PURE__ */Object.freeze(lines)}function isShareExpired(expiresAt,nowMs){if(!expiresAt)return false;let ms=Date.parse(expiresAt);return Number.isNaN(ms)?false:ms<=nowMs}function formatShareExpiry(expiresAt,expired){let date2=formatRecordsDate(expiresAt);return date2==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date2}`:`Expires ${date2}`}function buildShareRows(shares,urls,nowMs){let rows=shares.map(share=>{let expired=isShareExpired(share.expiresAt,nowMs),expiryLabel=formatShareExpiry(share.expiresAt,expired),createdDate=formatRecordsDate(share.createdAt),statusLabel=expired?"Expired":"Active",actionContext=expiryLabel.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return{shareId:share.shareId,shareUrl:urls[share.shareId]??null,active:!expired,statusLabel:statusLabel,expiryLabel:expiryLabel,createdLabel:createdDate==="-"?null:`Created ${createdDate}`,a11yLabel:`Share link. ${statusLabel}. ${expiryLabel}.`,actionContext:actionContext}});/* @__PURE__ */
204
+ /* @__PURE__ */jsx(Pressable,{onPress:onExit,accessibilityRole:"button",accessibilityLabel:exitLabel,testID:"records-gate-off-exit",style:{minHeight:MIN_TARGET,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.brandInk},children:/* @__PURE__ */jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null)return dayLabel(Number(iso[1]),Number(iso[2])-1,Number(iso[3]));let ms2=Date.parse(at);if(Number.isNaN(ms2))return"-";let date2=new Date(ms2);return dayLabel(date2.getUTCFullYear(),date2.getUTCMonth(),date2.getUTCDate())}function dayLabel(year,month,day){let name=MONTHS[month];return name===void 0?"-":`${name} ${day}, ${year}`}function formatRecordsInstant(at){let parts=at?/^([\d-]{10}T[\d:]+)(\.\d+)?(.*)$/.exec(at):null,ms2=parts?Date.parse(`${parts[1]}${(parts[2]??"").slice(0,4)}${parts[3]||"Z"}`):Number.NaN;if(Number.isNaN(ms2))return formatRecordsDate(at);let date2=new Date(ms2);return dayLabel(date2.getFullYear(),date2.getMonth(),date2.getDate())}function formatIdentityValue(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return value;let formatted=formatRecordsDate(value),day=Number(value.slice(8,10));return formatted==="-"||day<1||day>31?value:formatted}function documentsNewestFirst(documents){let at=doc=>{let ms2=doc.receivedAt===null?Number.NaN:Date.parse(doc.receivedAt);return Number.isNaN(ms2)?Number.NEGATIVE_INFINITY:ms2};return Object.values(documents).map((doc,index)=>({doc:doc,index:index,ms:at(doc)})).sort((a,b)=>b.ms===a.ms?a.index-b.index:b.ms>a.ms?1:-1).map(entry=>entry.doc)}var DEPTH_COPY=/* @__PURE__ */Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:date2=>`Measured ${date2}`,uploadedDocument:"Uploaded document",kind:/* @__PURE__ */Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:name=>`Dr. ${name}`,lot:lot=>`Lot ${lot}`,expires:date2=>`Expires ${date2}`});function markerStatusLabel(status){switch(status){case"above":return{label:"Above range",outOfRange:true};case"below":return{label:"Below range",outOfRange:true};case"in_range":return{label:"In range",outOfRange:false};default:return{label:"No range on file",outOfRange:false}}}function trajectoryLabel(trajectory,visitCount){return visitCount<2?null:`${trajectory==="flat"?"Holding steady":`Trending ${trajectory==="down"?"down":trajectory==="up"?"up":"steady"}`} over ${visitCount} visits`}function humanize(key){let spaced=key.replace(/_/g," ").trim();return spaced.length===0?key:spaced.charAt(0).toUpperCase()+spaced.slice(1)}var BODY_SYSTEM_LABEL=/* @__PURE__ */Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function bodySystemLabel(system){return Object.prototype.hasOwnProperty.call(BODY_SYSTEM_LABEL,system)?BODY_SYSTEM_LABEL[system]:humanize(system)}var SOAP_SECTION_LABEL=/* @__PURE__ */Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function soapSectionLabel(section){return Object.prototype.hasOwnProperty.call(SOAP_SECTION_LABEL,section)?SOAP_SECTION_LABEL[section]:humanize(section)}function formatWeightKg(weightKg){return weightKg===null||!Number.isFinite(weightKg)?"-":`${weightKg.toFixed(3).replace(/\.?0+$/,"")} kg`}function formatMarkerReading(value,unit,qualitative){if((value===null||!Number.isFinite(value))&&qualitative)return qualitative;if(value===null||!Number.isFinite(value))return"-";let num5=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num5} ${unit}`:num5}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}var DOCUMENT_CLASS_LABELS=/* @__PURE__ */Object.freeze({lab_report:"Lab report",pims_export:"Practice export",vaccination_certificate:"Vaccination certificate",imaging_report:"Imaging report",discharge_summary:"Discharge summary",referral_letter:"Referral letter",clinician_note:"Clinician note",consent_form:"Consent form",invoice_estimate:"Invoice",prescription:"Prescription",genetic_report:"Genetic report"});function documentTitle(doc){let title=doc.title?.trim()??"";if(title.length>0)return title;let cls=doc.documentClass;return(cls&&Object.prototype.hasOwnProperty.call(DOCUMENT_CLASS_LABELS,cls)?DOCUMENT_CLASS_LABELS[cls]:void 0)??DEPTH_COPY.uploadedDocument}var RECORD_SCREEN_COPY=/* @__PURE__ */Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:count=>`${count} ${count===1?"document":"documents"} from your vet ${count===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,needsAttention:"Needs attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:/* @__PURE__ */Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:count=>`${count} ${count===1?"document":"documents"} on file`,inReviewChip:count=>`${count} in review`,beingVerified:count=>`${count} being verified`,beingVerifiedA11y:count=>`${count} ${count===1?"fact is":"facts are"} being verified`,pendingReview:"Pending review: ",dateRange:(from,to)=>`${formatRecordsDate(from)} to ${formatRecordsDate(to)}`,documents:"Sources on file",uploadedDocument:DEPTH_COPY.uploadedDocument,documentRowA11y:title=>`View what ${title} contributed to this record`,documentMeta:(pageCount,receivedAt)=>{let date2=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date2].filter(part=>part!==null);return parts.length>0?parts.join(" · "):null},identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:date2=>`Last done ${date2}`,overdue:"Overdue",due:date2=>`Due ${date2}`,askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:DEPTH_COPY.labResults,visits:DEPTH_COPY.visits,physicalExams:DEPTH_COPY.physicalExams,visitNotes:DEPTH_COPY.visitNotes,document:/* @__PURE__ */Object.freeze({title:"Health Record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s health record`:"Health Record"},download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:date2=>`Generated ${formatRecordsDate(date2)}`,identity:"Identity",labs:"Blood & Lab Work",ref:band=>`Ref ${band}`,noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),ENTITY_SECTION_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function entityTypeLabel(entityType){return Object.prototype.hasOwnProperty.call(ENTITY_SECTION_TITLE,entityType)?ENTITY_SECTION_TITLE[entityType]:humanize(entityType)}var ENTITY_SECTION_ORDER=/* @__PURE__ */Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function orderEntityTypes(types){let known=ENTITY_SECTION_ORDER.filter(type=>types.includes(type)),rest=types.filter(type=>!ENTITY_SECTION_ORDER.includes(type));return[...known,...rest]}function conflictSeverityMeta(severity){switch(severity){case"identity_risk":return{label:"Identity mismatch",rank:0,tone:"critical"};case"benign":return{label:"Minor difference",rank:2,tone:"neutral"};default:return{label:"Needs review",rank:1,tone:"warning"}}}function dueBadge(dueAt,nowMs){if(!dueAt)return null;let due=Date.parse(dueAt);if(Number.isNaN(due))return null;let overdue=due<nowMs-1440*60*1e3;return{label:overdue?RECORD_SCREEN_COPY.overdue:RECORD_SCREEN_COPY.due(formatRecordsDate(dueAt)),overdue:overdue}}function formatReferenceBand(point){return point===null?null:point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}`:point.refLow!==null?`≥ ${point.refLow}`:point.refHigh!==null?`≤ ${point.refHigh}`:null}var SHARE_COPY=/* @__PURE__ */Object.freeze({openA11y:"Share medical record",openA11yFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share ${name}’s record`:"Share medical record"},title:"Share medical record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Send ${name}’s record`:"Share medical record"},helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it’s for; we include the right pages.",leadWebFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share a snapshot of what ${name}’s vets recorded. Pick who it’s for and we include the right pages.`:"Pick who it’s for; we include the right pages."},audienceLabel:"Who it’s for",audiences:/* @__PURE__ */Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What’s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com…",send:"Send",sending:"Sending…",addEmailFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Add an email to send ${name}’s record.`:"Add an email to send the record."},emailInvalid:"That email doesn’t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn’t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",turnOff:"Turn off",turnOffA11y:context=>`Turn off share link, ${context}`,turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:url=>`View this medical record: ${url}`,consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:/* @__PURE__ */Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:url=>`Couldn’t copy. The link is ${url}`,turnedOff:"Link turned off.",sentTo:email2=>`Sent to ${email2}. The link works for 7 days.`})}),FULL_RECORD_LINES=/* @__PURE__ */Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),DEPTH_SECTIONS=/* @__PURE__ */Object.freeze([["encounters","encounters",DEPTH_COPY.visits],["lab_results","markers",DEPTH_COPY.labResults],["physical_exams","physical_exams",DEPTH_COPY.physicalExams]]);function shareIncludedLines(scope,features){let lines=[];scope.sections.includes("entities")&&(scope.entityTypes===null?lines.push(...FULL_RECORD_LINES):lines.push(...orderEntityTypes(scope.entityTypes).map(entityTypeLabel)));for(let[section,feature,label]of DEPTH_SECTIONS)scope.sections.includes(section)&&features[feature]===true&&lines.push(label);return scope.sections.includes("forward_looking")&&lines.push(RECORD_SCREEN_COPY.upcomingCare),/* @__PURE__ */Object.freeze(lines)}function isShareExpired(expiresAt,nowMs){if(!expiresAt)return false;let ms2=Date.parse(expiresAt);return Number.isNaN(ms2)?false:ms2<=nowMs}function formatShareExpiry(expiresAt,expired){let date2=formatRecordsDate(expiresAt);return date2==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date2}`:`Expires ${date2}`}function buildShareRows(shares,urls,nowMs){let rows=shares.map(share=>{let expired=isShareExpired(share.expiresAt,nowMs),expiryLabel=formatShareExpiry(share.expiresAt,expired),createdDate=formatRecordsDate(share.createdAt),statusLabel=expired?"Expired":"Active",actionContext=expiryLabel.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return{shareId:share.shareId,shareUrl:urls[share.shareId]??null,active:!expired,statusLabel:statusLabel,expiryLabel:expiryLabel,createdLabel:createdDate==="-"?null:`Created ${createdDate}`,a11yLabel:`Share link. ${statusLabel}. ${expiryLabel}.`,actionContext:actionContext}});/* @__PURE__ */
205
205
  return Object.freeze([...rows.filter(r=>r.active),...rows.filter(r=>!r.active)])}function shareErrorMessage(error,action){let status=error?.httpStatus;if(isRecordsConsentRequired(error)){if(action==="create"||action==="email")return"Records access for this pet is off, so a new link cannot be created.";if(action==="download")return"Records access for this pet is off, so the PDF cannot be downloaded."}if(status===429)return"You are creating links a little too fast. Wait a moment, then try again.";if(action==="revoke"&&(status===404||status===409||status===410))return"That link was already turned off.";if(status===401||status===403)return"You need to be signed in as this pet's owner to do that.";if(action==="email"&&(status===400||status===422||error?.code==="validationFailed"))return SHARE_COPY.emailInvalid;switch(action){case"create":return"Could not create a share link. Please try again.";case"revoke":return"Could not turn off that link. Please try again.";case"email":return SHARE_COPY.emailFailed;default:return"Could not download the record PDF. Please try again."}}function SkeletonBlock({width:width,height:height,radius:radius,style:style}){let{color:color,radius:radii}=useEverfurTheme();/* @__PURE__ */
206
206
  return jsx(View,{style:[{width:width,height:height,borderRadius:radius??radii.xs,backgroundColor:color.skeleton},style],accessibilityElementsHidden:true,importantForAccessibility:"no"})}var DONUT=180,BADGE_W=70,BADGE_H=22,CAROUSEL_H=300,DISCLAIMER_H=44,RAIL_DOT=24,TIMELINE_BUBBLE=34,TIMELINE_ROWS=6,CLINIC_ROWS=5;function DashboardSkeleton({testID:testID}){let styles=useStyles3(),action=key=>/* @__PURE__ */jsxs(View,{style:styles.actionRow,children:[
207
207
  /* @__PURE__ */jsxs(View,{style:styles.actionLeft,children:[
@@ -282,7 +282,7 @@ return jsxs(View,{style:[styles.root,style],children:[
282
282
  return jsxs(Pressable,{onPress:()=>onSelect(clinic),accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.selectA11y(summary),hitSlop:8,style:styles.item,testID:`records-clinic-${clinic.id}`,children:[
283
283
  /* @__PURE__ */jsxs(View,{style:styles.itemHeader,children:[
284
284
  /* @__PURE__ */jsx(Text,{style:styles.itemName,numberOfLines:1,children:clinic.name}),distance?/* @__PURE__ */jsx(Text,{style:styles.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:distance}):null]}),clinic.address?/* @__PURE__ */jsx(Text,{style:styles.itemAddress,numberOfLines:2,children:clinic.address}):null,clinic.phone?/* @__PURE__ */jsx(Text,{style:styles.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:clinic.phone}):null,
285
- /* @__PURE__ */jsx(View,{style:[styles.badge,badge.tone==="positive"?styles.badgePositive:badge.tone==="caution"?styles.badgeCaution:styles.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(Text,{style:[styles.badgeLabel,badge.tone==="positive"?styles.badgePositiveText:badge.tone==="caution"?styles.badgeCautionText:styles.badgeNeutralText],children:badge.label})})]})}function useLocalStyles(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles(theme),[theme])}function makeLocalStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),card=theme.slots.card,cardText=slotText(card);return StyleSheet.create({lead:{...text4(type.size.body,type.lineHeight.normal,color.text.muted),paddingHorizontal:space.lg,paddingBottom:space.md},howCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.md,marginTop:space.sm,...slotBox(card)},howTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...cardText},howRow:{flexDirection:"row",gap:space.md},howNumber:{...face(theme,"monoBold"),fontSize:type.size.caption,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.brandInk,minWidth:space.xl},howText:{flex:1,gap:space.xs/2},howStepTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},howStepBody:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary),...cardText},searchBar:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.md+space.xs/2,height:space.xxl+space.md,marginHorizontal:space.lg,marginBottom:space.sm,borderRadius:radius.lg+space.xs/2,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.borderHairlineGreen,...slotBox(theme.slots.input,hairline)},searchInput:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.text.primary),paddingVertical:0,...slotText(theme.slots.input)},clearGlyph:text4(type.size.heading,type.lineHeight.tight,color.text.muted),uploadWrap:{paddingHorizontal:space.lg,paddingBottom:space.md,gap:space.sm},list:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.md},sectionLabel:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:radius.lg-space.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:color.brandBorder,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.md,...slotBox(card,1)},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:space.xxl+space.md},fallbackCopy:{flex:1,gap:space.xs/2},fallbackTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},fallbackSubtitle:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},fallbackForm:{gap:space.sm},item:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(card,1)},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},itemName:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),...cardText},itemDistance:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},itemAddress:{...text4(type.size.caption,type.lineHeight.normal,color.text.primary),...cardText},itemPhone:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},badge:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+1,paddingVertical:space.xs},badgePositive:{backgroundColor:color.badgeBgPositive},badgeCaution:{backgroundColor:color.badgeBgCaution},badgeNeutral:{backgroundColor:color.badgeBgNeutral},badgeLabel:{...text4(type.size.micro,type.lineHeight.snug,color.text.muted,"bold")},badgePositiveText:{color:color.success},badgeCautionText:{color:color.cautionAccent},badgeNeutralText:{color:color.text.muted},footer:{gap:space.sm,paddingTop:space.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,minHeight:space.xxl+space.md},footerRetry:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...text4(type.size.bodyTight,type.lineHeight.snug,color.brandInk,"bold")}})}var CLINIC_BATCH_COPY=/* @__PURE__ */Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${RECORDS_CLINIC_BATCH_MAX} clinics`,send:n=>`Send ${n} ${n===1?"request":"requests"}`,sending:"Sending…",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:name=>`Remove ${name}`,emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn’t send any of these requests. See the details below and try again.",partial:(created,total,failed)=>`${created} of ${total} requests sent. ${failed} couldn’t be sent.`,allSent:created=>`${created} ${created===1?"request":"requests"} sent.`,responded:(responded,total)=>`${responded} of ${total} ${total===1?"clinic":"clinics"} responded`});var CLINIC_FORM_SEARCH_LIMIT=25,CLINIC_FORM_RESULTS_STEP=5;function useVisibleClinics(clinics){let[state,setState]=useState({list:clinics,shown:CLINIC_FORM_RESULTS_STEP}),shown=state.list===clinics?state.shown:CLINIC_FORM_RESULTS_STEP,showMore=useCallback(()=>{setState(previous=>({list:clinics,shown:(previous.list===clinics?previous.shown:CLINIC_FORM_RESULTS_STEP)+CLINIC_FORM_RESULTS_STEP}))},[clinics]);return{visible:clinics.slice(0,shown),hasMore:clinics.length>shown,showMore:showMore}}var SignatureUploadLegError=class extends Error{constructor(){super("Signature upload failed"),this.name="SignatureUploadLegError"}};function isSignatureUploadLegFailure(error){return error instanceof SignatureUploadLegError}function renderClinicScope(copy,owner,pet,clinic){let fields={owner_name:owner,pet_name:pet,clinic_name:clinic},unknown=false,text4=copy.scopeTemplate.replace(/\{([^{}]+)\}/g,(_,key)=>Object.prototype.hasOwnProperty.call(fields,key)?fields[key]??"":(unknown=true,""));return unknown||/[{}]/.test(text4)?null:text4}function clinicNeedsEmail(clinic){return clinic===null||clinic.emailStatus!=="verified"&&clinic.emailStatus!=="unverified"}function useClinicRequestForm(props,controller,capture){let[ownerName,setOwner]=useState(props.ownerName),[query,setQueryValue]=useState(""),[clinic,setClinic]=useState(null),[email2,setEmail]=useState(""),[clinics,setClinics]=useState([]),[recent,setRecent]=useState([]),[copy,setCopy]=useState(null),[error,setError]=useState(null),[busy,setBusy]=useState(false),[searching,setSearching]=useState(false),[created,setCreated]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),active=useRef(false),locked=useRef(false),generation=useRef(0),keyFactory=useRef(defaultIdempotencyKeyFactory()),attempt=useRef(null),captureAbort=useRef(null),lifetime=useRef(0);useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,attempt.current=null,captureAbort.current?.abort()}),[controller]),useEffect(()=>{let live=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let invalidate=()=>{attempt.current=null,setError(null)},clinicName=clinic?.name??query.trim(),scope=copy?renderClinicScope(copy,ownerName.trim(),props.petName,clinicName):null,needsEmail=clinicNeedsEmail(clinic),results=useVisibleClinics(clinics),ready=!!(copy&&scope&&ownerName.trim()&&props.petName.trim()&&clinicName&&(!needsEmail||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email2.trim()))&&capture),search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},submit=async()=>{if(locked.current||created||!ready||!copy||!scope||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(!attempt.current){captureAbort.current=new AbortController;let signature=await capture({petRef:props.petRef,petName:props.petName,ownerName:ownerName.trim(),clinicName:clinicName,authorizationVersion:copy.authorizationVersion,scopeText:scope,signal:captureAbort.current.signal});if(!current()||signature===null)return;let target=clinic&&(!needsEmail||clinic.emailStatus==="none")?{clinicId:clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:email2.trim().toLowerCase()}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}if(!current())return;let result=await controller.createClinicRequest(attempt.current);if(!current())return;if(!result.ok){setError(result.error);return}if(result.value.petRef!==props.petRef){setError(makeEverfurError("internalError"));return}setCreated(result.value),attempt.current=null,props.onCreated?.(result.value)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}};return{ownerName:ownerName,query:query,clinic:clinic,email:email2,clinics:clinics,copy:copy,scope:scope,error:error,busy:busy,searching:searching,created:created,ready:ready,needsEmail:needsEmail,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0&&clinic===null?recent:[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(null),setEmail(""),setQueryValue(value))},setEmail(value){locked.current||(invalidate(),setEmail(value))},selectClinic(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(value),setQueryValue(value.name),setEmail(""))},invalidate:invalidate,search:search,submit:submit,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var EMAIL2=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function draftName(draft){return draft.clinic?.name??draft.freeText??""}function draftNeedsEmail(draft){return clinicNeedsEmail(draft.clinic)}function useClinicBatchForm(props,controller,batchClient,capture,registerSignature){let[ownerName,setOwner]=useState(props.ownerName),[query,setQueryValue]=useState(""),[clinics,setClinics]=useState([]),[recent,setRecent]=useState([]),[drafts,setDrafts]=useState([]),[copy,setCopy]=useState(null),[error,setError]=useState(null),[busy,setBusy]=useState(false),[searching,setSearching]=useState(false),[outcome,setOutcome]=useState(null),[group,setGroup]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),active=useRef(false),locked=useRef(false),generation=useRef(0),lifetime=useRef(0),keyFactory=useRef(defaultIdempotencyKeyFactory()),signature=useRef(null),captureAbort=useRef(null);useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,signature.current=null,captureAbort.current?.abort()}),[controller,batchClient]),useEffect(()=>{let live=true;return setCopy(null),signature.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let results=useVisibleClinics(clinics),invalidate=()=>{signature.current=null,setError(null)},names=drafts.map(draftName),pet=petNameOr(props.petName),scopes=copy?names.map(name=>renderClinicScope(copy,ownerName.trim(),pet,name)):[],scopeText=scopes.every(s=>s!==null)?scopes.join(`\n\n`):null,draftsReady=drafts.length>0&&drafts.every(draft=>!draftNeedsEmail(draft)||EMAIL2.test(draft.email.trim())),atCap=drafts.length>=RECORDS_CLINIC_BATCH_MAX,ready=!!(copy&&scopeText&&ownerName.trim()&&draftsReady&&capture)&&outcome===null,search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},add=draft=>{locked.current||atCap||outcome!==null||draft.clinic!==null&&drafts.some(d=>d.clinic?.id===draft.clinic?.id)||(invalidate(),setDrafts(current=>[...current,{...draft,key:keyFactory.current(),idempotencyKey:keyFactory.current()}]),setClinics([]),setQueryValue(""))},submit=async()=>{if(locked.current||outcome!==null||!ready||!copy||!scopeText||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(signature.current===null){captureAbort.current=new AbortController;let captured=await capture({petRef:props.petRef,petName:pet,ownerName:ownerName.trim(),clinicName:names.join(", "),authorizationVersion:copy.authorizationVersion,scopeText:scopeText,signal:captureAbort.current.signal});if(!current()||captured===null)return;if(signature.current=captured,captured.signaturePngBase64!==void 0&&registerSignature!==void 0){let abort=captureAbort.current;try{let registered=await registerSignature(captured.signaturePngBase64,abort.signal);if(!current())return;signature.current={signatureId:registered.signatureId}}catch(registrationError){if(!isSignatureUploadLegFailure(registrationError)||abort.signal.aborted)throw registrationError;if(!current())return}}}let signed=signature.current,items=drafts.map(draft=>({...draft.clinic!==null&&(!draftNeedsEmail(draft)||draft.clinic.emailStatus==="none")?{clinicId:draft.clinic.id}:{clinicFreeText:draftName(draft)},...draftNeedsEmail(draft)?{clinicEmail:draft.email.trim().toLowerCase()}:{},...signed.signatureId!==void 0?{signatureId:signed.signatureId}:{signaturePngBase64:signed.signaturePngBase64},idempotencyKey:draft.idempotencyKey})),result=await batchClient.createClinicRequestBatch({petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,clinics:items});if(!current())return;if(!result.ok){setError(result.error);return}setOutcome(result.value),props.onCreated?.(result.value),loadGroup(result.value.requestGroupId,run)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}},loadGroup=async(requestGroupId,run)=>{try{let result=await controller.getRequestGroup(requestGroupId);if(!active.current||lifetime.current!==run)return;result.ok&&result.value.petRef===props.petRef&&setGroup(result.value)}catch{}},refreshGroup=async()=>{outcome===null||locked.current||await loadGroup(outcome.requestGroupId,lifetime.current)};return{ownerName:ownerName,query:query,clinics:clinics,copy:copy,scopeText:scopeText,error:error,busy:busy,searching:searching,drafts:drafts,outcome:outcome,group:group,ready:ready,atCap:atCap,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0?recent.filter(clinic=>!drafts.some(d=>d.clinic?.id===clinic.id)):[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(generation.current+=1,setSearching(false),setClinics([]),setQueryValue(value))},search:search,addClinic(clinic){add({clinic:clinic,freeText:null,email:""})},addFreeText(){let name=query.trim();name.length!==0&&add({clinic:null,freeText:name,email:""})},setDraftEmail(key,email2){locked.current||(invalidate(),setDrafts(current=>current.map(draft=>draft.key===key?{...draft,email:email2}:draft)))},removeDraft(key){locked.current||outcome!==null||(invalidate(),setDrafts(current=>current.filter(draft=>draft.key!==key)))},submit:submit,refreshGroup:refreshGroup,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number",probeRef=useRef(null),[reading,setReading]=useState(null),frame=useRef(null),retry=useRef(null),mounted=useRef(true),stopRetry=useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return useMemo(()=>{if(!lifts)return{avoidingProps:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsx(View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function trustedSignatureUploadUrl(value){try{let url=new URL(value);if(url.protocol!=="https:"||url.username||url.password||url.port&&url.port!=="443")return!1;let host=url.hostname.toLowerCase();return host==="s3.amazonaws.com"||host.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(host)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(host)||host==="s3-accelerate.amazonaws.com"||host.endsWith(".s3-accelerate.amazonaws.com")||host==="s3-accelerate.dualstack.amazonaws.com"||host.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}var FAILED="Signature upload failed",UPLOAD_TIMEOUT_MS=3e4;function base64ByteLength(base64){let padding=base64.endsWith("==")?2:base64.endsWith("=")?1:0;return Math.floor(base64.length*3/4)-padding}async function registerRnSignature(signaturePngBase64,controller,signal,fetchImpl){let fail=()=>new Error(FAILED),size=base64ByteLength(signaturePngBase64);if(size<=0||signal.aborted)throw fail();let initiated=await controller.initiateSignatureUpload(size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw fail();let form=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))form.append(key,value);form.append("file",{uri:`data:image/png;base64,${signaturePngBase64}`,name:"signature.png",type:"image/png"});let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,UPLOAD_TIMEOUT_MS);try{if(!(await(fetchImpl??fetch)(initiated.value.uploadUrl,{method:"POST",body:form,credentials:"omit",signal:uploadAbort.signal})).ok||signal.aborted)throw fail()}catch{throw signal.aborted?fail():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw fail();return{signatureId:completed.value}}var SIGNATURE_CANVAS=/* @__PURE__ */Object.freeze({width:360,height:120});function blank(width,height){return{width:width,height:height,pixels:new Uint8Array(width*height)}}function stamp(bitmap,cx,cy,radius){for(let dy=-radius;dy<=radius;dy+=1)for(let dx=-radius;dx<=radius;dx+=1){if(dx*dx+dy*dy>radius*radius+radius)continue;let x=cx+dx,y=cy+dy;x<0||y<0||x>=bitmap.width||y>=bitmap.height||(bitmap.pixels[y*bitmap.width+x]=1)}}var MAX_STEPS_PER_STROKE=16384;function padPoint(point,bitmap){let[x,y]=point;if(!Number.isFinite(x)||!Number.isFinite(y))return null;let cx=Math.min(2*bitmap.width,Math.max(-bitmap.width,Math.round(x))),cy=Math.min(2*bitmap.height,Math.max(-bitmap.height,Math.round(y)));return[cx,cy]}function line(bitmap,from,to,radius,budget){let[x0,y0]=from,[x1,y1]=to,dx=Math.abs(x1-x0),dy=-Math.abs(y1-y0),sx=x0<x1?1:-1,sy=y0<y1?1:-1,error=dx+dy,steps=0;for(;steps<budget&&(stamp(bitmap,x0,y0,radius),steps+=1,!(x0===x1&&y0===y1));){let twice=2*error;twice>=dy&&(error+=dy,x0+=sx),twice<=dx&&(error+=dx,y0+=sy)}return steps}function rasterizeStrokes(strokes,penRadius=1){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height);for(let stroke3 of strokes){let points=[];for(let point of stroke3){let clamped=padPoint(point,bitmap);clamped!==null&&points.push(clamped)}if(points.length===0)continue;if(points.length===1){let[x,y]=points[0];stamp(bitmap,x,y,penRadius);continue}let budget=MAX_STEPS_PER_STROKE;for(let i=1;i<points.length&&budget>0;i+=1)budget-=line(bitmap,points[i-1],points[i],penRadius,budget)}return bitmap}var FONT_ORDER="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",FONT_ROWS="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",FONT_DIGITS="0123456789abcdefghijklmnopqrstuv",GLYPH_W=5,GLYPH_H=7,ADVANCE=GLYPH_W+1;function glyphRow(char,row){let index=FONT_ORDER.indexOf(char);return index<0?0:FONT_DIGITS.indexOf(FONT_ROWS.charAt(index*GLYPH_H+row))}function rasterizeTypedName(name){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height),text4=name.trim();if(text4.length===0)return bitmap;let chars=[...text4],scale=4;for(;scale>1&&(chars.length*ADVANCE-1)*scale>bitmap.width-8;)scale-=1;let textWidth=(chars.length*ADVANCE-1)*scale,x0=Math.max(0,Math.floor((bitmap.width-textWidth)/2)),y0=Math.floor((bitmap.height-GLYPH_H*scale)/2);return chars.forEach((char,i)=>{let gx=x0+i*ADVANCE*scale;for(let row=0;row<GLYPH_H;row+=1){let bits=glyphRow(char,row);for(let col=0;col<GLYPH_W;col+=1)if((bits>>GLYPH_W-1-col&1)!==0)for(let sy=0;sy<scale;sy+=1)for(let sx=0;sx<scale;sx+=1){let x=gx+col*scale+sx,y=y0+row*scale+sy;x<bitmap.width&&y<bitmap.height&&(bitmap.pixels[y*bitmap.width+x]=1)}}}),bitmap}var BitWriter=class{constructor(){this.bytes=[];this.acc=0;this.count=0}writeBits(value,count){for(this.acc|=value<<this.count,this.count+=count;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8}writeCode(code,length){let reversed=0;for(let i=0;i<length;i+=1)reversed=reversed<<1|code>>i&1;this.writeBits(reversed,length)}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};function writeLiteral(out,symbol){symbol<144?out.writeCode(48+symbol,8):symbol<256?out.writeCode(400+(symbol-144),9):symbol<280?out.writeCode(symbol-256,7):out.writeCode(192+(symbol-280),8)}var LENGTH_BASE=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],LENGTH_EXTRA=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],DIST_BASE=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],DIST_EXTRA=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function writeMatch(out,length,distance){let li=LENGTH_BASE.length-1;for(;LENGTH_BASE[li]>length;)li-=1;writeLiteral(out,257+li),LENGTH_EXTRA[li]>0&&out.writeBits(length-LENGTH_BASE[li],LENGTH_EXTRA[li]);let di=DIST_BASE.length-1;for(;DIST_BASE[di]>distance;)di-=1;out.writeCode(di,5),DIST_EXTRA[di]>0&&out.writeBits(distance-DIST_BASE[di],DIST_EXTRA[di])}var WINDOW=32768,MIN_MATCH=3,MAX_MATCH=258,HASH_BITS=15,CHAIN_LIMIT=64;function deflate(input){let out=new BitWriter;out.writeBits(1,1),out.writeBits(1,2);let head=new Int32Array(1<<HASH_BITS).fill(-1),prev=new Int32Array(input.length).fill(-1),hashAt=i2=>(input[i2]<<10^input[i2+1]<<5^input[i2+2])&(1<<HASH_BITS)-1,insert=i2=>{if(i2+MIN_MATCH>input.length)return;let h=hashAt(i2);prev[i2]=head[h],head[h]=i2},i=0;for(;i<input.length;){let bestLength=0,bestDistance=0;if(i+MIN_MATCH<=input.length){let candidate=head[hashAt(i)],chain=0,limit=Math.min(MAX_MATCH,input.length-i);for(;candidate>=0&&chain<CHAIN_LIMIT&&i-candidate<=WINDOW;){let length=0;for(;length<limit&&input[candidate+length]===input[i+length];)length+=1;if(length>bestLength&&(bestLength=length,bestDistance=i-candidate,length===limit))break;candidate=prev[candidate],chain+=1}}if(bestLength>=MIN_MATCH){writeMatch(out,bestLength,bestDistance);for(let k=0;k<bestLength;k+=1)insert(i+k);i+=bestLength}else writeLiteral(out,input[i]),insert(i),i+=1}return writeLiteral(out,256),out.finish()}function adler32(bytes){let a=1,b=0;for(let byte2 of bytes)a=(a+byte2)%65521,b=(b+a)%65521;return(b<<16|a)>>>0}var crcTable=null;function crc32(bytes){if(crcTable===null){crcTable=new Uint32Array(256);for(let n=0;n<256;n+=1){let c=n;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n]=c>>>0}}let crc=4294967295;for(let byte2 of bytes)crc=crcTable[(crc^byte2)&255]^crc>>>8;return(crc^4294967295)>>>0}function u32(value){return[value>>>24&255,value>>>16&255,value>>>8&255,value&255]}function chunk(type,data){let typed=Uint8Array.from([...type].map(c=>c.charCodeAt(0))),body=new Uint8Array(typed.length+data.length);return body.set(typed,0),body.set(data,typed.length),[...u32(data.length),...body,...u32(crc32(body))]}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function toBase64(bytes){let out="";for(let i=0;i<bytes.length;i+=3){let a=bytes[i],b=i+1<bytes.length?bytes[i+1]:0,c=i+2<bytes.length?bytes[i+2]:0,triple=a<<16|b<<8|c;out+=BASE64.charAt(triple>>18&63)+BASE64.charAt(triple>>12&63),out+=i+1<bytes.length?BASE64.charAt(triple>>6&63):"=",out+=i+2<bytes.length?BASE64.charAt(triple&63):"="}return out}function encodeSignaturePng(bitmap){let{width:width,height:height,pixels:pixels}=bitmap,stride=Math.ceil(width/8)+1,raw=new Uint8Array(stride*height);for(let y=0;y<height;y+=1){let rowStart=y*stride;raw[rowStart]=0,raw.fill(255,rowStart+1,rowStart+stride);for(let x=0;x<width;x+=1)if(pixels[y*width+x]===1){let index=rowStart+1+(x>>3);raw[index]=raw[index]&~(128>>(x&7))}}let compressed=deflate(raw),idat=new Uint8Array(2+compressed.length+4);idat[0]=120,idat[1]=1,idat.set(compressed,2),idat.set(u32(adler32(raw)),2+compressed.length);let ihdr=Uint8Array.from([...u32(width),...u32(height),1,0,0,0,0]),png=Uint8Array.from([137,80,78,71,13,10,26,10,...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))]);return toBase64(png)}var SIGNATURE_STROKE_WIDTH=2.6,INK="#111111";function strokeSegments(strokes,scale){let segments=[];return strokes.forEach((stroke3,s)=>{let at=i=>{let p=stroke3[i];return[p[0]/scale,p[1]/scale]};if(stroke3.length===1){let[x,y]=at(0);segments.push({key:`${s}-0`,cx:x,cy:y,length:0,angle:0});return}for(let i=1;i<stroke3.length;i+=1){let[x0,y0]=at(i-1),[x1,y1]=at(i);segments.push({key:`${s}-${i}`,cx:(x0+x1)/2,cy:(y0+y1)/2,length:Math.hypot(x1-x0,y1-y0),angle:Math.atan2(y1-y0,x1-x0)})}}),segments}var MIN_DRAWN_POINTS=8,MIN_MOVE=2;function SignaturePad({onChange:onChange,disabled:disabled=false}){let styles=useStyles4(),[mode,setMode]=useState("draw"),[typed,setTyped]=useState(""),[strokes,setStrokes]=useState([]),[width,setWidth]=useState(0),current=useRef([]),drawing=useRef(null),scale=width>0?SIGNATURE_CANVAS.width/width:1,scaleRef=useRef(scale);scaleRef.current=scale;let disabledRef=useRef(disabled);disabledRef.current=disabled,useEffect(()=>{if(mode==="type"){callHost(onChange,typed.trim().length>0?encodeSignaturePng(rasterizeTypedName(typed)):null);return}let points=strokes.reduce((n,stroke3)=>n+stroke3.length,0);callHost(onChange,points>=MIN_DRAWN_POINTS?encodeSignaturePng(rasterizeStrokes(strokes)):null)},[mode,typed,strokes,onChange]);let point=event=>{let{locationX:locationX,locationY:locationY}=event.nativeEvent;return[locationX*scaleRef.current,locationY*scaleRef.current]},commitStroke=()=>{let finished=current.current,inProgress=drawing.current;current.current=[],drawing.current=null,setStrokes(committed=>[...committed.filter(s=>s!==inProgress),finished])},responder=useMemo(()=>PanResponder.create({onStartShouldSetPanResponder:()=>!disabledRef.current,onMoveShouldSetPanResponder:()=>!disabledRef.current,onPanResponderTerminationRequest:()=>false,onPanResponderGrant:event=>{current.current=[point(event)]},onPanResponderMove:event=>{let next=point(event),last=current.current[current.current.length-1];if(last!==void 0&&Math.abs(last[0]-next[0])<MIN_MOVE&&Math.abs(last[1]-next[1])<MIN_MOVE)return;current.current=[...current.current,next];let previous=drawing.current,trail=current.current;drawing.current=trail,setStrokes(committed=>[...committed.filter(s=>s!==previous),trail])},onPanResponderRelease:()=>commitStroke(),onPanResponderTerminate:()=>commitStroke()}),[]),clear=useCallback(()=>{disabledRef.current||(current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[]),toggle=useCallback(()=>{clear(),setMode(m=>m==="draw"?"type":"draw")},[clear]),onLayout=event=>setWidth(event.nativeEvent.layout.width);/* @__PURE__ */
285
+ /* @__PURE__ */jsx(View,{style:[styles.badge,badge.tone==="positive"?styles.badgePositive:badge.tone==="caution"?styles.badgeCaution:styles.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(Text,{style:[styles.badgeLabel,badge.tone==="positive"?styles.badgePositiveText:badge.tone==="caution"?styles.badgeCautionText:styles.badgeNeutralText],children:badge.label})})]})}function useLocalStyles(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles(theme),[theme])}function makeLocalStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),card=theme.slots.card,cardText=slotText(card);return StyleSheet.create({lead:{...text4(type.size.body,type.lineHeight.normal,color.text.muted),paddingHorizontal:space.lg,paddingBottom:space.md},howCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.md,marginTop:space.sm,...slotBox(card)},howTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...cardText},howRow:{flexDirection:"row",gap:space.md},howNumber:{...face(theme,"monoBold"),fontSize:type.size.caption,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.brandInk,minWidth:space.xl},howText:{flex:1,gap:space.xs/2},howStepTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},howStepBody:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary),...cardText},searchBar:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.md+space.xs/2,height:space.xxl+space.md,marginHorizontal:space.lg,marginBottom:space.sm,borderRadius:radius.lg+space.xs/2,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.borderHairlineGreen,...slotBox(theme.slots.input,hairline)},searchInput:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.text.primary),paddingVertical:0,...slotText(theme.slots.input)},clearGlyph:text4(type.size.heading,type.lineHeight.tight,color.text.muted),uploadWrap:{paddingHorizontal:space.lg,paddingBottom:space.md,gap:space.sm},list:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.md},sectionLabel:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:radius.lg-space.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:color.brandBorder,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.md,...slotBox(card,1)},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:space.xxl+space.md},fallbackCopy:{flex:1,gap:space.xs/2},fallbackTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},fallbackSubtitle:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},fallbackForm:{gap:space.sm},item:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(card,1)},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},itemName:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),...cardText},itemDistance:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},itemAddress:{...text4(type.size.caption,type.lineHeight.normal,color.text.primary),...cardText},itemPhone:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},badge:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+1,paddingVertical:space.xs},badgePositive:{backgroundColor:color.badgeBgPositive},badgeCaution:{backgroundColor:color.badgeBgCaution},badgeNeutral:{backgroundColor:color.badgeBgNeutral},badgeLabel:{...text4(type.size.micro,type.lineHeight.snug,color.text.muted,"bold")},badgePositiveText:{color:color.success},badgeCautionText:{color:color.cautionAccent},badgeNeutralText:{color:color.text.muted},footer:{gap:space.sm,paddingTop:space.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,minHeight:space.xxl+space.md},footerRetry:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...text4(type.size.bodyTight,type.lineHeight.snug,color.brandInk,"bold")}})}var CLINIC_BATCH_COPY=/* @__PURE__ */Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${RECORDS_CLINIC_BATCH_MAX} clinics`,send:n2=>`Send ${n2} ${n2===1?"request":"requests"}`,sending:"Sending…",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:name=>`Remove ${name}`,emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn’t send any of these requests. See the details below and try again.",partial:(created,total,failed)=>`${created} of ${total} requests sent. ${failed} couldn’t be sent.`,allSent:created=>`${created} ${created===1?"request":"requests"} sent.`,responded:(responded,total)=>`${responded} of ${total} ${total===1?"clinic":"clinics"} responded`});var CLINIC_FORM_SEARCH_LIMIT=25,CLINIC_FORM_RESULTS_STEP=5;function useVisibleClinics(clinics){let[state,setState]=useState({list:clinics,shown:CLINIC_FORM_RESULTS_STEP}),shown=state.list===clinics?state.shown:CLINIC_FORM_RESULTS_STEP,showMore=useCallback(()=>{setState(previous=>({list:clinics,shown:(previous.list===clinics?previous.shown:CLINIC_FORM_RESULTS_STEP)+CLINIC_FORM_RESULTS_STEP}))},[clinics]);return{visible:clinics.slice(0,shown),hasMore:clinics.length>shown,showMore:showMore}}var SignatureUploadLegError=class extends Error{constructor(){super("Signature upload failed"),this.name="SignatureUploadLegError"}};function isSignatureUploadLegFailure(error){return error instanceof SignatureUploadLegError}function renderClinicScope(copy,owner,pet,clinic){let fields={owner_name:owner,pet_name:pet,clinic_name:clinic},unknown=false,text4=copy.scopeTemplate.replace(/\{([^{}]+)\}/g,(_,key)=>Object.prototype.hasOwnProperty.call(fields,key)?fields[key]??"":(unknown=true,""));return unknown||/[{}]/.test(text4)?null:text4}function clinicNeedsEmail(clinic){return clinic===null||clinic.emailStatus!=="verified"&&clinic.emailStatus!=="unverified"}function useClinicRequestForm(props,controller,capture){let[ownerName,setOwner]=useState(props.ownerName),[query,setQueryValue]=useState(""),[clinic,setClinic]=useState(null),[email2,setEmail]=useState(""),[clinics,setClinics]=useState([]),[recent,setRecent]=useState([]),[copy,setCopy]=useState(null),[error,setError]=useState(null),[busy,setBusy]=useState(false),[searching,setSearching]=useState(false),[created,setCreated]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),active=useRef(false),locked=useRef(false),generation=useRef(0),keyFactory=useRef(defaultIdempotencyKeyFactory()),attempt=useRef(null),captureAbort=useRef(null),lifetime=useRef(0);useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,attempt.current=null,captureAbort.current?.abort()}),[controller]),useEffect(()=>{let live=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let invalidate=()=>{attempt.current=null,setError(null)},clinicName=clinic?.name??query.trim(),scope=copy?renderClinicScope(copy,ownerName.trim(),props.petName,clinicName):null,needsEmail=clinicNeedsEmail(clinic),results=useVisibleClinics(clinics),ready=!!(copy&&scope&&ownerName.trim()&&props.petName.trim()&&clinicName&&(!needsEmail||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email2.trim()))&&capture),search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},submit=async()=>{if(locked.current||created||!ready||!copy||!scope||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(!attempt.current){captureAbort.current=new AbortController;let signature=await capture({petRef:props.petRef,petName:props.petName,ownerName:ownerName.trim(),clinicName:clinicName,authorizationVersion:copy.authorizationVersion,scopeText:scope,signal:captureAbort.current.signal});if(!current()||signature===null)return;let target=clinic&&(!needsEmail||clinic.emailStatus==="none")?{clinicId:clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:email2.trim().toLowerCase()}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}if(!current())return;let result=await controller.createClinicRequest(attempt.current);if(!current())return;if(!result.ok){setError(result.error);return}if(result.value.petRef!==props.petRef){setError(makeEverfurError("internalError"));return}setCreated(result.value),attempt.current=null,props.onCreated?.(result.value)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}};return{ownerName:ownerName,query:query,clinic:clinic,email:email2,clinics:clinics,copy:copy,scope:scope,error:error,busy:busy,searching:searching,created:created,ready:ready,needsEmail:needsEmail,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0&&clinic===null?recent:[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(null),setEmail(""),setQueryValue(value))},setEmail(value){locked.current||(invalidate(),setEmail(value))},selectClinic(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(value),setQueryValue(value.name),setEmail(""))},invalidate:invalidate,search:search,submit:submit,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var EMAIL2=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function draftName(draft){return draft.clinic?.name??draft.freeText??""}function draftNeedsEmail(draft){return clinicNeedsEmail(draft.clinic)}function useClinicBatchForm(props,controller,batchClient,capture,registerSignature){let[ownerName,setOwner]=useState(props.ownerName),[query,setQueryValue]=useState(""),[clinics,setClinics]=useState([]),[recent,setRecent]=useState([]),[drafts,setDrafts]=useState([]),[copy,setCopy]=useState(null),[error,setError]=useState(null),[busy,setBusy]=useState(false),[searching,setSearching]=useState(false),[outcome,setOutcome]=useState(null),[group,setGroup]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),active=useRef(false),locked=useRef(false),generation=useRef(0),lifetime=useRef(0),keyFactory=useRef(defaultIdempotencyKeyFactory()),signature=useRef(null),captureAbort=useRef(null);useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,signature.current=null,captureAbort.current?.abort()}),[controller,batchClient]),useEffect(()=>{let live=true;return setCopy(null),signature.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let results=useVisibleClinics(clinics),invalidate=()=>{signature.current=null,setError(null)},names=drafts.map(draftName),pet=petNameOr(props.petName),scopes=copy?names.map(name=>renderClinicScope(copy,ownerName.trim(),pet,name)):[],scopeText=scopes.every(s=>s!==null)?scopes.join(`\n\n`):null,draftsReady=drafts.length>0&&drafts.every(draft=>!draftNeedsEmail(draft)||EMAIL2.test(draft.email.trim())),atCap=drafts.length>=RECORDS_CLINIC_BATCH_MAX,ready=!!(copy&&scopeText&&ownerName.trim()&&draftsReady&&capture)&&outcome===null,search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},add=draft=>{locked.current||atCap||outcome!==null||draft.clinic!==null&&drafts.some(d=>d.clinic?.id===draft.clinic?.id)||(invalidate(),setDrafts(current=>[...current,{...draft,key:keyFactory.current(),idempotencyKey:keyFactory.current()}]),setClinics([]),setQueryValue(""))},submit=async()=>{if(locked.current||outcome!==null||!ready||!copy||!scopeText||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(signature.current===null){captureAbort.current=new AbortController;let captured=await capture({petRef:props.petRef,petName:pet,ownerName:ownerName.trim(),clinicName:names.join(", "),authorizationVersion:copy.authorizationVersion,scopeText:scopeText,signal:captureAbort.current.signal});if(!current()||captured===null)return;if(signature.current=captured,captured.signaturePngBase64!==void 0&&registerSignature!==void 0){let abort=captureAbort.current;try{let registered=await registerSignature(captured.signaturePngBase64,abort.signal);if(!current())return;signature.current={signatureId:registered.signatureId}}catch(registrationError){if(!isSignatureUploadLegFailure(registrationError)||abort.signal.aborted)throw registrationError;if(!current())return}}}let signed=signature.current,items=drafts.map(draft=>({...draft.clinic!==null&&(!draftNeedsEmail(draft)||draft.clinic.emailStatus==="none")?{clinicId:draft.clinic.id}:{clinicFreeText:draftName(draft)},...draftNeedsEmail(draft)?{clinicEmail:draft.email.trim().toLowerCase()}:{},...signed.signatureId!==void 0?{signatureId:signed.signatureId}:{signaturePngBase64:signed.signaturePngBase64},idempotencyKey:draft.idempotencyKey})),result=await batchClient.createClinicRequestBatch({petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,clinics:items});if(!current())return;if(!result.ok){setError(result.error);return}setOutcome(result.value),props.onCreated?.(result.value),loadGroup(result.value.requestGroupId,run)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}},loadGroup=async(requestGroupId,run)=>{try{let result=await controller.getRequestGroup(requestGroupId);if(!active.current||lifetime.current!==run)return;result.ok&&result.value.petRef===props.petRef&&setGroup(result.value)}catch{}},refreshGroup=async()=>{outcome===null||locked.current||await loadGroup(outcome.requestGroupId,lifetime.current)};return{ownerName:ownerName,query:query,clinics:clinics,copy:copy,scopeText:scopeText,error:error,busy:busy,searching:searching,drafts:drafts,outcome:outcome,group:group,ready:ready,atCap:atCap,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0?recent.filter(clinic=>!drafts.some(d=>d.clinic?.id===clinic.id)):[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(generation.current+=1,setSearching(false),setClinics([]),setQueryValue(value))},search:search,addClinic(clinic){add({clinic:clinic,freeText:null,email:""})},addFreeText(){let name=query.trim();name.length!==0&&add({clinic:null,freeText:name,email:""})},setDraftEmail(key,email2){locked.current||(invalidate(),setDrafts(current=>current.map(draft=>draft.key===key?{...draft,email:email2}:draft)))},removeDraft(key){locked.current||outcome!==null||(invalidate(),setDrafts(current=>current.filter(draft=>draft.key!==key)))},submit:submit,refreshGroup:refreshGroup,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number",probeRef=useRef(null),[reading,setReading]=useState(null),frame2=useRef(null),retry=useRef(null),mounted=useRef(true),stopRetry=useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame2.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame2.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return useMemo(()=>{if(!lifts)return{avoidingProps:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsx(View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function trustedSignatureUploadUrl(value){try{let url=new URL(value);if(url.protocol!=="https:"||url.username||url.password||url.port&&url.port!=="443")return!1;let host=url.hostname.toLowerCase();return host==="s3.amazonaws.com"||host.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(host)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(host)||host==="s3-accelerate.amazonaws.com"||host.endsWith(".s3-accelerate.amazonaws.com")||host==="s3-accelerate.dualstack.amazonaws.com"||host.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}var FAILED="Signature upload failed",UPLOAD_TIMEOUT_MS=3e4;function base64ByteLength(base64){let padding=base64.endsWith("==")?2:base64.endsWith("=")?1:0;return Math.floor(base64.length*3/4)-padding}async function registerRnSignature(signaturePngBase64,controller,signal,fetchImpl){let fail=()=>new Error(FAILED),size=base64ByteLength(signaturePngBase64);if(size<=0||signal.aborted)throw fail();let initiated=await controller.initiateSignatureUpload(size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw fail();let form=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))form.append(key,value);form.append("file",{uri:`data:image/png;base64,${signaturePngBase64}`,name:"signature.png",type:"image/png"});let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,UPLOAD_TIMEOUT_MS);try{if(!(await(fetchImpl??fetch)(initiated.value.uploadUrl,{method:"POST",body:form,credentials:"omit",signal:uploadAbort.signal})).ok||signal.aborted)throw fail()}catch{throw signal.aborted?fail():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw fail();return{signatureId:completed.value}}var SIGNATURE_CANVAS=/* @__PURE__ */Object.freeze({width:360,height:120});function blank(width,height){return{width:width,height:height,pixels:new Uint8Array(width*height)}}function stamp(bitmap,cx,cy,radius){for(let dy=-radius;dy<=radius;dy+=1)for(let dx=-radius;dx<=radius;dx+=1){if(dx*dx+dy*dy>radius*radius+radius)continue;let x=cx+dx,y=cy+dy;x<0||y<0||x>=bitmap.width||y>=bitmap.height||(bitmap.pixels[y*bitmap.width+x]=1)}}var MAX_STEPS_PER_STROKE=16384;function padPoint(point,bitmap){let[x,y]=point;if(!Number.isFinite(x)||!Number.isFinite(y))return null;let cx=Math.min(2*bitmap.width,Math.max(-bitmap.width,Math.round(x))),cy=Math.min(2*bitmap.height,Math.max(-bitmap.height,Math.round(y)));return[cx,cy]}function line(bitmap,from,to,radius,budget){let[x0,y0]=from,[x1,y1]=to,dx=Math.abs(x1-x0),dy=-Math.abs(y1-y0),sx=x0<x1?1:-1,sy=y0<y1?1:-1,error=dx+dy,steps=0;for(;steps<budget&&(stamp(bitmap,x0,y0,radius),steps+=1,!(x0===x1&&y0===y1));){let twice=2*error;twice>=dy&&(error+=dy,x0+=sx),twice<=dx&&(error+=dx,y0+=sy)}return steps}function rasterizeStrokes(strokes,penRadius=1){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height);for(let stroke3 of strokes){let points=[];for(let point of stroke3){let clamped=padPoint(point,bitmap);clamped!==null&&points.push(clamped)}if(points.length===0)continue;if(points.length===1){let[x,y]=points[0];stamp(bitmap,x,y,penRadius);continue}let budget=MAX_STEPS_PER_STROKE;for(let i=1;i<points.length&&budget>0;i+=1)budget-=line(bitmap,points[i-1],points[i],penRadius,budget)}return bitmap}var FONT_ORDER="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",FONT_ROWS="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",FONT_DIGITS="0123456789abcdefghijklmnopqrstuv",GLYPH_W=5,GLYPH_H=7,ADVANCE=GLYPH_W+1;function glyphRow(char,row){let index=FONT_ORDER.indexOf(char);return index<0?0:FONT_DIGITS.indexOf(FONT_ROWS.charAt(index*GLYPH_H+row))}function rasterizeTypedName(name){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height),text4=name.trim();if(text4.length===0)return bitmap;let chars=[...text4],scale=4;for(;scale>1&&(chars.length*ADVANCE-1)*scale>bitmap.width-8;)scale-=1;let textWidth=(chars.length*ADVANCE-1)*scale,x0=Math.max(0,Math.floor((bitmap.width-textWidth)/2)),y0=Math.floor((bitmap.height-GLYPH_H*scale)/2);return chars.forEach((char,i)=>{let gx=x0+i*ADVANCE*scale;for(let row=0;row<GLYPH_H;row+=1){let bits=glyphRow(char,row);for(let col=0;col<GLYPH_W;col+=1)if((bits>>GLYPH_W-1-col&1)!==0)for(let sy=0;sy<scale;sy+=1)for(let sx=0;sx<scale;sx+=1){let x=gx+col*scale+sx,y=y0+row*scale+sy;x<bitmap.width&&y<bitmap.height&&(bitmap.pixels[y*bitmap.width+x]=1)}}}),bitmap}var BitWriter=class{constructor(){this.bytes=[];this.acc=0;this.count=0}writeBits(value,count){for(this.acc|=value<<this.count,this.count+=count;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8}writeCode(code,length){let reversed=0;for(let i=0;i<length;i+=1)reversed=reversed<<1|code>>i&1;this.writeBits(reversed,length)}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};function writeLiteral(out,symbol){symbol<144?out.writeCode(48+symbol,8):symbol<256?out.writeCode(400+(symbol-144),9):symbol<280?out.writeCode(symbol-256,7):out.writeCode(192+(symbol-280),8)}var LENGTH_BASE=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],LENGTH_EXTRA=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],DIST_BASE=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],DIST_EXTRA=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function writeMatch(out,length,distance){let li=LENGTH_BASE.length-1;for(;LENGTH_BASE[li]>length;)li-=1;writeLiteral(out,257+li),LENGTH_EXTRA[li]>0&&out.writeBits(length-LENGTH_BASE[li],LENGTH_EXTRA[li]);let di=DIST_BASE.length-1;for(;DIST_BASE[di]>distance;)di-=1;out.writeCode(di,5),DIST_EXTRA[di]>0&&out.writeBits(distance-DIST_BASE[di],DIST_EXTRA[di])}var WINDOW=32768,MIN_MATCH=3,MAX_MATCH=258,HASH_BITS=15,CHAIN_LIMIT=64;function deflate(input){let out=new BitWriter;out.writeBits(1,1),out.writeBits(1,2);let head=new Int32Array(1<<HASH_BITS).fill(-1),prev=new Int32Array(input.length).fill(-1),hashAt=i2=>(input[i2]<<10^input[i2+1]<<5^input[i2+2])&(1<<HASH_BITS)-1,insert=i2=>{if(i2+MIN_MATCH>input.length)return;let h=hashAt(i2);prev[i2]=head[h],head[h]=i2},i=0;for(;i<input.length;){let bestLength=0,bestDistance=0;if(i+MIN_MATCH<=input.length){let candidate=head[hashAt(i)],chain=0,limit=Math.min(MAX_MATCH,input.length-i);for(;candidate>=0&&chain<CHAIN_LIMIT&&i-candidate<=WINDOW;){let length=0;for(;length<limit&&input[candidate+length]===input[i+length];)length+=1;if(length>bestLength&&(bestLength=length,bestDistance=i-candidate,length===limit))break;candidate=prev[candidate],chain+=1}}if(bestLength>=MIN_MATCH){writeMatch(out,bestLength,bestDistance);for(let k=0;k<bestLength;k+=1)insert(i+k);i+=bestLength}else writeLiteral(out,input[i]),insert(i),i+=1}return writeLiteral(out,256),out.finish()}function adler32(bytes){let a=1,b=0;for(let byte2 of bytes)a=(a+byte2)%65521,b=(b+a)%65521;return(b<<16|a)>>>0}var crcTable=null;function crc32(bytes){if(crcTable===null){crcTable=new Uint32Array(256);for(let n2=0;n2<256;n2+=1){let c=n2;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n2]=c>>>0}}let crc=4294967295;for(let byte2 of bytes)crc=crcTable[(crc^byte2)&255]^crc>>>8;return(crc^4294967295)>>>0}function u32(value){return[value>>>24&255,value>>>16&255,value>>>8&255,value&255]}function chunk(type,data){let typed=Uint8Array.from([...type].map(c=>c.charCodeAt(0))),body=new Uint8Array(typed.length+data.length);return body.set(typed,0),body.set(data,typed.length),[...u32(data.length),...body,...u32(crc32(body))]}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function toBase64(bytes){let out="";for(let i=0;i<bytes.length;i+=3){let a=bytes[i],b=i+1<bytes.length?bytes[i+1]:0,c=i+2<bytes.length?bytes[i+2]:0,triple=a<<16|b<<8|c;out+=BASE64.charAt(triple>>18&63)+BASE64.charAt(triple>>12&63),out+=i+1<bytes.length?BASE64.charAt(triple>>6&63):"=",out+=i+2<bytes.length?BASE64.charAt(triple&63):"="}return out}function encodeSignaturePng(bitmap){let{width:width,height:height,pixels:pixels}=bitmap,stride=Math.ceil(width/8)+1,raw=new Uint8Array(stride*height);for(let y=0;y<height;y+=1){let rowStart=y*stride;raw[rowStart]=0,raw.fill(255,rowStart+1,rowStart+stride);for(let x=0;x<width;x+=1)if(pixels[y*width+x]===1){let index=rowStart+1+(x>>3);raw[index]=raw[index]&~(128>>(x&7))}}let compressed=deflate(raw),idat=new Uint8Array(2+compressed.length+4);idat[0]=120,idat[1]=1,idat.set(compressed,2),idat.set(u32(adler32(raw)),2+compressed.length);let ihdr=Uint8Array.from([...u32(width),...u32(height),1,0,0,0,0]),png=Uint8Array.from([137,80,78,71,13,10,26,10,...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))]);return toBase64(png)}var SIGNATURE_STROKE_WIDTH=2.6,INK="#111111";function strokeSegments(strokes,scale){let segments=[];return strokes.forEach((stroke3,s)=>{let at=i=>{let p=stroke3[i];return[p[0]/scale,p[1]/scale]};if(stroke3.length===1){let[x,y]=at(0);segments.push({key:`${s}-0`,cx:x,cy:y,length:0,angle:0});return}for(let i=1;i<stroke3.length;i+=1){let[x0,y0]=at(i-1),[x1,y1]=at(i);segments.push({key:`${s}-${i}`,cx:(x0+x1)/2,cy:(y0+y1)/2,length:Math.hypot(x1-x0,y1-y0),angle:Math.atan2(y1-y0,x1-x0)})}}),segments}var MIN_DRAWN_POINTS=8,MIN_MOVE=2;function SignaturePad({onChange:onChange,disabled:disabled=false}){let styles=useStyles4(),[mode,setMode]=useState("draw"),[typed,setTyped]=useState(""),[strokes,setStrokes]=useState([]),[width,setWidth]=useState(0),current=useRef([]),drawing=useRef(null),scale=width>0?SIGNATURE_CANVAS.width/width:1,scaleRef=useRef(scale);scaleRef.current=scale;let disabledRef=useRef(disabled);disabledRef.current=disabled,useEffect(()=>{if(mode==="type"){callHost(onChange,typed.trim().length>0?encodeSignaturePng(rasterizeTypedName(typed)):null);return}let points=strokes.reduce((n2,stroke3)=>n2+stroke3.length,0);callHost(onChange,points>=MIN_DRAWN_POINTS?encodeSignaturePng(rasterizeStrokes(strokes)):null)},[mode,typed,strokes,onChange]);let point=event=>{let{locationX:locationX,locationY:locationY}=event.nativeEvent;return[locationX*scaleRef.current,locationY*scaleRef.current]},commitStroke=()=>{let finished=current.current,inProgress=drawing.current;current.current=[],drawing.current=null,setStrokes(committed=>[...committed.filter(s=>s!==inProgress),finished])},responder=useMemo(()=>PanResponder.create({onStartShouldSetPanResponder:()=>!disabledRef.current,onMoveShouldSetPanResponder:()=>!disabledRef.current,onPanResponderTerminationRequest:()=>false,onPanResponderGrant:event=>{current.current=[point(event)]},onPanResponderMove:event=>{let next=point(event),last=current.current[current.current.length-1];if(last!==void 0&&Math.abs(last[0]-next[0])<MIN_MOVE&&Math.abs(last[1]-next[1])<MIN_MOVE)return;current.current=[...current.current,next];let previous=drawing.current,trail=current.current;drawing.current=trail,setStrokes(committed=>[...committed.filter(s=>s!==previous),trail])},onPanResponderRelease:()=>commitStroke(),onPanResponderTerminate:()=>commitStroke()}),[]),clear=useCallback(()=>{disabledRef.current||(current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[]),toggle=useCallback(()=>{clear(),setMode(m=>m==="draw"?"type":"draw")},[clear]),onLayout=event=>setWidth(event.nativeEvent.layout.width);/* @__PURE__ */
286
286
  return jsxs(View,{style:styles.container,testID:"records-signature-pad",children:[
287
287
  /* @__PURE__ */jsx(Text,{style:styles.label,children:mode==="draw"?CLINIC_REQUEST_COPY.draw:CLINIC_REQUEST_COPY.type}),mode==="type"?/* @__PURE__ */jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.type,style:styles.input,value:typed,maxLength:100,editable:!disabled,autoComplete:"off",autoCorrect:false,onChangeText:value=>{disabledRef.current||setTyped(value)}}):null,
288
288
  /* @__PURE__ */jsx(View,{onLayout:onLayout,style:[styles.canvas,{height:width>0?width/3:120}],accessible:true,accessibilityLabel:CLINIC_REQUEST_COPY.sign,accessibilityRole:"image",testID:"records-signature-canvas",...mode==="draw"?responder.panHandlers:{},children:mode==="type"?/* @__PURE__ */jsx(Text,{style:styles.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:typed.trim()}):strokeSegments(strokes,scale).map(segment=>{let box3=segment.length+SIGNATURE_STROKE_WIDTH;/* @__PURE__ */
@@ -323,10 +323,10 @@ return Object.freeze({petRef:pet,withheld:false,markers:/* @__PURE__ */Object.fr
323
323
  /* @__PURE__ */Object.freeze({sourceDocId:item.data.source_doc_id,fileName:item.data.file_name??null,docFormat:item.data.doc_format??null,byteSize:item.data.byte_size??null,receivedAt:item.data.received_at??null,downloadUrl:item.data.download_url,expiresInSeconds:item.data.expires_in_seconds??0}))}/* @__PURE__ */
324
324
  return Object.freeze(rows)}var listSchema3=/* @__PURE__ */z.object({signatures:/* @__PURE__ */z.array(/* @__PURE__ */z.object({signature_id:/* @__PURE__ */z.string().min(1),preview_url:/* @__PURE__ */z.string().min(1).refine(value=>value.startsWith("https://")),created_at:/* @__PURE__ */z.string().nullish()})).optional()});function mapSignatureSuggestions(wire){let parsed=listSchema3.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze((parsed.data.signatures??[]).map(row=>/* @__PURE__ */Object.freeze({signatureId:row.signature_id,previewUrl:row.preview_url,createdAt:row.created_at??null}))):null}var str3=/* @__PURE__ */z.string().nullish(),num2=/* @__PURE__ */z.number().nullish(),labPointSchema=/* @__PURE__ */z.object({at:str3,value:num2,unit:str3,qualitative_result:str3,ref_low:num2,ref_high:num2,status:str3,doc_id:str3}),labMarkerSchema=/* @__PURE__ */z.object({marker_id:/* @__PURE__ */z.string(),name:/* @__PURE__ */z.string(),loinc_code:str3,unit:str3,panel:str3,meaning:str3,latest:/* @__PURE__ */z.object({at:str3,value:num2,unit:str3,qualitative_result:str3,status:str3}).nullish(),trajectory:str3,points:/* @__PURE__ */z.array(labPointSchema).optional()}),encounterSchema=/* @__PURE__ */z.object({encounter_id:/* @__PURE__ */z.string(),date:str3,type:str3,clinic_name:str3,veterinarian:str3,doc_id:str3}),noteSchema=/* @__PURE__ */z.object({note_id:/* @__PURE__ */z.string(),encounter_id:str3,observed_on:str3,sections:/* @__PURE__ */z.array(/* @__PURE__ */z.object({section:/* @__PURE__ */z.string(),text:/* @__PURE__ */z.string()})).optional()}),examSchema=/* @__PURE__ */z.object({exam_id:/* @__PURE__ */z.string(),encounter_id:str3,observed_on:str3,doc_id:str3,systems:/* @__PURE__ */z.record(/* @__PURE__ */z.object({finding_status:str3,finding:str3})).optional()}),completenessSchema=/* @__PURE__ */z.object({has_lab_history:/* @__PURE__ */z.boolean().optional(),has_vaccination_history:/* @__PURE__ */z.boolean().optional(),has_weight_history:/* @__PURE__ */z.boolean().optional(),has_vitals_history:/* @__PURE__ */z.boolean().optional(),has_physical_exam_history:/* @__PURE__ */z.boolean().optional(),has_procedure_history:/* @__PURE__ */z.boolean().optional(),has_genetic_history:/* @__PURE__ */z.boolean().optional(),has_reproductive_history:/* @__PURE__ */z.boolean().optional(),has_parasite_prevention_history:/* @__PURE__ */z.boolean().optional(),earliest_record_at:str3,latest_record_at:str3,documents_ingested:/* @__PURE__ */z.number().int().nonnegative().optional(),documents_in_review:/* @__PURE__ */z.number().int().nonnegative().optional(),entities_pending_review:/* @__PURE__ */z.record(/* @__PURE__ */z.number().int().nonnegative()).optional(),held_total:/* @__PURE__ */z.number().int().nonnegative().optional()}),conflictSchema=/* @__PURE__ */z.object({conflict_id:/* @__PURE__ */z.string(),entity_type:/* @__PURE__ */z.string(),field:str3,severity:str3,candidates:/* @__PURE__ */z.array(/* @__PURE__ */z.object({value:/* @__PURE__ */z.string(),source_doc_id:str3,doc_id:str3,collected_at:str3})).optional()}),depthSchema=/* @__PURE__ */z.object({lab_results:/* @__PURE__ */z.array(labMarkerSchema).optional(),encounters:/* @__PURE__ */z.array(encounterSchema).optional(),clinician_notes:/* @__PURE__ */z.array(noteSchema).optional(),physical_exams:/* @__PURE__ */z.array(examSchema).optional(),completeness:/* @__PURE__ */completenessSchema.nullish(),conflicts:/* @__PURE__ */z.array(conflictSchema).optional()}),timelineSchema=/* @__PURE__ */z.object({visits:/* @__PURE__ */z.array(/* @__PURE__ */z.object({visit_id:/* @__PURE__ */z.string(),visit_date:str3,veterinarian:str3,summary:str3,doc_id:str3})),vaccines:/* @__PURE__ */z.array(/* @__PURE__ */z.object({vaccine_id:/* @__PURE__ */z.string(),product:str3,lot:str3,administered_on:str3,expires_on:str3,doc_id:str3})),weights:/* @__PURE__ */z.array(/* @__PURE__ */z.object({weight_id:/* @__PURE__ */z.string(),observed_on:str3,weight_kg:num2,doc_id:str3})),medications:/* @__PURE__ */z.array(/* @__PURE__ */z.object({medication_id:/* @__PURE__ */z.string(),drug_name:str3,dose:str3,route:str3,frequency:str3,sig:str3,rx_number:str3,started_on:str3,stopped_on:str3,doc_id:str3})),disclaimer:/* @__PURE__ */z.string().optional()}),contributionsSchema=/* @__PURE__ */z.object({document:documentSchema,contributions:/* @__PURE__ */z.array(entitySchema),contribution_count:/* @__PURE__ */z.number().int().nonnegative().optional()});function isObject3(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function petOf(w,petRef){return typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef}function emptyDepth(pet,withheld){/* @__PURE__ */
325
325
  return Object.freeze({petRef:pet,available:false,withheld:withheld,labResults:/* @__PURE__ */Object.freeze([]),encounters:/* @__PURE__ */Object.freeze([]),clinicianNotes:/* @__PURE__ */Object.freeze([]),physicalExams:/* @__PURE__ */Object.freeze([]),completeness:null,conflicts:/* @__PURE__ */Object.freeze([])})}function mapRecordDepth(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef);if(w.withheld===true)return emptyDepth(pet,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(key=>key in w))return emptyDepth(pet,false);let parsed=depthSchema.safeParse(w);if(!parsed.success)return emptyDepth(pet,true);let d=parsed.data,point=p=>/* @__PURE__ */Object.freeze({at:p.at??null,value:p.value??null,unit:p.unit??null,qualitativeResult:p.qualitative_result??null,refLow:p.ref_low??null,refHigh:p.ref_high??null,status:p.status??null,docId:p.doc_id??null});/* @__PURE__ */
326
- return Object.freeze({petRef:pet,available:true,withheld:false,labResults:/* @__PURE__ */Object.freeze((d.lab_results??[]).map(m=>/* @__PURE__ */Object.freeze({markerId:m.marker_id,name:m.name,loincCode:m.loinc_code??null,unit:m.unit??null,panel:m.panel??null,meaning:m.meaning??null,latest:/* @__PURE__ */Object.freeze({at:m.latest?.at??null,value:m.latest?.value??null,unit:m.latest?.unit??null,qualitativeResult:m.latest?.qualitative_result??null,status:m.latest?.status??null}),trajectory:m.trajectory??null,points:/* @__PURE__ */Object.freeze((m.points??[]).map(point))}))),encounters:/* @__PURE__ */Object.freeze((d.encounters??[]).map(e=>/* @__PURE__ */Object.freeze({encounterId:e.encounter_id,date:e.date??null,type:e.type??null,clinicName:e.clinic_name??null,veterinarian:e.veterinarian??null,docId:e.doc_id??null}))),clinicianNotes:/* @__PURE__ */Object.freeze((d.clinician_notes??[]).map(n=>/* @__PURE__ */Object.freeze({noteId:n.note_id,encounterId:n.encounter_id??null,observedOn:n.observed_on??null,sections:/* @__PURE__ */Object.freeze((n.sections??[]).map(s=>/* @__PURE__ */Object.freeze({section:s.section,text:s.text})))}))),physicalExams:/* @__PURE__ */Object.freeze((d.physical_exams??[]).map(x=>/* @__PURE__ */Object.freeze({examId:x.exam_id,encounterId:x.encounter_id??null,observedOn:x.observed_on??null,docId:x.doc_id??null,systems:/* @__PURE__ */Object.freeze(Object.entries(x.systems??{}).map(([system,field])=>/* @__PURE__ */Object.freeze({system:system,findingStatus:field.finding_status??null,finding:field.finding??null})))}))),completeness:d.completeness?/* @__PURE__ */Object.freeze({hasLabHistory:d.completeness.has_lab_history===true,hasVaccinationHistory:d.completeness.has_vaccination_history===true,hasWeightHistory:d.completeness.has_weight_history===true,hasVitalsHistory:d.completeness.has_vitals_history===true,hasPhysicalExamHistory:d.completeness.has_physical_exam_history===true,hasProcedureHistory:d.completeness.has_procedure_history===true,hasGeneticHistory:d.completeness.has_genetic_history===true,hasReproductiveHistory:d.completeness.has_reproductive_history===true,hasParasitePreventionHistory:d.completeness.has_parasite_prevention_history===true,earliestRecordAt:d.completeness.earliest_record_at??null,latestRecordAt:d.completeness.latest_record_at??null,documentsIngested:d.completeness.documents_ingested??0,documentsInReview:d.completeness.documents_in_review??0,entitiesPendingReview:/* @__PURE__ */Object.freeze({...d.completeness.entities_pending_review??{}}),heldTotal:d.completeness.held_total??0}):null,conflicts:/* @__PURE__ */Object.freeze((d.conflicts??[]).map(c=>/* @__PURE__ */Object.freeze({conflictId:c.conflict_id,entityType:c.entity_type,field:c.field??null,severity:c.severity??"needs_review",candidates:/* @__PURE__ */Object.freeze((c.candidates??[]).map(k=>/* @__PURE__ */Object.freeze({value:k.value,docId:k.source_doc_id??k.doc_id??null,collectedAt:k.collected_at??null})))})))})}function withheldTimeline(pet){/* @__PURE__ */
326
+ return Object.freeze({petRef:pet,available:true,withheld:false,labResults:/* @__PURE__ */Object.freeze((d.lab_results??[]).map(m=>/* @__PURE__ */Object.freeze({markerId:m.marker_id,name:m.name,loincCode:m.loinc_code??null,unit:m.unit??null,panel:m.panel??null,meaning:m.meaning??null,latest:/* @__PURE__ */Object.freeze({at:m.latest?.at??null,value:m.latest?.value??null,unit:m.latest?.unit??null,qualitativeResult:m.latest?.qualitative_result??null,status:m.latest?.status??null}),trajectory:m.trajectory??null,points:/* @__PURE__ */Object.freeze((m.points??[]).map(point))}))),encounters:/* @__PURE__ */Object.freeze((d.encounters??[]).map(e=>/* @__PURE__ */Object.freeze({encounterId:e.encounter_id,date:e.date??null,type:e.type??null,clinicName:e.clinic_name??null,veterinarian:e.veterinarian??null,docId:e.doc_id??null}))),clinicianNotes:/* @__PURE__ */Object.freeze((d.clinician_notes??[]).map(n2=>/* @__PURE__ */Object.freeze({noteId:n2.note_id,encounterId:n2.encounter_id??null,observedOn:n2.observed_on??null,sections:/* @__PURE__ */Object.freeze((n2.sections??[]).map(s=>/* @__PURE__ */Object.freeze({section:s.section,text:s.text})))}))),physicalExams:/* @__PURE__ */Object.freeze((d.physical_exams??[]).map(x=>/* @__PURE__ */Object.freeze({examId:x.exam_id,encounterId:x.encounter_id??null,observedOn:x.observed_on??null,docId:x.doc_id??null,systems:/* @__PURE__ */Object.freeze(Object.entries(x.systems??{}).map(([system,field])=>/* @__PURE__ */Object.freeze({system:system,findingStatus:field.finding_status??null,finding:field.finding??null})))}))),completeness:d.completeness?/* @__PURE__ */Object.freeze({hasLabHistory:d.completeness.has_lab_history===true,hasVaccinationHistory:d.completeness.has_vaccination_history===true,hasWeightHistory:d.completeness.has_weight_history===true,hasVitalsHistory:d.completeness.has_vitals_history===true,hasPhysicalExamHistory:d.completeness.has_physical_exam_history===true,hasProcedureHistory:d.completeness.has_procedure_history===true,hasGeneticHistory:d.completeness.has_genetic_history===true,hasReproductiveHistory:d.completeness.has_reproductive_history===true,hasParasitePreventionHistory:d.completeness.has_parasite_prevention_history===true,earliestRecordAt:d.completeness.earliest_record_at??null,latestRecordAt:d.completeness.latest_record_at??null,documentsIngested:d.completeness.documents_ingested??0,documentsInReview:d.completeness.documents_in_review??0,entitiesPendingReview:/* @__PURE__ */Object.freeze({...d.completeness.entities_pending_review??{}}),heldTotal:d.completeness.held_total??0}):null,conflicts:/* @__PURE__ */Object.freeze((d.conflicts??[]).map(c=>/* @__PURE__ */Object.freeze({conflictId:c.conflict_id,entityType:c.entity_type,field:c.field??null,severity:c.severity??"needs_review",candidates:/* @__PURE__ */Object.freeze((c.candidates??[]).map(k=>/* @__PURE__ */Object.freeze({value:k.value,docId:k.source_doc_id??k.doc_id??null,collectedAt:k.collected_at??null})))})))})}function withheldTimeline(pet){/* @__PURE__ */
327
327
  return Object.freeze({petRef:pet,withheld:true,isEmpty:false,visits:/* @__PURE__ */Object.freeze([]),vaccines:/* @__PURE__ */Object.freeze([]),weights:/* @__PURE__ */Object.freeze([]),medications:/* @__PURE__ */Object.freeze([]),disclaimer:""})}function mapRecordsTimeline(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef);if(w.withheld===true)return withheldTimeline(pet);let parsed=timelineSchema.safeParse(w);if(!parsed.success)return withheldTimeline(pet);let t=parsed.data,visits=t.visits.map(v=>/* @__PURE__ */Object.freeze({visitId:v.visit_id,visitDate:v.visit_date??null,veterinarian:v.veterinarian??null,summary:v.summary??null,docId:v.doc_id??null})),vaccines=t.vaccines.map(v=>/* @__PURE__ */Object.freeze({vaccineId:v.vaccine_id,product:v.product??null,lot:v.lot??null,administeredOn:v.administered_on??null,expiresOn:v.expires_on??null,docId:v.doc_id??null})),weights=t.weights.map(v=>/* @__PURE__ */Object.freeze({weightId:v.weight_id,observedOn:v.observed_on??null,weightKg:v.weight_kg??null,docId:v.doc_id??null})),medications=t.medications.map(m=>/* @__PURE__ */Object.freeze({medicationId:m.medication_id,drugName:m.drug_name??null,dose:m.dose??null,route:m.route??null,frequency:m.frequency??null,sig:m.sig??null,rxNumber:m.rx_number??null,startedOn:m.started_on??null,stoppedOn:m.stopped_on??null,docId:m.doc_id??null}));/* @__PURE__ */
328
328
  return Object.freeze({petRef:pet,withheld:false,isEmpty:visits.length===0&&vaccines.length===0&&weights.length===0&&medications.length===0,visits:/* @__PURE__ */Object.freeze(visits),vaccines:/* @__PURE__ */Object.freeze(vaccines),weights:/* @__PURE__ */Object.freeze(weights),medications:/* @__PURE__ */Object.freeze(medications),disclaimer:t.disclaimer??""})}function mapDocumentContributions(petRef,wire){let w=isObject3(wire)?wire:{},pet=petOf(w,petRef),withheld=()=>/* @__PURE__ */Object.freeze({petRef:pet,withheld:true,document:null,contributions:/* @__PURE__ */Object.freeze([]),contributionCount:0});if(w.withheld===true)return withheld();let parsed=contributionsSchema.safeParse(w);if(!parsed.success)return withheld();let contributions=/* @__PURE__ */Object.freeze(parsed.data.contributions.map(mapEntityRow));/* @__PURE__ */
329
- return Object.freeze({petRef:pet,withheld:false,document:mapDocumentRow(parsed.data.document),contributions:contributions,contributionCount:parsed.data.contribution_count??contributions.length})}var BASE3="/widget/v1/records/pets";function createRecordsDepthClient(deps){let funnel=withPlainNotFound(deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}})),segment=(value,max)=>typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)&&[...value].length<=max,read=async(call,petRef,path,map)=>{if(!segment(petRef,PET_REF_MAX))return invalid2();let result=await funnel.send(call,{method:"GET",path:path});if(!result.ok)return result;let view=map(result.value);return view.petRef===petRef?ok(view):err(makeEverfurError("internalError",{retryable:false}))},pet=petRef=>`${BASE3}/${encodeURIComponent(petRef)}`,record=petRef=>`${pet(petRef)}/everfur_record`,parsed=async(call,req,map)=>{let result=await funnel.send(call,req,req.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!result.ok)return result;let value=map(result.value);return value===null?err(makeEverfurError("internalError",{retryable:false})):ok(value)},factBody=(input,corrected)=>!segment(input.entityType,FACT_ENTITY_TYPE_MAX)||!segment(input.canonicalKey,FACT_CANONICAL_KEY_MAX)||input.idempotencyKey!==void 0&&!segment(input.idempotencyKey,IDEMPOTENCY_KEY_MAX)||corrected!==void 0&&Object.keys(corrected).length===0?null:{entity_type:input.entityType,canonical_key:input.canonicalKey,...corrected!==void 0?{corrected_fields:corrected}:{},...input.idempotencyKey!==void 0?{idempotency_key:input.idempotencyKey}:{}};return{getRecordDepth:petRef=>read("records.depth.record",petRef,`${pet(petRef)}/record`,wire=>mapRecordDepth(petRef,wire)),getTimeline:petRef=>read("records.depth.timeline",petRef,`${pet(petRef)}/timeline`,wire=>mapRecordsTimeline(petRef,wire)),getDocumentContributions(petRef,docId){return segment(docId,64)?read("records.depth.contributions",petRef,`${pet(petRef)}/documents/${encodeURIComponent(docId)}/contributions`,wire=>mapDocumentContributions(petRef,wire)):invalid2()},getMarkers:petRef=>read("records.depth.markers",petRef,`${pet(petRef)}/markers`,wire=>mapRecordMarkers(petRef,wire)),createShare(petRef,opts){if(!segment(petRef,PET_REF_MAX))return invalid2();let audience=opts?.audience;return audience!==void 0&&!RECORD_SHARE_AUDIENCES.includes(audience)?invalid2():parsed("records.share.create",{method:"POST",path:`${record(petRef)}/share`,...audience!==void 0?{body:{audience:audience}}:{}},wire=>mapRecordShareLink(wire,deps.apiBaseUrl))},emailShare(petRef,input){let kind=input.recipientKind,email2=typeof input.recipientEmail=="string"?input.recipientEmail.trim():"",kindOk=kind==="other"||RECORD_SHARE_AUDIENCES.includes(kind);return!segment(petRef,PET_REF_MAX)||!kindOk||!isShareRecipientEmail(email2)||hasLoneSurrogate(email2)?invalid2():parsed("records.share.email",{method:"POST",path:`${record(petRef)}/share/email`,body:{recipient_email:email2,recipient_kind:kind}},mapRecordShareEmailReceipt)},async readFeatures(){try{let result=await funnel.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return result.ok?mapRecordsFeatures(result.value):RECORDS_FEATURES_PDF_ONLY}catch{return RECORDS_FEATURES_PDF_ONLY}},listShares(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.share.list",{method:"GET",path:`${record(petRef)}/shares`},mapRecordShareList):invalid2()},async revokeShare(petRef,shareId){if(!segment(petRef,PET_REF_MAX)||!segment(shareId,64))return invalid2();let result=await funnel.send("records.share.revoke",{method:"DELETE",path:`${record(petRef)}/shares/${encodeURIComponent(shareId)}`},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},getPdfLink(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.pdf.link",{method:"GET",path:`${record(petRef)}/pdf-link`},mapRecordPdfLink):invalid2()},async editFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input,input.correctedFields):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.edit",{method:"POST",path:`${record(petRef)}/facts/edit`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},async removeFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.remove",{method:"POST",path:`${record(petRef)}/facts/remove`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},listRequestDocuments(requestId2){return segment(requestId2,64)?parsed("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(requestId2)}/documents`},mapRequestDocuments):invalid2()},listAuthorizationSignatures:()=>parsed("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},mapSignatureSuggestions)}}function invalid2(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsDepthClient(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();return useMemo(()=>{let{services:services}=runtime.registry;return createRecordsDepthClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{},...typeof services.apiBaseUrl=="string"?{apiBaseUrl:services.apiBaseUrl}:{}})},[runtime,userRef,scopeEpoch])}function useRecordsDepthRead(petRef,read,isEmpty,extraKey=""){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),consentEpoch=useRecordsConsentEpoch(petRef),scope=useMemo(()=>({}),[client,petRef,extraKey,consentEpoch]),[state,setState]=useState({scope:scope,value:null,error:null,loading:true}),generation=useRef(0),load=useCallback(async()=>{let gen=generation.current+=1;if(setState({scope:scope,value:null,error:null,loading:true}),userRef===null){setState({scope:scope,value:null,error:null,loading:false});return}let result=await read(client,petRef);gen===generation.current&&(result.ok?setState({scope:scope,value:result.value,error:null,loading:false}):setState({scope:scope,value:null,error:result.error,loading:false}))},[client,petRef,read,scope,userRef]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let current=state.scope===scope?state:{value:null,error:null,loading:true},refresh=useCallback(()=>{load()},[load]),available=current.error===null||current.error.httpStatus!==404,error=available?current.error:null,status=current.loading?"loading":error!==null?"error":current.value===null?"empty":current.value.withheld?"populated":isEmpty(current.value)?"empty":"populated";return useMemo(()=>({status:status,value:current.value,error:error,available:available,refresh:refresh}),[status,current.value,error,available,refresh])}function isDarkRouteError(error){return error!==null&&error.httpStatus===404}var readMarkers=(client,petRef)=>client.getMarkers(petRef),markersEmpty=value=>value.markers.length===0;function useRecordsMarkers(petRef){let state=useRecordsDepthRead(petRef,readMarkers,markersEmpty);return useMemo(()=>{let markers=state.available&&state.value!==null&&!state.value.withheld?state.value:null;return{status:state.status,markers:markers,available:state.available,error:state.error,refresh:state.refresh}},[state])}var EMAIL3=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function useRecordsConsentForm(input){let{clinic:clinic,controller:controller,depthClient:depthClient,capture:capture,onCreated:onCreated}=input,clinicName=clinic.clinic?.name??clinic.freeText??"",isFreeText=clinic.clinic===null,[authorized,setAuthorized]=useState(false),[ownerName,setOwnerName]=useState(input.ownerName),[email2,setEmail]=useState(clinic.email),[emailTouched,setEmailTouched]=useState(false),[copy,setCopy]=useState(null),[copyError,setCopyError]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),[error,setError]=useState(null),[busy,setBusy]=useState(false),[created,setCreated]=useState(null),[signatures,setSignatures]=useState([]),[reuseSignatureId,setReuseSignatureId]=useState(null),[signed,setSigned]=useState(false),locked=useRef(false),live=useRef(true),keyFactory=useRef(defaultIdempotencyKeyFactory()),attempt=useRef(null);useEffect(()=>(live.current=true,()=>{live.current=false,attempt.current=null}),[controller]),useEffect(()=>{let alive=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{alive&&(result.ok?(setCopy(result.value),setCopyError(null)):setCopyError(result.error))}).catch(()=>{alive&&setCopyError(makeEverfurError("internalError"))}),()=>{alive=false}},[controller,copyAttempt]),useEffect(()=>{if(depthClient===void 0)return;let alive=true;return depthClient.listAuthorizationSignatures().then(result=>{alive&&(result.ok?setSignatures(result.value):isDarkRouteError(result.error)||setSignatures([]))}).catch(()=>{}),()=>{alive=false}},[depthClient]);let needsEmail=clinicNeedsEmail(clinic.clinic),normalizedEmail=email2.trim().toLowerCase(),validEmail=EMAIL3.test(normalizedEmail),emailError=needsEmail&&(emailTouched||normalizedEmail.length>0)&&!validEmail?normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired:null,named=ownerName.trim().length>0,scope=copy&&named?renderClinicScope(copy,ownerName.trim(),petNameOr(input.petName),clinicName):null,hasSignature=input.hostCapture===true||signed||reuseSignatureId!==null,readyButSigned=!!(authorized&&copy&&scope&&named&&clinicName&&(!needsEmail||validEmail)),ready=readyButSigned&&hasSignature,submit=useCallback(async()=>{if(!(locked.current||created!==null||!copy||!scope)){if(!clinicName){setError(RECORDS_CONSENT_COPY.missingDraftError);return}if(needsEmail&&!validEmail){setEmailTouched(true),setError(normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired);return}if(!(!authorized||!ownerName.trim())){locked.current=true,setBusy(true),setError(null);try{if(attempt.current===null){let signature=reuseSignatureId!==null?{signatureId:reuseSignatureId}:await capture();if(!live.current)return;if(signature===null){setError(RECORDS_CONSENT_COPY.missingSignatureError);return}let target=clinic.clinic&&(!needsEmail||clinic.clinic.emailStatus==="none")?{clinicId:clinic.clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:input.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:normalizedEmail}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}let result=await controller.createClinicRequest(attempt.current);if(!live.current)return;if(!result.ok){setError(result.error.displayMessage);return}if(result.value.petRef!==input.petRef){setError(makeEverfurError("internalError").displayMessage);return}setCreated(result.value),attempt.current=null,onCreated?.(result.value)}catch{live.current&&setError(makeEverfurError("internalError").displayMessage)}finally{locked.current=false,live.current&&setBusy(false)}}}},[authorized,capture,clinic.clinic,clinicName,controller,copy,created,input.petRef,needsEmail,normalizedEmail,onCreated,ownerName,reuseSignatureId,scope,validEmail]),invalidate=useCallback(()=>{attempt.current=null,setError(null)},[]);return{title:isFreeText?RECORDS_CONSENT_COPY.titleFreeText:RECORDS_CONSENT_COPY.titleDirectory,clinicName:clinicName,isFreeText:isFreeText,authorized:authorized,ownerName:ownerName,email:email2,emailError:emailError,needsEmail:needsEmail,directoryClinicNoEmail:needsEmail&&clinic.clinic!==null,copy:copy,copyError:copyError,scope:scope,error:error,busy:busy,created:created,ready:ready,signatures:signatures,reuseSignatureId:reuseSignatureId,hasSignature:hasSignature,scopeAwaitingName:copy!==null&&!named,signatureLastMissing:readyButSigned&&!hasSignature,setAuthorized(value){locked.current||(invalidate(),setAuthorized(value))},setOwnerName(value){locked.current||(invalidate(),setOwnerName(value))},setEmail(value){locked.current||(invalidate(),setEmailTouched(false),setEmail(value))},setSigned(value){locked.current||(invalidate(),setSigned(value),value&&setReuseSignatureId(null))},pickReuseSignature(signatureId){locked.current||(invalidate(),setReuseSignatureId(signatureId))},retryCopy(){setCopyError(null),setCopyAttempt(n=>n+1)},submit:submit}}function EverfurRecordsConsent(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
329
+ return Object.freeze({petRef:pet,withheld:false,document:mapDocumentRow(parsed.data.document),contributions:contributions,contributionCount:parsed.data.contribution_count??contributions.length})}var BASE3="/widget/v1/records/pets";function createRecordsDepthClient(deps){let funnel=withPlainNotFound(deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}})),segment=(value,max)=>typeof value=="string"&&value.length>0&&!hasLoneSurrogate(value)&&[...value].length<=max,read=async(call,petRef,path,map)=>{if(!segment(petRef,PET_REF_MAX))return invalid2();let result=await funnel.send(call,{method:"GET",path:path});if(!result.ok)return result;let view=map(result.value);return view.petRef===petRef?ok(view):err(makeEverfurError("internalError",{retryable:false}))},pet=petRef=>`${BASE3}/${encodeURIComponent(petRef)}`,record=petRef=>`${pet(petRef)}/everfur_record`,parsed=async(call,req,map)=>{let result=await funnel.send(call,req,req.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!result.ok)return result;let value=map(result.value);return value===null?err(makeEverfurError("internalError",{retryable:false})):ok(value)},factBody=(input,corrected)=>!segment(input.entityType,FACT_ENTITY_TYPE_MAX)||!segment(input.canonicalKey,FACT_CANONICAL_KEY_MAX)||input.idempotencyKey!==void 0&&!segment(input.idempotencyKey,IDEMPOTENCY_KEY_MAX)||corrected!==void 0&&Object.keys(corrected).length===0?null:{entity_type:input.entityType,canonical_key:input.canonicalKey,...corrected!==void 0?{corrected_fields:corrected}:{},...input.idempotencyKey!==void 0?{idempotency_key:input.idempotencyKey}:{}};return{getRecordDepth:petRef=>read("records.depth.record",petRef,`${pet(petRef)}/record`,wire=>mapRecordDepth(petRef,wire)),getTimeline:petRef=>read("records.depth.timeline",petRef,`${pet(petRef)}/timeline`,wire=>mapRecordsTimeline(petRef,wire)),getDocumentContributions(petRef,docId){return segment(docId,64)?read("records.depth.contributions",petRef,`${pet(petRef)}/documents/${encodeURIComponent(docId)}/contributions`,wire=>mapDocumentContributions(petRef,wire)):invalid2()},getMarkers:petRef=>read("records.depth.markers",petRef,`${pet(petRef)}/markers`,wire=>mapRecordMarkers(petRef,wire)),createShare(petRef,opts){if(!segment(petRef,PET_REF_MAX))return invalid2();let audience=opts?.audience;return audience!==void 0&&!RECORD_SHARE_AUDIENCES.includes(audience)?invalid2():parsed("records.share.create",{method:"POST",path:`${record(petRef)}/share`,...audience!==void 0?{body:{audience:audience}}:{}},wire=>mapRecordShareLink(wire,deps.apiBaseUrl))},emailShare(petRef,input){let kind=input.recipientKind,email2=typeof input.recipientEmail=="string"?input.recipientEmail.trim():"",kindOk=kind==="other"||RECORD_SHARE_AUDIENCES.includes(kind);return!segment(petRef,PET_REF_MAX)||!kindOk||!isShareRecipientEmail(email2)||hasLoneSurrogate(email2)?invalid2():parsed("records.share.email",{method:"POST",path:`${record(petRef)}/share/email`,body:{recipient_email:email2,recipient_kind:kind}},mapRecordShareEmailReceipt)},async readFeatures(){try{let result=await funnel.send("records.getFeatures",{method:"GET",path:"/widget/v1/records/features"});return result.ok?mapRecordsFeatures(result.value):RECORDS_FEATURES_PDF_ONLY}catch{return RECORDS_FEATURES_PDF_ONLY}},listShares(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.share.list",{method:"GET",path:`${record(petRef)}/shares`},mapRecordShareList):invalid2()},async revokeShare(petRef,shareId){if(!segment(petRef,PET_REF_MAX)||!segment(shareId,64))return invalid2();let result=await funnel.send("records.share.revoke",{method:"DELETE",path:`${record(petRef)}/shares/${encodeURIComponent(shareId)}`},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},getPdfLink(petRef){return segment(petRef,PET_REF_MAX)?parsed("records.pdf.link",{method:"GET",path:`${record(petRef)}/pdf-link`},mapRecordPdfLink):invalid2()},async editFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input,input.correctedFields):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.edit",{method:"POST",path:`${record(petRef)}/facts/edit`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},async removeFact(petRef,input){let body=segment(petRef,PET_REF_MAX)?factBody(input):null;if(body===null)return invalid2();let result=await funnel.send("records.fact.remove",{method:"POST",path:`${record(petRef)}/facts/remove`,body:body},{idempotent:false,maxAttempts:1});return result.ok?ok(void 0):result},listRequestDocuments(requestId2){return segment(requestId2,64)?parsed("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(requestId2)}/documents`},mapRequestDocuments):invalid2()},listAuthorizationSignatures:()=>parsed("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},mapSignatureSuggestions)}}function invalid2(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsDepthClient(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();return useMemo(()=>{let{services:services}=runtime.registry;return createRecordsDepthClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{},...typeof services.apiBaseUrl=="string"?{apiBaseUrl:services.apiBaseUrl}:{}})},[runtime,userRef,scopeEpoch])}function useRecordsDepthRead(petRef,read,isEmpty,extraKey=""){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),consentEpoch=useRecordsConsentEpoch(petRef),scope=useMemo(()=>({}),[client,petRef,extraKey,consentEpoch]),[state,setState]=useState({scope:scope,value:null,error:null,loading:true}),generation=useRef(0),load=useCallback(async()=>{let gen=generation.current+=1;if(setState({scope:scope,value:null,error:null,loading:true}),userRef===null){setState({scope:scope,value:null,error:null,loading:false});return}let result=await read(client,petRef);gen===generation.current&&(result.ok?setState({scope:scope,value:result.value,error:null,loading:false}):setState({scope:scope,value:null,error:result.error,loading:false}))},[client,petRef,read,scope,userRef]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let current=state.scope===scope?state:{value:null,error:null,loading:true},refresh=useCallback(()=>{load()},[load]),available=current.error===null||current.error.httpStatus!==404,error=available?current.error:null,status=current.loading?"loading":error!==null?"error":current.value===null?"empty":current.value.withheld?"populated":isEmpty(current.value)?"empty":"populated";return useMemo(()=>({status:status,value:current.value,error:error,available:available,refresh:refresh}),[status,current.value,error,available,refresh])}function isDarkRouteError(error){return error!==null&&error.httpStatus===404}var readMarkers=(client,petRef)=>client.getMarkers(petRef),markersEmpty=value=>value.markers.length===0;function useRecordsMarkers(petRef){let state=useRecordsDepthRead(petRef,readMarkers,markersEmpty);return useMemo(()=>{let markers=state.available&&state.value!==null&&!state.value.withheld?state.value:null;return{status:state.status,markers:markers,available:state.available,error:state.error,refresh:state.refresh}},[state])}var EMAIL3=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function useRecordsConsentForm(input){let{clinic:clinic,controller:controller,depthClient:depthClient,capture:capture,onCreated:onCreated}=input,clinicName=clinic.clinic?.name??clinic.freeText??"",isFreeText=clinic.clinic===null,[authorized,setAuthorized]=useState(false),[ownerName,setOwnerName]=useState(input.ownerName),[email2,setEmail]=useState(clinic.email),[emailTouched,setEmailTouched]=useState(false),[copy,setCopy]=useState(null),[copyError,setCopyError]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),[error,setError]=useState(null),[busy,setBusy]=useState(false),[created,setCreated]=useState(null),[signatures,setSignatures]=useState([]),[reuseSignatureId,setReuseSignatureId]=useState(null),[signed,setSigned]=useState(false),locked=useRef(false),live=useRef(true),keyFactory=useRef(defaultIdempotencyKeyFactory()),attempt=useRef(null);useEffect(()=>(live.current=true,()=>{live.current=false,attempt.current=null}),[controller]),useEffect(()=>{let alive=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{alive&&(result.ok?(setCopy(result.value),setCopyError(null)):setCopyError(result.error))}).catch(()=>{alive&&setCopyError(makeEverfurError("internalError"))}),()=>{alive=false}},[controller,copyAttempt]),useEffect(()=>{if(depthClient===void 0)return;let alive=true;return depthClient.listAuthorizationSignatures().then(result=>{alive&&(result.ok?setSignatures(result.value):isDarkRouteError(result.error)||setSignatures([]))}).catch(()=>{}),()=>{alive=false}},[depthClient]);let needsEmail=clinicNeedsEmail(clinic.clinic),normalizedEmail=email2.trim().toLowerCase(),validEmail=EMAIL3.test(normalizedEmail),emailError=needsEmail&&(emailTouched||normalizedEmail.length>0)&&!validEmail?normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired:null,named=ownerName.trim().length>0,scope=copy&&named?renderClinicScope(copy,ownerName.trim(),petNameOr(input.petName),clinicName):null,hasSignature=input.hostCapture===true||signed||reuseSignatureId!==null,readyButSigned=!!(authorized&&copy&&scope&&named&&clinicName&&(!needsEmail||validEmail)),ready=readyButSigned&&hasSignature,submit=useCallback(async()=>{if(!(locked.current||created!==null||!copy||!scope)){if(!clinicName){setError(RECORDS_CONSENT_COPY.missingDraftError);return}if(needsEmail&&!validEmail){setEmailTouched(true),setError(normalizedEmail.length>0?RECORDS_CONSENT_COPY.emailInvalid:RECORDS_CONSENT_COPY.emailRequired);return}if(!(!authorized||!ownerName.trim())){locked.current=true,setBusy(true),setError(null);try{if(attempt.current===null){let signature=reuseSignatureId!==null?{signatureId:reuseSignatureId}:await capture();if(!live.current)return;if(signature===null){setError(RECORDS_CONSENT_COPY.missingSignatureError);return}let target=clinic.clinic&&(!needsEmail||clinic.clinic.emailStatus==="none")?{clinicId:clinic.clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:input.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:normalizedEmail}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}let result=await controller.createClinicRequest(attempt.current);if(!live.current)return;if(!result.ok){setError(result.error.displayMessage);return}if(result.value.petRef!==input.petRef){setError(makeEverfurError("internalError").displayMessage);return}setCreated(result.value),attempt.current=null,onCreated?.(result.value)}catch{live.current&&setError(makeEverfurError("internalError").displayMessage)}finally{locked.current=false,live.current&&setBusy(false)}}}},[authorized,capture,clinic.clinic,clinicName,controller,copy,created,input.petRef,needsEmail,normalizedEmail,onCreated,ownerName,reuseSignatureId,scope,validEmail]),invalidate=useCallback(()=>{attempt.current=null,setError(null)},[]);return{title:isFreeText?RECORDS_CONSENT_COPY.titleFreeText:RECORDS_CONSENT_COPY.titleDirectory,clinicName:clinicName,isFreeText:isFreeText,authorized:authorized,ownerName:ownerName,email:email2,emailError:emailError,needsEmail:needsEmail,directoryClinicNoEmail:needsEmail&&clinic.clinic!==null,copy:copy,copyError:copyError,scope:scope,error:error,busy:busy,created:created,ready:ready,signatures:signatures,reuseSignatureId:reuseSignatureId,hasSignature:hasSignature,scopeAwaitingName:copy!==null&&!named,signatureLastMissing:readyButSigned&&!hasSignature,setAuthorized(value){locked.current||(invalidate(),setAuthorized(value))},setOwnerName(value){locked.current||(invalidate(),setOwnerName(value))},setEmail(value){locked.current||(invalidate(),setEmailTouched(false),setEmail(value))},setSigned(value){locked.current||(invalidate(),setSigned(value),value&&setReuseSignatureId(null))},pickReuseSignature(signatureId){locked.current||(invalidate(),setReuseSignatureId(signatureId))},retryCopy(){setCopyError(null),setCopyAttempt(n2=>n2+1)},submit:submit}}function EverfurRecordsConsent(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
330
330
  return jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(ConsentBody,{...guardHostProps(props,["onCreated","onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.clinic.key]))})}var IOS2=Platform.OS==="ios";function ConsentBody({petRef:petRef,petName:petName,clinic:clinic,ownerName:ownerName,onCaptureSignature:onCaptureSignature,onCreated:onCreated,controller:controller,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles3(),theme=useEverfurTheme(),runtimeController=useEverfurRecordsClinic(),directSendNote=useRecordsSandboxTenant()?RECORDS_SANDBOX_COPY.newClinicDirectSendNote:RECORDS_CONSENT_COPY.newClinicDirectSendNote,depthClient=useEverfurRecordsDepthClient(),[png,setPng]=useState(null),[mode,setMode]=useState("draw"),padCapture=useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useRecordsConsentForm({petRef:petRef,petName:petName,ownerName:ownerName??"",clinic:clinic,controller:controller??runtimeController,depthClient:depthClient,capture:onCaptureSignature?()=>onCaptureSignature({petRef:petRef,petName:petNameOr(petName),ownerName:form.ownerName,clinicName:form.clinicName,authorizationVersion:form.copy?.authorizationVersion??"",scopeText:form.scope??"",signal:(new AbortController).signal}):padCapture,hostCapture:onCaptureSignature!==void 0,onCreated:request=>{onCreated?.(request),onNavigate?.({name:"dashboard"})}}),formRef=useRef(form);formRef.current=form;let onPadChange=useCallback(next=>{setPng(next),formRef.current.setSigned(next!==null)},[]),busy=form.busy,keyboard=useChatKeyboardOffset(void 0,IOS2);/* @__PURE__ */
331
331
  return jsxs(View,{style:[styles.root,style],children:[
332
332
  /* @__PURE__ */jsx(ScreenHeader,{title:form.title,onBack:onBack,testID:"records-consent-header"}),
@@ -408,7 +408,7 @@ return jsxs(Modal,{transparent:true,visible:true,animationType:"slide",onRequest
408
408
  /* @__PURE__ */jsxs(View,{style:styles.valueRow,children:[
409
409
  /* @__PURE__ */jsx(Text,{style:styles.sheetName,children:marker.name}),
410
410
  /* @__PURE__ */jsx(Text,{style:styles.sheetValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsx(View,{style:styles.reviewed,accessibilityRole:"text",children:/* @__PURE__ */jsx(Text,{style:styles.reviewedText,children:PROVENANCE_COPY.reviewed})}):null,row(PROVENANCE_COPY.collected,formatRecordsDate(point.at)),point.sourceClinic?row(PROVENANCE_COPY.clinic,point.sourceClinic):null,row(PROVENANCE_COPY.referenceRange,point.refLow!==null||point.refHigh!==null?formatReferenceRange(point,marker.unit):PROVENANCE_COPY.noRange),point.docId?row(PROVENANCE_COPY.sourceDocument,point.docId):null,point.reviewed?null:/* @__PURE__ */jsx(Text,{style:styles.unverified,accessibilityRole:"text",children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsx(Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.ask,style:[screen.pill,screen.pillAsk],testID:"marker-provenance-ask",children:/* @__PURE__ */jsx(Text,{style:screen.pillAskLabel,children:PROVENANCE_COPY.ask})}):null]})]})]})}function useStyles6(){let theme=useEverfurTheme();return useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=StyleSheet.hairlineWidth,dot=space.md,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),cardText=slotText(recordCardSlot(slots)),dialogText=slotText(slots.dialog),nameText={...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},valueText=text4(type.size.verdict+space.xs,type.lineHeight.tight,color.text.primary,"bold");return StyleSheet.create({page:{paddingHorizontal:space.sm},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,gap:space.md,...slotBox(recordCardSlot(slots),1)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm+space.xs/2},nameColumn:{flex:1,gap:space.xs/2},markerName:{...nameText,...cardText},sheetName:{...nameText,...dialogText},unit:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted,...cardText},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},latestValue:{...valueText,...cardText},sheetValue:{...valueText,...dialogText},latestValueDanger:{color:color.danger},latestDate:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},trajectory:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...cardText},chartWrap:{gap:space.sm},plot:{height:PLOT_HEIGHT,borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:color.badgeBgPositive},point:{position:"absolute",width:dot,height:dot,borderRadius:dot/2,marginLeft:-dot/2,marginTop:-dot/2,backgroundColor:color.brand,borderWidth:2,borderColor:color.surface},pointDanger:{backgroundColor:color.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...text4(type.size.tiny,type.lineHeight.normal,color.text.placeholder),textAlign:"center",...cardText},singleHint:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},emptyBody:{alignItems:"center",justifyContent:"center",gap:space.sm,paddingVertical:space.xxl+space.xs},emptyText:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},carousel:{height:CAROUSEL_HEIGHT},footer:{alignItems:"center",gap:space.sm,paddingTop:space.md},dots:{flexDirection:"row",gap:space.xs+space.xs/2},dot:{width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs-1,backgroundColor:color.borderHairlineGreen},dotActive:{width:space.lg+space.xs/2,backgroundColor:color.brand},counter:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,letterSpacing:type.letterSpacing.eyebrow/3,color:color.text.muted},backdrop:{flex:1,backgroundColor:SHEET_SCRIM},sheet:{backgroundColor:color.surfaceCream,borderTopLeftRadius:radius.xl-space.xs,borderTopRightRadius:radius.xl-space.xs,paddingHorizontal:space.lg+space.xs,paddingTop:space.sm,paddingBottom:space.xxl+space.xs,maxHeight:"80%",gap:space.md,...sheetSlotBox(slots.dialog)},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},sheetTitle:{flex:1,...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...dialogText},closeButton:{width:space.xxl+space.md,height:space.xxl+space.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...text4(type.size.verdict,type.lineHeight.tight,color.text.primary),...dialogText},sheetBody:{gap:space.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},reviewed:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs,backgroundColor:color.badgeBgPositive},reviewedText:{...text4(type.size.tiny,type.lineHeight.normal,color.success,"medium")},detailRow:{gap:space.xs/2},detailLabel:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted,"medium"),...dialogText},detailValue:{...text4(type.size.body,type.lineHeight.normal,color.text.primary),...dialogText},unverified:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...dialogText}})}var FACT_EDIT_COPY=/* @__PURE__ */Object.freeze({editA11y:label=>`Edit ${label}. Correct or remove this record detail.`,title:label=>`Edit ${label}`,helper:"Corrects your record. Your vet can still review it.",close:"Close",closeEditorA11y:"Close editor",save:"Save changes",saving:"Saving...",remove:"Remove this detail",confirmRemove:"Remove this detail from your record? This can't be undone.",removeConfirm:"Remove",removing:"Removing...",keep:"Keep",noChange:"Change a value before saving.",saved:"Saved.",removed:"Removed.",detail:"record detail"});function factEditErrorMessage(error,mode){return isRecordsConsentRequired(error)?mode==="remove"?"Records access for this pet is off, so this detail cannot be removed.":"Records access for this pet is off, so this detail cannot be changed.":isFactReviewerLocked(error)?mode==="remove"?"A clinician already reviewed this detail, so it can't be removed here.":"A clinician already reviewed this detail, so it can't be changed here.":mode==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}var EMPTY_FACT_OVERLAY=/* @__PURE__ */Object.freeze({edits:/* @__PURE__ */Object.freeze({}),removed:/* @__PURE__ */Object.freeze([])});function applyFactOverlay(entities,overlay){if(Object.keys(overlay.edits).length===0&&overlay.removed.length===0)return entities;let out=[];for(let entity of entities){let key=entity.canonicalKey??null;if(key!==null&&overlay.removed.includes(key))continue;let edited=key!==null?overlay.edits[key]:void 0;out.push(edited===void 0?entity:/* @__PURE__ */Object.freeze({...entity,value:edited}))}/* @__PURE__ */
411
- return Object.freeze(out)}function isFactEditable(entity){return typeof entity.canonicalKey=="string"&&entity.canonicalKey.length>0}function defaultFactKey(){return`records-fact-${Date.now().toString(36)}`}function useRecordFactEdit(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),[overlay,setOverlay]=useState(EMPTY_FACT_OVERLAY),[busy,setBusy]=useState(false),[error,setError]=useState(null),scope=useMemo(()=>({}),[client,petRef,userRef]),[darkScope,setDarkScope]=useState(null),markDark=useCallback(()=>setDarkScope(scope),[scope]),[refused,setRefused]=useState(null);useEffect(()=>{if(userRef===null||client.readFeatures===void 0)return;let current=true;return client.readFeatures().then(value=>{current&&value.features.fact_edit===false&&setRefused(scope)},()=>{}),()=>{current=false}},[client,userRef,scope]);let available=userRef!==null&&darkScope!==scope&&refused!==scope,locked=useRef(false),mintRef=useRef(opts.newIdempotencyKey);mintRef.current=opts.newIdempotencyKey;let mint=useCallback(()=>(mintRef.current??defaultFactKey)(),[]),settle=useCallback((result,rollback,mode)=>{if(setBusy(false),!result.ok){if(rollback(),isDarkRouteError(result.error)){markDark();return}setError(factEditErrorMessage(result.error,mode))}},[markDark]),edit=useCallback(async(entity,value)=>{let key=entity.canonicalKey??"",next=value.trim();if(locked.current||key.length===0||next.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,edits:{...current.edits,[key]:next}}));let result=await client.editFact(petRef,{entityType:entity.category,canonicalKey:key,correctedFields:factCorrectionFor(entity.value,next),idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"edit"),result},[client,petRef,overlay,settle,mint]),remove=useCallback(async entity=>{let key=entity.canonicalKey??"";if(locked.current||key.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,removed:[...current.removed,key]}));let result=await client.removeFact(petRef,{entityType:entity.category,canonicalKey:key,idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"remove"),result},[client,petRef,overlay,settle,mint]),clearError=useCallback(()=>setError(null),[]);return useMemo(()=>({overlay:overlay,busy:busy,error:error,available:available,edit:edit,remove:remove,clearError:clearError}),[overlay,busy,error,available,edit,remove,clearError])}var VACCINE_CATEGORIES=/* @__PURE__ */Object.freeze(["vaccination","parasite_prevention"]),VACCINE_UNDATED_GROUP="Undated",VACCINE_STATUS_LABEL=/* @__PURE__ */Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),VACCINE_CHIP_TONE=/* @__PURE__ */Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function toMillis(value){if(!value)return null;let ms=Date.parse(value);return Number.isNaN(ms)?null:ms}function isLapsed(entity){let status=entity.status?.toLowerCase()??"";return/overdue|lapsed|expired/.test(status)}function vaccineTone(entity){return entity.category==="parasite_prevention"?"prevention":toMillis(entity.observedAt)===null?"noDate":isLapsed(entity)?"overdue":"given"}function yearOf(at){let ms=toMillis(at);return ms===null?VACCINE_UNDATED_GROUP:String(new Date(ms).getUTCFullYear())}function buildRow(entity){let tone=vaccineTone(entity),parts=[entity.value!==null&&entity.value.length>0?entity.value:null,entity.observedAt!==null?formatRecordsDate(entity.observedAt):null].filter(part=>part!==null&&part.length>0);return{key:entity.key,name:entity.label,detail:parts.length>0?parts.join(" · "):null,statusLabel:VACCINE_STATUS_LABEL[tone],tone:tone,entity:entity}}function selectVaccineGroups(entities){let byYear=/* @__PURE__ */new Map;for(let entity of entities){if(!VACCINE_CATEGORIES.includes(entity.category))continue;let year=yearOf(entity.observedAt),bucket=byYear.get(year),item={row:buildRow(entity),at:entity.observedAt};bucket===void 0?byYear.set(year,[item]):bucket.push(item)}let years=[...byYear.keys()].sort((a,b)=>a===VACCINE_UNDATED_GROUP?1:b===VACCINE_UNDATED_GROUP?-1:Number(b)-Number(a));/* @__PURE__ */
411
+ return Object.freeze(out)}function isFactEditable(entity){return typeof entity.canonicalKey=="string"&&entity.canonicalKey.length>0}function defaultFactKey(){return`records-fact-${Date.now().toString(36)}`}function useRecordFactEdit(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),[overlay,setOverlay]=useState(EMPTY_FACT_OVERLAY),[busy,setBusy]=useState(false),[error,setError]=useState(null),scope=useMemo(()=>({}),[client,petRef,userRef]),[darkScope,setDarkScope]=useState(null),markDark=useCallback(()=>setDarkScope(scope),[scope]),[refused,setRefused]=useState(null);useEffect(()=>{if(userRef===null||client.readFeatures===void 0)return;let current=true;return client.readFeatures().then(value=>{current&&value.features.fact_edit===false&&setRefused(scope)},()=>{}),()=>{current=false}},[client,userRef,scope]);let available=userRef!==null&&darkScope!==scope&&refused!==scope,locked=useRef(false),mintRef=useRef(opts.newIdempotencyKey);mintRef.current=opts.newIdempotencyKey;let mint=useCallback(()=>(mintRef.current??defaultFactKey)(),[]),settle=useCallback((result,rollback,mode)=>{if(setBusy(false),!result.ok){if(rollback(),isDarkRouteError(result.error)){markDark();return}setError(factEditErrorMessage(result.error,mode))}},[markDark]),edit=useCallback(async(entity,value)=>{let key=entity.canonicalKey??"",next=value.trim();if(locked.current||key.length===0||next.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,edits:{...current.edits,[key]:next}}));let result=await client.editFact(petRef,{entityType:entity.category,canonicalKey:key,correctedFields:factCorrectionFor(entity.value,next),idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"edit"),result},[client,petRef,overlay,settle,mint]),remove=useCallback(async entity=>{let key=entity.canonicalKey??"";if(locked.current||key.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,removed:[...current.removed,key]}));let result=await client.removeFact(petRef,{entityType:entity.category,canonicalKey:key,idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"remove"),result},[client,petRef,overlay,settle,mint]),clearError=useCallback(()=>setError(null),[]);return useMemo(()=>({overlay:overlay,busy:busy,error:error,available:available,edit:edit,remove:remove,clearError:clearError}),[overlay,busy,error,available,edit,remove,clearError])}var VACCINE_CATEGORIES=/* @__PURE__ */Object.freeze(["vaccination","parasite_prevention"]),VACCINE_UNDATED_GROUP="Undated",VACCINE_STATUS_LABEL=/* @__PURE__ */Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),VACCINE_CHIP_TONE=/* @__PURE__ */Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function toMillis(value){if(!value)return null;let ms2=Date.parse(value);return Number.isNaN(ms2)?null:ms2}function isLapsed(entity){let status=entity.status?.toLowerCase()??"";return/overdue|lapsed|expired/.test(status)}function vaccineTone(entity){return entity.category==="parasite_prevention"?"prevention":toMillis(entity.observedAt)===null?"noDate":isLapsed(entity)?"overdue":"given"}function yearOf(at){let ms2=toMillis(at);return ms2===null?VACCINE_UNDATED_GROUP:String(new Date(ms2).getUTCFullYear())}function buildRow(entity){let tone=vaccineTone(entity),parts=[entity.value!==null&&entity.value.length>0?entity.value:null,entity.observedAt!==null?formatRecordsDate(entity.observedAt):null].filter(part=>part!==null&&part.length>0);return{key:entity.key,name:entity.label,detail:parts.length>0?parts.join(" · "):null,statusLabel:VACCINE_STATUS_LABEL[tone],tone:tone,entity:entity}}function selectVaccineGroups(entities){let byYear=/* @__PURE__ */new Map;for(let entity of entities){if(!VACCINE_CATEGORIES.includes(entity.category))continue;let year=yearOf(entity.observedAt),bucket=byYear.get(year),item={row:buildRow(entity),at:entity.observedAt};bucket===void 0?byYear.set(year,[item]):bucket.push(item)}let years=[...byYear.keys()].sort((a,b)=>a===VACCINE_UNDATED_GROUP?1:b===VACCINE_UNDATED_GROUP?-1:Number(b)-Number(a));/* @__PURE__ */
412
412
  return Object.freeze(years.map(year=>{let items=byYear.get(year)??[],ordered=year===VACCINE_UNDATED_GROUP?items:[...items].sort((a,b)=>(toMillis(b.at)??0)-(toMillis(a.at)??0));/* @__PURE__ */
413
413
  return Object.freeze({year:year,items:/* @__PURE__ */Object.freeze(ordered.map(i=>i.row))})}))}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});function FactEditAffordance({entity:entity,factEdit:factEdit,children:children}){let styles=useStyles7(),[open,setOpen]=useState(false),label=entity.label.trim()||FACT_EDIT_COPY.detail;/* @__PURE__ */
414
414
  return jsxs(View,{style:styles.row,children:[
@@ -459,7 +459,7 @@ return jsxs(View,{style:[local.conflictCard,{borderColor:styles.chipTones[meta.t
459
459
  return jsxs(View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
460
460
  /* @__PURE__ */jsxs(View,{style:styles.rowMain,children:[
461
461
  /* @__PURE__ */jsx(Text,{style:styles.rowTitle,children:item.title}),item.detail?/* @__PURE__ */jsx(Text,{style:styles.rowDetail,children:item.detail}):null]}),badge?/* @__PURE__ */jsx(Chip,{label:badge.label,tone:badge.overdue?"critical":"info"}):null]},`${item.title}-${index}`)})}),ask(()=>buildUpcomingCareAskPrompt(petName,record.forwardLooking.map(item=>{let badge=dueBadge(item.dueAt,now);return{label:item.title,relativeText:badge?.label??"",tone:badge?.overdue?"overdue":"upcoming"}}),record.petRef),RECORD_SCREEN_COPY.askUpcomingCare,"records-ask-upcoming-care")]}):null,vaccineGroups.length>0?/* @__PURE__ */jsxs(View,{style:styles.section,testID:"record-section-vaccination",children:[
462
- /* @__PURE__ */jsx(SectionHeader,{title:entityTypeLabel("vaccination"),count:vaccineGroups.reduce((n,g)=>n+g.items.length,0)}),vaccineGroups.map(group=>/* @__PURE__ */jsxs(View,{style:local.vaccineGroup,testID:`records-vaccine-group-${group.year}`,children:[
462
+ /* @__PURE__ */jsx(SectionHeader,{title:entityTypeLabel("vaccination"),count:vaccineGroups.reduce((n2,g)=>n2+g.items.length,0)}),vaccineGroups.map(group=>/* @__PURE__ */jsxs(View,{style:local.vaccineGroup,testID:`records-vaccine-group-${group.year}`,children:[
463
463
  /* @__PURE__ */jsx(Text,{style:local.vaccineYear,accessibilityRole:"header",children:group.year.toUpperCase()}),
464
464
  /* @__PURE__ */jsx(View,{style:styles.card,children:group.items.map((row,index)=>{let body=/* @__PURE__ */jsxs(View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
465
465
  /* @__PURE__ */jsxs(View,{style:styles.rowMain,children:[
@@ -491,7 +491,7 @@ return jsxs(View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
491
491
  /* @__PURE__ */jsx(View,{style:styles.card,children:depth.encounters.map((encounter,index)=>{let detail=[encounter.date?formatRecordsDate(encounter.date):null,encounter.clinicName,encounter.veterinarian].filter(p=>p&&p!=="-").join(" · ");/* @__PURE__ */
492
492
  return jsx(View,{style:[styles.row,index>0?styles.rowDivider:null],children:/* @__PURE__ */jsxs(View,{style:styles.rowMain,children:[
493
493
  /* @__PURE__ */jsx(Text,{style:styles.rowTitle,children:encounter.type?humanize(encounter.type):DEPTH_COPY.visit}),detail?/* @__PURE__ */jsx(Text,{style:styles.rowDetail,children:detail}):null]})},encounter.encounterId)})})]}):null]}),
494
- /* @__PURE__ */jsx(DisclaimerBand,{disclaimer:record.disclaimer})]})}function heldCount(heldTotal,pending){return heldTotal>0?heldTotal:Object.values(pending).reduce((sum,count)=>sum+count,0)}function useLocalStyles4(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth;return StyleSheet.create({sections:{gap:space.lg+space.xs},vaccineGroup:{gap:space.xs+1,marginBottom:space.sm},vaccineYear:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:type.size.micro+space.xs,color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:space.xs+2},ask:{marginTop:space.lg},conflictCard:{borderRadius:radius.md,borderWidth:1,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(recordCardSlot(theme.slots),1)},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...slotText(recordCardSlot(theme.slots))},candidate:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,paddingTop:space.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:space.sm,paddingVertical:space.md},coveragePill:{borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs+1},coverageText:{...face(theme,"medium"),fontSize:type.size.caption,lineHeight:type.size.caption+space.xs-1},coverageRest:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},coverageRestText:{},coverageOnFile:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},metaRow:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingBottom:space.md},metaText:{flex:1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},pendingText:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,paddingBottom:space.md},identityLabel:{...face(theme,"medium"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},cardTitle:{paddingTop:space.sm},noteSection:{paddingVertical:space.md,gap:space.xs},noteLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,color:color.text.secondary,textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},noteBody:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.primary},noteBodyMuted:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.muted,fontStyle:"italic"}})}var CALL_CLINIC_COPY=/* @__PURE__ */Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:phone=>`Call the clinic at ${phone}`});function presentConsentText(consentText){return typeof consentText=="string"&&consentText.trim().length>0?consentText:null}function isConsentTextMissing(consentVersion,consentText){return typeof consentVersion=="string"&&consentVersion.length>0&&presentConsentText(consentText)===null}var CONSENT_TEXT_MISSING_WARNING="[everfur] consentVersion was passed without consentText, so the records consent gate shows no consent text above Allow. Pass the consent text your member agrees to as consentText, next to its consentVersion.",warned=false;function warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment3()===!0}catch{development=false}if(!development)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(CONSENT_TEXT_MISSING_WARNING)}catch{}}function useConsentTextWarning(consentVersion,consentText,isDevelopment3){useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=useState(false);return useEffect(()=>{let mounted=true,query=AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=useState(false);return useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var warnedRemoteFonts=/* @__PURE__ */new Set;function remoteFontFields(theme){let fields=[];return theme.type.fontSources.length>0&&fields.push("fontSources"),Object.values(theme.type.fontUrls).some(url=>typeof url=="string"&&url.length>0)&&fields.push("fontUrls"),fields}var REMOTE_FONT_LABEL=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function warnRemoteFonts(theme){if(!isDevelopment())return;let fresh=remoteFontFields(theme).filter(field=>!warnedRemoteFonts.has(field));if(fresh.length===0)return;for(let field of fresh)warnedRemoteFonts.add(field);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme sets ${fresh.map(field=>REMOTE_FONT_LABEL[field]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function useRnResolvedTheme(theme){useEffect(()=>{try{warnRemoteFonts(theme)}catch{}},[theme])}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,useResolvedTheme:useRnResolvedTheme,isDevelopment:isDevelopment});var isDevelopment2=()=>rnThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment2)}var MAX_MB=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Upload ${petNameOr(petName)}’s records`,screenTitle:"Upload a document",subtitle:petName=>`Already have lab results, a vet summary, or test reports? Add them here and we’ll read them and pull out ${petNameOr(petName)}’s health markers.`,noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${MAX_MB} MB each. You can pick several at once. We’ll read them and add the results to your records.`,chooseFiles:"Choose a file",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total}…`,cancel:"Cancel",cancelA11y:"Cancel these uploads",received:done=>`${done===1?"Record received.":`${done} records received.`} We’ll read and review ${done===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,retryFailed:failed=>`Retry ${failed} that didn’t upload`,haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:/* @__PURE__ */Object.freeze({start:"We couldn’t start that upload. Check your connection and try again.",startPlain:"We couldn’t start that upload. Please try again.",upload:"We couldn’t upload that record. Check your connection and try again."})}),UPLOAD_PHOTO_COPY=/* @__PURE__ */Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can’t read this kind of file. Upload a PDF or a photo of the record."});function uploadActionA11y(label,meta){return`${label} ${meta}`}var MAX_MB2=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_QUEUE_COPY=/* @__PURE__ */Object.freeze({queued:"Queued",verifying:"Verifying…",done:"Done",failed:"Failed",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total} records`,uploaded:(done,total)=>`${done} of ${total} records uploaded`});function uploadItemStatusLabel(item){let pct2=Math.round(item.progress*100);switch(item.status){case"done":return UPLOAD_QUEUE_COPY.done;case"failed":return UPLOAD_QUEUE_COPY.failed;case"uploading":return item.progress>=1?UPLOAD_QUEUE_COPY.verifying:`${pct2}%`;case"queued":return UPLOAD_QUEUE_COPY.queued;default:return null}}function skippedFilesMessage(skipped,photosLive=false){if(skipped.length===0)return null;let nameList=entries=>{let names=entries.map(e=>e.name??"");return names.length<=3?names.join(", "):`${names.slice(0,3).join(", ")} and ${names.length-3} more`},tooLarge=skipped.filter(s=>s.reason==="too_large"),unsupported=skipped.filter(s=>s.reason==="unsupported");if(photosLive){let lines=[];return unsupported.length>0&&lines.push(UPLOAD_PHOTO_COPY.unreadable),tooLarge.length>0&&lines.push(`Didn’t upload: ${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB.`),lines.join(" ")}let parts=[];return unsupported.length>0&&parts.push(`${nameList(unsupported)} ${unsupported.length>1?"are not PDFs":"is not a PDF"}`),tooLarge.length>0&&parts.push(`${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB`),`Didn’t upload: ${parts.join("; ")}. We can only read PDFs up to ${MAX_MB2} MB right now.`}function skippedOf(queue){let out=[];for(let item of queue)item.status==="skipped"&&item.skipReason!==null&&out.push({name:item.name,reason:item.skipReason});return out}var RECORDS_RECOVERY_COPY=/* @__PURE__ */Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We’ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function useRecordsRecovery({request:request,onRecovered:onRecovered,canUpload:canUpload=false},controller){let[email2,setEmailValue]=useState(""),[busy,setBusy]=useState(false),[error,setError]=useState(null),[confirmingRevoke,setConfirmingRevoke]=useState(false),[settled,setSettled]=useState(null),locked=useRef(false),active=useRef(false),generation=useRef(0);useEffect(()=>(active.current=true,()=>{active.current=false,generation.current+=1}),[controller]);let current=settled!==null&&settled.before===request.updatedAt?{...settled.value,canRetrySend:request.canRetrySend===true&&settled.value.canRetrySend===true,canUpdateClinicEmail:request.canUpdateClinicEmail===true&&settled.value.canUpdateClinicEmail===true,canRevoke:request.canRevoke===true&&settled.value.canRevoke===true,canConvertToUpload:request.canConvertToUpload===true&&settled.value.canConvertToUpload===true}:request,trimmed=email2.trim(),validEmail=trimmed.length<=320&&!Array.from(trimmed).some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed),hasEmailEdit=current.canUpdateClinicEmail===true&&trimmed.length>0,canRetry=current.canRetrySend===true&&!busy&&!hasEmailEdit,canUpdateEmail=current.canUpdateClinicEmail===true&&!busy&&validEmail,canConvert=current.canConvertToUpload===true&&canUpload,run=async kind=>{let allowed={retry:canRetry,email:canUpdateEmail,revoke:current.canRevoke===true&&confirmingRevoke,convert:canConvert};if(locked.current||!active.current||!allowed[kind])return;locked.current=true,setBusy(true),setError(null);let revision=generation.current,live=()=>active.current&&revision===generation.current;try{let result=kind==="retry"?await controller.retryRequest(request.id):kind==="email"?await controller.updateClinicEmail(request.id,trimmed):kind==="revoke"?await controller.revokeRequest(request.id):await controller.convertToUpload(request.id);if(!live())return;if(!result.ok){setError(result.error);return}if(result.value.id!==request.id||result.value.petRef!==request.petRef){setError(makeEverfurError("internalError"));return}setSettled({before:request.updatedAt,value:result.value}),setEmailValue(""),setConfirmingRevoke(!1),onRecovered()}catch{live()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,live()&&setBusy(false)}};return{request:current,email:email2,busy:busy,error:error,canRetry:canRetry,canUpdateEmail:canUpdateEmail,canConvert:canConvert,hasEmailEdit:hasEmailEdit,confirmingRevoke:confirmingRevoke&&current.canRevoke===true,emailInvalid:trimmed.length>0&&!validEmail,setEmail(value){locked.current||(setEmailValue(value),setError(null))},retry:()=>run("retry"),updateEmail:()=>run("email"),revoke:()=>run("revoke"),convert:()=>run("convert"),askRevoke(){!locked.current&&current.canRevoke===true&&setConfirmingRevoke(true)},keepRequest(){locked.current||setConfirmingRevoke(false)}}}var RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],OWNER_RAIL_STAGES=["requested","awaiting_upload","records_received","processing","ready"],CONVERTED_RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],REQUEST_TIMELINE_TITLES=/* @__PURE__ */Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),CLINIC_RAIL_TITLES=/* @__PURE__ */Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records…"}),CLINIC_RAIL_DETAILS=/* @__PURE__ */Object.freeze({notified:email2=>`A secure request went to ${email2}.`,received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:petName=>`Added to ${petName}’s records`}),DETAILS=/* @__PURE__ */Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn’t read this one automatically",manualReview:"Checking these by hand so nothing’s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),TERMINAL_DETAILS=/* @__PURE__ */Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),WIRE_FROM_STATUS=/* @__PURE__ */Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function wireStatusOf(request){return request.wireStatus??WIRE_FROM_STATUS[request.status]??"sent"}function reminderProgressLabel(status,reminderCount){return status!=="awaiting_response"||reminderCount<=0?null:`${reminderCount} ${reminderCount===1?"reminder":"reminders"} sent`}function reachedRailIndex(status){switch(status){case"submitted":case"sent":return 1;case"awaiting_response":return 2;case"records_received":return 3;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 4;case"published":return 5;default:return-1}}function deliveryDetail(request){switch(request.dispatchStatus){case"sent":return DETAILS.delivered;case"preparing":case"queued":case"sending":return DETAILS.emailing;case"failed":return DETAILS.bounced;default:return null}}function awaitingDetail(request,status){return reminderProgressLabel(status,request.reminderCount??0)??DETAILS.waiting}function isOwnerSourcedRequest(request){return request.source==="owner_provided"||!!request.convertedToUploadAt}function railDetail(key,request,status){let isOwnerSourced=isOwnerSourcedRequest(request);switch(key){case"sent_to_clinic":return deliveryDetail(request);case"awaiting_clinic":return awaitingDetail(request,status);case"awaiting_upload":return DETAILS.upload;case"records_received":return isOwnerSourced?DETAILS.ownerAdded:DETAILS.clinicSent;case"processing":return DETAILS.preparing;case"ready":return DETAILS.ready;default:return null}}function tookReviewBranch(request,status){return!!request.reviewStartedAt||status==="parsing_failed"||status==="review_email_failed"}function expandProcessingPhase(event,request,status){if(event.key!=="processing"||!tookReviewBranch(request,status))return[event];let atParsingFailed=status==="parsing_failed",published=status==="published",parsingFailedState=published?"done":atParsingFailed?"current":"done",reviewState=published?"done":atParsingFailed?"upcoming":"current";return[{key:"parsing_failed",title:REQUEST_TIMELINE_TITLES.parsing_failed,detail:DETAILS.parsingFailed,at:null,state:parsingFailedState},{key:"manual_review",title:REQUEST_TIMELINE_TITLES.manual_review,detail:DETAILS.manualReview,at:request.reviewStartedAt??null,state:reviewState}]}function convertedReachedIndex(status){switch(status){case"awaiting_upload":return 3;case"records_received":return 4;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 5;case"published":return 6;default:return 3}}function convertedClinicSwitchEvent(request){return{key:"awaiting_clinic",title:DETAILS.switchedTitle,detail:DETAILS.switched,at:request.convertedToUploadAt??null,state:"done"}}function ownerReachedIndex(status){switch(status){case"submitted":case"sent":return 0;case"awaiting_upload":return 1;case"records_received":return 2;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 3;case"published":return 4;default:return-1}}function railTimestamp(key,request,status){switch(key){case"requested":return request.createdAt||null;case"awaiting_clinic":return request.lastReminderAt??null;case"processing":return request.parsingStartedAt??request.reviewStartedAt??null;case"ready":return status==="published"&&request.updatedAt||null;default:return null}}function railEvent(key,request,status,state){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:railDetail(key,request,status),at:railTimestamp(key,request,status),state:state}}function terminalEvent(key,request){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:TERMINAL_DETAILS[key]??null,at:request.updatedAt||null,state:"failed"}}function walkRail(stages,reached,request,status,replace){return stages.map((key,idx)=>{let replaced=replace?.(key)??null;if(replaced!==null)return replaced;let state=status==="published"||idx<reached?"done":idx===reached?"current":"upcoming";return railEvent(key,request,status,state)}).flatMap(event=>expandProcessingPhase(event,request,status))}function buildRequestTimeline(request,options={}){return inArtifactWords(buildRailEvents(request),request,options.petName??null,options.sandbox===true)}function inArtifactWords(events,request,petName,sandbox){let clinicRail=request.source!=="owner_provided"&&!events.some(event=>event.key==="delivery_failed"),email2=request.clinicEmail?.trim()??"";return events.map(event=>{if(event.title!==REQUEST_TIMELINE_TITLES[event.key])return event;if(event.key==="ready")return{...event,title:CLINIC_RAIL_DETAILS.added(petNameOr(petName))};if(!clinicRail)return event;if(sandbox&&event.key==="sent_to_clinic")return{...event,title:RECORDS_SANDBOX_COPY.clinicNotContacted,detail:email2.length>0?RECORDS_SANDBOX_COPY.notEmailed(email2):null};let title=CLINIC_RAIL_TITLES[event.key]??event.title;return event.key==="sent_to_clinic"&&request.dispatchStatus==="sent"&&email2.length>0?{...event,title:title,detail:CLINIC_RAIL_DETAILS.notified(email2)}:event.key==="records_received"&&!isOwnerSourcedRequest(request)?{...event,title:title,detail:CLINIC_RAIL_DETAILS.received}:{...event,title:title}})}function buildRailEvents(request){let status=wireStatusOf(request),done=key=>railEvent(key,request,status,"done");if(status==="revoked")return[done("requested"),terminalEvent("revoked",request)];if(request.convertedToUploadAt)return status==="failed"?[done("requested"),done("sent_to_clinic"),convertedClinicSwitchEvent(request),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)]:walkRail(CONVERTED_RAIL_STAGES,convertedReachedIndex(status),request,status,key=>key==="awaiting_clinic"?convertedClinicSwitchEvent(request):null);if(request.source==="owner_provided"){if(status==="failed"||status==="clinic_declined")return[done("requested"),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)];let reached2=ownerReachedIndex(status);return walkRail(OWNER_RAIL_STAGES,reached2<0?1:reached2,request,status)}if(status==="clinic_declined")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_declined",request)];if(status==="clinic_responded_no_records")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_no_records",request)];if(status==="failed"){let code=request.failureCode??null;return code==="no_response"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("no_response",request)]:code==="hard_bounce"||code==="dispatch_failed"?[done("requested"),terminalEvent("delivery_failed",request)]:code==="parse_timeout"||code==="parse_error"||request.dispatchStatus==="sent"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),done("records_received"),terminalEvent("processing_failed",request)]:[done("requested"),terminalEvent("delivery_failed",request)]}let reached=reachedRailIndex(status);return walkRail(RAIL_STAGES,reached<0?1:reached,request,status)}var A11Y_STATE=/* @__PURE__ */Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),DOT_SIZE=28,NOW="Now",DOT_CORE_SIZE=10;function RequestTimeline({request:request,petName:petName}){let styles=useStyles8(),sandbox=useRecordsSandboxTenant(),events=buildRequestTimeline(request,{petName:petName??null,sandbox:sandbox});/* @__PURE__ */
494
+ /* @__PURE__ */jsx(DisclaimerBand,{disclaimer:record.disclaimer})]})}function heldCount(heldTotal,pending){return heldTotal>0?heldTotal:Object.values(pending).reduce((sum,count)=>sum+count,0)}function useLocalStyles4(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth;return StyleSheet.create({sections:{gap:space.lg+space.xs},vaccineGroup:{gap:space.xs+1,marginBottom:space.sm},vaccineYear:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:type.size.micro+space.xs,color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:space.xs+2},ask:{marginTop:space.lg},conflictCard:{borderRadius:radius.md,borderWidth:1,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(recordCardSlot(theme.slots),1)},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...slotText(recordCardSlot(theme.slots))},candidate:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,paddingTop:space.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:space.sm,paddingVertical:space.md},coveragePill:{borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs+1},coverageText:{...face(theme,"medium"),fontSize:type.size.caption,lineHeight:type.size.caption+space.xs-1},coverageRest:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},coverageRestText:{},coverageOnFile:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},metaRow:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingBottom:space.md},metaText:{flex:1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},pendingText:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,paddingBottom:space.md},identityLabel:{...face(theme,"medium"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},cardTitle:{paddingTop:space.sm},noteSection:{paddingVertical:space.md,gap:space.xs},noteLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,color:color.text.secondary,textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},noteBody:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.primary},noteBodyMuted:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.muted,fontStyle:"italic"}})}var CALL_CLINIC_COPY=/* @__PURE__ */Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:phone=>`Call the clinic at ${phone}`});function presentConsentText(consentText){return typeof consentText=="string"&&consentText.trim().length>0?consentText:null}function isConsentTextMissing(consentVersion,consentText){return typeof consentVersion=="string"&&consentVersion.length>0&&presentConsentText(consentText)===null}var CONSENT_TEXT_MISSING_WARNING="[everfur] consentVersion was passed without consentText, so the records consent gate shows no consent text above Allow. Pass the consent text your member agrees to as consentText, next to its consentVersion.",warned=false;function warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment3()===!0}catch{development=false}if(!development)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(CONSENT_TEXT_MISSING_WARNING)}catch{}}function useConsentTextWarning(consentVersion,consentText,isDevelopment3){useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=useState(false);return useEffect(()=>{let mounted=true,query=AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=useState(false);return useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var warnedRemoteFonts=/* @__PURE__ */new Set;function remoteFontFields(theme){let fields=[];return theme.type.fontSources.length>0&&fields.push("fontSources"),Object.values(theme.type.fontUrls).some(url=>typeof url=="string"&&url.length>0)&&fields.push("fontUrls"),fields}var REMOTE_FONT_LABEL=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function warnRemoteFonts(theme){if(!isDevelopment())return;let fresh=remoteFontFields(theme).filter(field=>!warnedRemoteFonts.has(field));if(fresh.length===0)return;for(let field of fresh)warnedRemoteFonts.add(field);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme sets ${fresh.map(field=>REMOTE_FONT_LABEL[field]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function useRnResolvedTheme(theme){useEffect(()=>{try{warnRemoteFonts(theme)}catch{}},[theme])}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,useResolvedTheme:useRnResolvedTheme,isDevelopment:isDevelopment});var isDevelopment2=()=>rnThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment2)}var MAX_MB=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Upload ${petNameOr(petName)}’s records`,screenTitle:"Upload a document",subtitle:petName=>`Already have lab results, a vet summary, or test reports? Add them here and we’ll read them and pull out ${petNameOr(petName)}’s health markers.`,noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${MAX_MB} MB each. You can pick several at once. We’ll read them and add the results to your records.`,chooseFiles:"Choose a file",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total}…`,cancel:"Cancel",cancelA11y:"Cancel these uploads",received:done=>`${done===1?"Record received.":`${done} records received.`} We’ll read and review ${done===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,retryFailed:failed=>`Retry ${failed} that didn’t upload`,haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:/* @__PURE__ */Object.freeze({start:"We couldn’t start that upload. Check your connection and try again.",startPlain:"We couldn’t start that upload. Please try again.",upload:"We couldn’t upload that record. Check your connection and try again."})}),UPLOAD_PHOTO_COPY=/* @__PURE__ */Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can’t read this kind of file. Upload a PDF or a photo of the record."});function uploadActionA11y(label,meta){return`${label} ${meta}`}var MAX_MB2=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_QUEUE_COPY=/* @__PURE__ */Object.freeze({queued:"Queued",verifying:"Verifying…",done:"Done",failed:"Failed",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total} records`,uploaded:(done,total)=>`${done} of ${total} records uploaded`});function uploadItemStatusLabel(item){let pct2=Math.round(item.progress*100);switch(item.status){case"done":return UPLOAD_QUEUE_COPY.done;case"failed":return UPLOAD_QUEUE_COPY.failed;case"uploading":return item.progress>=1?UPLOAD_QUEUE_COPY.verifying:`${pct2}%`;case"queued":return UPLOAD_QUEUE_COPY.queued;default:return null}}function skippedFilesMessage(skipped,photosLive=false){if(skipped.length===0)return null;let nameList=entries=>{let names=entries.map(e=>e.name??"");return names.length<=3?names.join(", "):`${names.slice(0,3).join(", ")} and ${names.length-3} more`},tooLarge=skipped.filter(s=>s.reason==="too_large"),unsupported=skipped.filter(s=>s.reason==="unsupported");if(photosLive){let lines=[];return unsupported.length>0&&lines.push(UPLOAD_PHOTO_COPY.unreadable),tooLarge.length>0&&lines.push(`Didn’t upload: ${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB.`),lines.join(" ")}let parts=[];return unsupported.length>0&&parts.push(`${nameList(unsupported)} ${unsupported.length>1?"are not PDFs":"is not a PDF"}`),tooLarge.length>0&&parts.push(`${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB`),`Didn’t upload: ${parts.join("; ")}. We can only read PDFs up to ${MAX_MB2} MB right now.`}function skippedOf(queue){let out=[];for(let item of queue)item.status==="skipped"&&item.skipReason!==null&&out.push({name:item.name,reason:item.skipReason});return out}var RECORDS_RECOVERY_COPY=/* @__PURE__ */Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We’ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function useRecordsRecovery({request:request,onRecovered:onRecovered,canUpload:canUpload=false},controller){let[email2,setEmailValue]=useState(""),[busy,setBusy]=useState(false),[error,setError]=useState(null),[confirmingRevoke,setConfirmingRevoke]=useState(false),[settled,setSettled]=useState(null),locked=useRef(false),active=useRef(false),generation=useRef(0);useEffect(()=>(active.current=true,()=>{active.current=false,generation.current+=1}),[controller]);let current=settled!==null&&settled.before===request.updatedAt?{...settled.value,canRetrySend:request.canRetrySend===true&&settled.value.canRetrySend===true,canUpdateClinicEmail:request.canUpdateClinicEmail===true&&settled.value.canUpdateClinicEmail===true,canRevoke:request.canRevoke===true&&settled.value.canRevoke===true,canConvertToUpload:request.canConvertToUpload===true&&settled.value.canConvertToUpload===true}:request,trimmed=email2.trim(),validEmail=trimmed.length<=320&&!Array.from(trimmed).some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed),hasEmailEdit=current.canUpdateClinicEmail===true&&trimmed.length>0,canRetry=current.canRetrySend===true&&!busy&&!hasEmailEdit,canUpdateEmail=current.canUpdateClinicEmail===true&&!busy&&validEmail,canConvert=current.canConvertToUpload===true&&canUpload,run=async kind=>{let allowed={retry:canRetry,email:canUpdateEmail,revoke:current.canRevoke===true&&confirmingRevoke,convert:canConvert};if(locked.current||!active.current||!allowed[kind])return;locked.current=true,setBusy(true),setError(null);let revision=generation.current,live=()=>active.current&&revision===generation.current;try{let result=kind==="retry"?await controller.retryRequest(request.id):kind==="email"?await controller.updateClinicEmail(request.id,trimmed):kind==="revoke"?await controller.revokeRequest(request.id):await controller.convertToUpload(request.id);if(!live())return;if(!result.ok){setError(result.error);return}if(result.value.id!==request.id||result.value.petRef!==request.petRef){setError(makeEverfurError("internalError"));return}setSettled({before:request.updatedAt,value:result.value}),setEmailValue(""),setConfirmingRevoke(!1),onRecovered()}catch{live()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,live()&&setBusy(false)}};return{request:current,email:email2,busy:busy,error:error,canRetry:canRetry,canUpdateEmail:canUpdateEmail,canConvert:canConvert,hasEmailEdit:hasEmailEdit,confirmingRevoke:confirmingRevoke&&current.canRevoke===true,emailInvalid:trimmed.length>0&&!validEmail,setEmail(value){locked.current||(setEmailValue(value),setError(null))},retry:()=>run("retry"),updateEmail:()=>run("email"),revoke:()=>run("revoke"),convert:()=>run("convert"),askRevoke(){!locked.current&&current.canRevoke===true&&setConfirmingRevoke(true)},keepRequest(){locked.current||setConfirmingRevoke(false)}}}var RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],OWNER_RAIL_STAGES=["requested","awaiting_upload","records_received","processing","ready"],CONVERTED_RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],REQUEST_TIMELINE_TITLES=/* @__PURE__ */Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),CLINIC_RAIL_TITLES=/* @__PURE__ */Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records…"}),CLINIC_RAIL_DETAILS=/* @__PURE__ */Object.freeze({notified:email2=>`A secure request went to ${email2}.`,received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:petName=>`Added to ${petName}’s records`}),DETAILS=/* @__PURE__ */Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn’t read this one automatically",manualReview:"Checking these by hand so nothing’s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),TERMINAL_DETAILS=/* @__PURE__ */Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),WIRE_FROM_STATUS=/* @__PURE__ */Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function wireStatusOf(request){return request.wireStatus??WIRE_FROM_STATUS[request.status]??"sent"}function reminderProgressLabel(status,reminderCount){return status!=="awaiting_response"||reminderCount<=0?null:`${reminderCount} ${reminderCount===1?"reminder":"reminders"} sent`}function reachedRailIndex(status){switch(status){case"submitted":case"sent":return 1;case"awaiting_response":return 2;case"records_received":return 3;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 4;case"published":return 5;default:return-1}}function deliveryDetail(request){switch(request.dispatchStatus){case"sent":return DETAILS.delivered;case"preparing":case"queued":case"sending":return DETAILS.emailing;case"failed":return DETAILS.bounced;default:return null}}function awaitingDetail(request,status){return reminderProgressLabel(status,request.reminderCount??0)??DETAILS.waiting}function isOwnerSourcedRequest(request){return request.source==="owner_provided"||!!request.convertedToUploadAt}function railDetail(key,request,status){let isOwnerSourced=isOwnerSourcedRequest(request);switch(key){case"sent_to_clinic":return deliveryDetail(request);case"awaiting_clinic":return awaitingDetail(request,status);case"awaiting_upload":return DETAILS.upload;case"records_received":return isOwnerSourced?DETAILS.ownerAdded:DETAILS.clinicSent;case"processing":return DETAILS.preparing;case"ready":return DETAILS.ready;default:return null}}function tookReviewBranch(request,status){return!!request.reviewStartedAt||status==="parsing_failed"||status==="review_email_failed"}function expandProcessingPhase(event,request,status){if(event.key!=="processing"||!tookReviewBranch(request,status))return[event];let atParsingFailed=status==="parsing_failed",published=status==="published",parsingFailedState=published?"done":atParsingFailed?"current":"done",reviewState=published?"done":atParsingFailed?"upcoming":"current";return[{key:"parsing_failed",title:REQUEST_TIMELINE_TITLES.parsing_failed,detail:DETAILS.parsingFailed,at:null,state:parsingFailedState},{key:"manual_review",title:REQUEST_TIMELINE_TITLES.manual_review,detail:DETAILS.manualReview,at:request.reviewStartedAt??null,state:reviewState}]}function convertedReachedIndex(status){switch(status){case"awaiting_upload":return 3;case"records_received":return 4;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 5;case"published":return 6;default:return 3}}function convertedClinicSwitchEvent(request){return{key:"awaiting_clinic",title:DETAILS.switchedTitle,detail:DETAILS.switched,at:request.convertedToUploadAt??null,state:"done"}}function ownerReachedIndex(status){switch(status){case"submitted":case"sent":return 0;case"awaiting_upload":return 1;case"records_received":return 2;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 3;case"published":return 4;default:return-1}}function railTimestamp(key,request,status){switch(key){case"requested":return request.createdAt||null;case"awaiting_clinic":return request.lastReminderAt??null;case"processing":return request.parsingStartedAt??request.reviewStartedAt??null;case"ready":return status==="published"&&request.updatedAt||null;default:return null}}function railEvent(key,request,status,state){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:railDetail(key,request,status),at:railTimestamp(key,request,status),state:state}}function terminalEvent(key,request){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:TERMINAL_DETAILS[key]??null,at:request.updatedAt||null,state:"failed"}}function walkRail(stages,reached,request,status,replace){return stages.map((key,idx)=>{let replaced=replace?.(key)??null;if(replaced!==null)return replaced;let state=status==="published"||idx<reached?"done":idx===reached?"current":"upcoming";return railEvent(key,request,status,state)}).flatMap(event=>expandProcessingPhase(event,request,status))}function buildRequestTimeline(request,options={}){return inArtifactWords(buildRailEvents(request),request,options.petName??null,options.sandbox===true)}function buildRequestRail(request){return buildRailEvents(request)}function inArtifactWords(events,request,petName,sandbox){let clinicRail=request.source!=="owner_provided"&&!events.some(event=>event.key==="delivery_failed"),email2=request.clinicEmail?.trim()??"";return events.map(event=>{if(event.title!==REQUEST_TIMELINE_TITLES[event.key])return event;if(event.key==="ready")return{...event,title:CLINIC_RAIL_DETAILS.added(petNameOr(petName))};if(!clinicRail)return event;if(sandbox&&event.key==="sent_to_clinic")return{...event,title:RECORDS_SANDBOX_COPY.clinicNotContacted,detail:email2.length>0?RECORDS_SANDBOX_COPY.notEmailed(email2):null};let title=CLINIC_RAIL_TITLES[event.key]??event.title;return event.key==="sent_to_clinic"&&request.dispatchStatus==="sent"&&email2.length>0?{...event,title:title,detail:CLINIC_RAIL_DETAILS.notified(email2)}:event.key==="records_received"&&!isOwnerSourcedRequest(request)?{...event,title:title,detail:CLINIC_RAIL_DETAILS.received}:{...event,title:title}})}function buildRailEvents(request){let status=wireStatusOf(request),done=key=>railEvent(key,request,status,"done");if(status==="revoked")return[done("requested"),terminalEvent("revoked",request)];if(request.convertedToUploadAt)return status==="failed"?[done("requested"),done("sent_to_clinic"),convertedClinicSwitchEvent(request),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)]:walkRail(CONVERTED_RAIL_STAGES,convertedReachedIndex(status),request,status,key=>key==="awaiting_clinic"?convertedClinicSwitchEvent(request):null);if(request.source==="owner_provided"){if(status==="failed"||status==="clinic_declined")return[done("requested"),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)];let reached2=ownerReachedIndex(status);return walkRail(OWNER_RAIL_STAGES,reached2<0?1:reached2,request,status)}if(status==="clinic_declined")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_declined",request)];if(status==="clinic_responded_no_records")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_no_records",request)];if(status==="failed"){let code=request.failureCode??null;return code==="no_response"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("no_response",request)]:code==="hard_bounce"||code==="dispatch_failed"?[done("requested"),terminalEvent("delivery_failed",request)]:code==="parse_timeout"||code==="parse_error"||request.dispatchStatus==="sent"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),done("records_received"),terminalEvent("processing_failed",request)]:[done("requested"),terminalEvent("delivery_failed",request)]}let reached=reachedRailIndex(status);return walkRail(RAIL_STAGES,reached<0?1:reached,request,status)}var A11Y_STATE=/* @__PURE__ */Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),DOT_SIZE=28,NOW="Now",DOT_CORE_SIZE=10;function RequestTimeline({request:request,petName:petName}){let styles=useStyles8(),sandbox=useRecordsSandboxTenant(),events=buildRequestTimeline(request,{petName:petName??null,sandbox:sandbox});/* @__PURE__ */
495
495
  return jsx(View,{style:styles.container,accessibilityRole:"summary",children:events.map((event,idx)=>/* @__PURE__ */jsx(TimelineRow,{event:event,isLast:idx===events.length-1,styles:styles},event.key))})}function TimelineRow({event:event,isLast:isLast,styles:styles}){let date2=event.at?formatRecordsInstant(event.at):null,a11yParts=[event.title,event.detail,date2,A11Y_STATE[event.state]].filter(Boolean);/* @__PURE__ */
496
496
  return jsxs(View,{style:styles.row,accessible:true,accessibilityRole:"text",accessibilityLabel:a11yParts.join(", "),testID:`records-timeline-${event.key}`,children:[
497
497
  /* @__PURE__ */jsxs(View,{style:styles.railColumn,children:[
@@ -579,7 +579,7 @@ return jsxs(View,{style:local.inProgressCard,testID:"dashboard-in-progress-card"
579
579
  return jsxs(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??(sub?`${title}. ${sub}`:title),style:({pressed:pressed})=>[local.way,dashed?local.wayDashed:null,pressed&&!still?{transform:[{scale:RECORDS_MOTION.pressScale}]}:null],testID:testID,children:[
580
580
  /* @__PURE__ */jsxs(View,{style:local.wayText,children:[
581
581
  /* @__PURE__ */jsx(Text,{style:local.wayTitle,children:title}),sub?/* @__PURE__ */jsx(Text,{style:local.waySub,children:sub}):null]}),
582
- /* @__PURE__ */jsx(Chevron,{})]})}function useLocalStyles6(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles6(theme),[theme])}function makeLocalStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,touch=space.xxl+space.md,card=theme.slots.card,cardText=slotText(card);return StyleSheet.create({headerButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},actions:{gap:space.sm+space.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.lg,...slotBox(card,1)},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:space.md},actionIcon:{width:ACTION_GLYPH_SIZE,height:ACTION_GLYPH_SIZE,alignItems:"center",justifyContent:"center"},actionLabel:{flex:1,...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...cardText},inProgressCard:{borderRadius:radius.lg,backgroundColor:color.surface,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.lg,...slotBox(card,1)},inProgressHeadText:{flex:1,gap:space.xs/2},ways:{gap:space.sm},way:{flexDirection:"row",alignItems:"center",gap:space.md,borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,...slotBox(card,1)},wayDashed:{borderStyle:"dashed",borderColor:color.brandBorderStrong},wayText:{flex:1,gap:space.xs/2},wayTitle:{...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...cardText},waySub:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,...cardText},inProgressInner:{gap:space.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},inProgressTitle:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:-.4,color:color.brandInk,...cardText},promptCard:{borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderRingCream,paddingHorizontal:space.lg+space.xs,paddingVertical:space.lg+space.xs/2,...slotBox(card,hairline)},promptHeader:{flexDirection:"row",alignItems:"center",gap:space.xs+1},promptGlyph:{width:space.xl+1,height:space.xl+1,borderRadius:radius.xs,borderWidth:2,borderColor:color.warningStrong},promptTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:type.letterSpacing.headerBrand,color:color.brandInk,...cardText},promptBody:{marginTop:space.sm-1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:space.lg+space.xs,color:color.text.primary,...cardText},promptCta:{marginTop:space.sm-1,minHeight:space.xxl+space.sm},promptCtaSecondary:{marginTop:space.sm,minHeight:space.xxl+space.sm},addActions:{gap:space.sm},addCta:{minHeight:space.xxl+space.sm}})}var KIND_ORDER=/* @__PURE__ */Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function toMillis2(iso){if(!iso)return null;let ms=Date.parse(iso);return Number.isNaN(ms)?null:ms}function buildTimelineRows(timeline){let rows=[...timeline.visits.map((visit,index)=>({key:`visit-${index}-${visit.visitId}`,kind:"visit",kindLabel:DEPTH_COPY.kind.visit,at:visit.visitDate,date:formatRecordsDate(visit.visitDate),title:visit.summary??DEPTH_COPY.clinicVisit,detail:visit.veterinarian?DEPTH_COPY.doctor(visit.veterinarian):null,docId:visit.docId})),...timeline.vaccines.map((vaccine,index)=>{let parts=[];return vaccine.lot&&parts.push(DEPTH_COPY.lot(vaccine.lot)),vaccine.expiresOn&&parts.push(DEPTH_COPY.expires(formatRecordsDate(vaccine.expiresOn))),{key:`vaccine-${index}-${vaccine.vaccineId}`,kind:"vaccine",kindLabel:DEPTH_COPY.kind.vaccine,at:vaccine.administeredOn,date:formatRecordsDate(vaccine.administeredOn),title:vaccine.product||DEPTH_COPY.kind.vaccine,detail:parts.length?parts.join(" · "):null,docId:vaccine.docId}}),...timeline.weights.map((weight,index)=>({key:`weight-${index}-${weight.weightId}`,kind:"weight",kindLabel:DEPTH_COPY.kind.weight,at:weight.observedOn,date:formatRecordsDate(weight.observedOn),title:formatWeightKg(weight.weightKg),detail:null,docId:weight.docId})),...timeline.medications.map((medication,index)=>{let parts=[medication.dose,medication.route,medication.frequency].filter(p=>!!p);return{key:`medication-${index}-${medication.medicationId}`,kind:"medication",kindLabel:DEPTH_COPY.kind.medication,at:medication.startedOn,date:formatRecordsDate(medication.startedOn),title:medication.drugName||DEPTH_COPY.kind.medication,detail:parts.length?parts.join(" · "):null,docId:medication.docId}})];/* @__PURE__ */
582
+ /* @__PURE__ */jsx(Chevron,{})]})}function useLocalStyles6(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles6(theme),[theme])}function makeLocalStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,touch=space.xxl+space.md,card=theme.slots.card,cardText=slotText(card);return StyleSheet.create({headerButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},actions:{gap:space.sm+space.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.lg,...slotBox(card,1)},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:space.md},actionIcon:{width:ACTION_GLYPH_SIZE,height:ACTION_GLYPH_SIZE,alignItems:"center",justifyContent:"center"},actionLabel:{flex:1,...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...cardText},inProgressCard:{borderRadius:radius.lg,backgroundColor:color.surface,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.lg,...slotBox(card,1)},inProgressHeadText:{flex:1,gap:space.xs/2},ways:{gap:space.sm},way:{flexDirection:"row",alignItems:"center",gap:space.md,borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,...slotBox(card,1)},wayDashed:{borderStyle:"dashed",borderColor:color.brandBorderStrong},wayText:{flex:1,gap:space.xs/2},wayTitle:{...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...cardText},waySub:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,...cardText},inProgressInner:{gap:space.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},inProgressTitle:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:-.4,color:color.brandInk,...cardText},promptCard:{borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderRingCream,paddingHorizontal:space.lg+space.xs,paddingVertical:space.lg+space.xs/2,...slotBox(card,hairline)},promptHeader:{flexDirection:"row",alignItems:"center",gap:space.xs+1},promptGlyph:{width:space.xl+1,height:space.xl+1,borderRadius:radius.xs,borderWidth:2,borderColor:color.warningStrong},promptTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:type.letterSpacing.headerBrand,color:color.brandInk,...cardText},promptBody:{marginTop:space.sm-1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:space.lg+space.xs,color:color.text.primary,...cardText},promptCta:{marginTop:space.sm-1,minHeight:space.xxl+space.sm},promptCtaSecondary:{marginTop:space.sm,minHeight:space.xxl+space.sm},addActions:{gap:space.sm},addCta:{minHeight:space.xxl+space.sm}})}var KIND_ORDER=/* @__PURE__ */Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function toMillis2(iso){if(!iso)return null;let ms2=Date.parse(iso);return Number.isNaN(ms2)?null:ms2}function buildTimelineRows(timeline){let rows=[...timeline.visits.map((visit,index)=>({key:`visit-${index}-${visit.visitId}`,kind:"visit",kindLabel:DEPTH_COPY.kind.visit,at:visit.visitDate,date:formatRecordsDate(visit.visitDate),title:visit.summary??DEPTH_COPY.clinicVisit,detail:visit.veterinarian?DEPTH_COPY.doctor(visit.veterinarian):null,docId:visit.docId})),...timeline.vaccines.map((vaccine,index)=>{let parts=[];return vaccine.lot&&parts.push(DEPTH_COPY.lot(vaccine.lot)),vaccine.expiresOn&&parts.push(DEPTH_COPY.expires(formatRecordsDate(vaccine.expiresOn))),{key:`vaccine-${index}-${vaccine.vaccineId}`,kind:"vaccine",kindLabel:DEPTH_COPY.kind.vaccine,at:vaccine.administeredOn,date:formatRecordsDate(vaccine.administeredOn),title:vaccine.product||DEPTH_COPY.kind.vaccine,detail:parts.length?parts.join(" · "):null,docId:vaccine.docId}}),...timeline.weights.map((weight,index)=>({key:`weight-${index}-${weight.weightId}`,kind:"weight",kindLabel:DEPTH_COPY.kind.weight,at:weight.observedOn,date:formatRecordsDate(weight.observedOn),title:formatWeightKg(weight.weightKg),detail:null,docId:weight.docId})),...timeline.medications.map((medication,index)=>{let parts=[medication.dose,medication.route,medication.frequency].filter(p=>!!p);return{key:`medication-${index}-${medication.medicationId}`,kind:"medication",kindLabel:DEPTH_COPY.kind.medication,at:medication.startedOn,date:formatRecordsDate(medication.startedOn),title:medication.drugName||DEPTH_COPY.kind.medication,detail:parts.length?parts.join(" · "):null,docId:medication.docId}})];/* @__PURE__ */
583
583
  return Object.freeze(rows.sort((a,b)=>{let am=toMillis2(a.at),bm=toMillis2(b.at);return am===null&&bm===null?KIND_ORDER[a.kind]-KIND_ORDER[b.kind]:am===null?1:bm===null?-1:bm!==am?bm-am:KIND_ORDER[a.kind]-KIND_ORDER[b.kind]}))}var SPINNER_DELAY_MS=300,readTimeline=(client,petRef)=>client.getTimeline(petRef),timelineEmpty=value=>value.isEmpty;var contributionsEmpty=value=>value.contributions.length===0;function EverfurRecordsTimeline({petRef:petRef,style:style,onBack:onBack}){let state=useRecordsDepthRead(petRef,readTimeline,timelineEmpty);/* @__PURE__ */
584
584
  return jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsx(ScreenHeader,{title:DEPTH_COPY.timeline,onBack:guardHost(onBack),testID:"timeline-header"}),loading:/* @__PURE__ */jsx(TimelineSkeleton,{testID:"timeline-loading"}),empty:/* @__PURE__ */jsx(RecordsEmptyState,{variant:"no_records",testID:"timeline-empty"}),render:timeline=>/* @__PURE__ */jsx(TimelineBody,{timeline:timeline})})}function EverfurDocumentContributions({petRef:petRef,docId:docId,style:style,onBack:onBack}){let read=useCallback((client,pet)=>client.getDocumentContributions(pet,docId),[docId]),state=useRecordsDepthRead(petRef,read,contributionsEmpty,docId),shown=state.value?.document??null,title=shown!==null?documentTitle(shown):DEPTH_COPY.uploadedDocument;/* @__PURE__ */
585
585
  return jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsx(ScreenHeader,{title:title,onBack:guardHost(onBack),testID:"contributions-header"}),empty:/* @__PURE__ */jsx(RecordsEmptyState,{variant:"no_records",testID:"contributions-empty"}),render:view=>/* @__PURE__ */jsx(ContributionsBody,{view:view})})}function DepthSurface({state:state,style:style,header:header,loading:loading,empty:empty,render:render,onBack:onBack}){let styles=useStyles10();/* @__PURE__ */
@@ -685,7 +685,7 @@ return jsxs(View,{style:[styles.root,style],children:[
685
685
  /* @__PURE__ */jsx(Text,{style:local.title,accessibilityRole:"header",children:UPLOAD_COPY.screenTitle}),
686
686
  /* @__PURE__ */jsx(Text,{style:local.subtitle,children:UPLOAD_COPY.subtitle(petName)})]}),
687
687
  /* @__PURE__ */jsx(UploadRecordCard,{records:records,requestId:null,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onNavigate?requestId2=>onNavigate({name:"request",requestId:requestId2}):void 0})]}),
688
- /* @__PURE__ */jsx(RecordsFootnote,{})]})}function UploadRecordCard({records:records,requestId:requestId2,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onDone}){let styles=useScreenStyles(),local=useLocalStyles9(),{runtime:runtime}=useEverfurContext(),camera=runtime.registry.services.camera,types=records.uploadContentTypes,photosLive=acceptsPhotos(types),canTakePhoto=photosLive&&isCaptureAvailable(camera),canChoosePhotos=photosLive&&onPickPhotos!==void 0,photoCopy=canTakePhoto||canChoosePhotos,[pickError,setPickError]=useState(null),[batchCount,setBatchCount]=useState(0),resolvedId=useRef(requestId2),failedFiles=useRef([]),rows=records.uploadQueue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,failed=rows.filter(item=>item.status==="failed").length,settled=!records.isUploading&&batchCount>0,run=useCallback(async picked=>{let{uploadable:uploadable,skipped:skipped}=classifyPick(picked,types),refusal=skippedFilesMessage(skipped,photoCopy);if(uploadable.length===0){refusal!==null&&setPickError(refusal);return}setPickError(refusal);let target=resolvedId.current;if(target===null){let created=await records.createRequest(`records-upload-${Date.now().toString(36)}`);if(!created.ok){setPickError(UPLOAD_COPY.errors.start);return}target=created.value.id,resolvedId.current=target}setBatchCount(n=>n+1);let outcome=await records.uploadDocuments(target,uploadable);failedFiles.current=outcome.flatMap((item,index)=>item.status==="failed"&&uploadable[index]!==void 0?[uploadable[index]]:[])},[records,types,photoCopy]),pickFrom=useCallback(picker=>{!picker||!canUpload||callHostAsync(picker).then(outcome=>{if(!outcome.ok){setPickError(UPLOAD_COPY.errors.startPlain);return}let picked=outcome.value;picked!==null&&run(Array.isArray(picked)?picked:[picked])})},[canUpload,run]),pick2=useCallback(()=>{pickFrom(onPickDocument)},[pickFrom,onPickDocument]),pickPhotos=useCallback(()=>{pickFrom(onPickPhotos)},[pickFrom,onPickPhotos]),takePhoto=useCallback(()=>{!canTakePhoto||!canUpload||callHostAsync(()=>camera.capture(captureOptionsFor("photo"))).then(outcome=>{if(!outcome.ok)return;let handle=fileHandleFromMedia(outcome.value);if(handle.sizeBytes===void 0){setPickError(UPLOAD_COPY.errors.startPlain);return}run([handle])})},[camera,canTakePhoto,canUpload,run]),retryFailed=useCallback(()=>{run(failedFiles.current)},[run]);/* @__PURE__ */
688
+ /* @__PURE__ */jsx(RecordsFootnote,{})]})}function UploadRecordCard({records:records,requestId:requestId2,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onDone}){let styles=useScreenStyles(),local=useLocalStyles9(),{runtime:runtime}=useEverfurContext(),camera=runtime.registry.services.camera,types=records.uploadContentTypes,photosLive=acceptsPhotos(types),canTakePhoto=photosLive&&isCaptureAvailable(camera),canChoosePhotos=photosLive&&onPickPhotos!==void 0,photoCopy=canTakePhoto||canChoosePhotos,[pickError,setPickError]=useState(null),[batchCount,setBatchCount]=useState(0),resolvedId=useRef(requestId2),failedFiles=useRef([]),rows=records.uploadQueue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,failed=rows.filter(item=>item.status==="failed").length,settled=!records.isUploading&&batchCount>0,run=useCallback(async picked=>{let{uploadable:uploadable,skipped:skipped}=classifyPick(picked,types),refusal=skippedFilesMessage(skipped,photoCopy);if(uploadable.length===0){refusal!==null&&setPickError(refusal);return}setPickError(refusal);let target=resolvedId.current;if(target===null){let created=await records.createRequest(`records-upload-${Date.now().toString(36)}`);if(!created.ok){setPickError(UPLOAD_COPY.errors.start);return}target=created.value.id,resolvedId.current=target}setBatchCount(n2=>n2+1);let outcome=await records.uploadDocuments(target,uploadable);failedFiles.current=outcome.flatMap((item,index)=>item.status==="failed"&&uploadable[index]!==void 0?[uploadable[index]]:[])},[records,types,photoCopy]),pickFrom=useCallback(picker=>{!picker||!canUpload||callHostAsync(picker).then(outcome=>{if(!outcome.ok){setPickError(UPLOAD_COPY.errors.startPlain);return}let picked=outcome.value;picked!==null&&run(Array.isArray(picked)?picked:[picked])})},[canUpload,run]),pick2=useCallback(()=>{pickFrom(onPickDocument)},[pickFrom,onPickDocument]),pickPhotos=useCallback(()=>{pickFrom(onPickPhotos)},[pickFrom,onPickPhotos]),takePhoto=useCallback(()=>{!canTakePhoto||!canUpload||callHostAsync(()=>camera.capture(captureOptionsFor("photo"))).then(outcome=>{if(!outcome.ok)return;let handle=fileHandleFromMedia(outcome.value);if(handle.sizeBytes===void 0){setPickError(UPLOAD_COPY.errors.startPlain);return}run([handle])})},[camera,canTakePhoto,canUpload,run]),retryFailed=useCallback(()=>{run(failedFiles.current)},[run]);/* @__PURE__ */
689
689
  return jsxs(View,{style:local.card,testID:"records-upload-card",children:[
690
690
  /* @__PURE__ */jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:UPLOAD_COPY.cardTitle}),
691
691
  /* @__PURE__ */jsx(Text,{style:local.cardSubtitle,children:photoCopy?UPLOAD_PHOTO_COPY.note:UPLOAD_COPY.cardSubtitle}),pickError?/* @__PURE__ */jsx(View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsx(Text,{style:styles.errorText,children:pickError})}):null,
@@ -726,32 +726,226 @@ return jsxs(ScrollView,{contentContainerStyle:local.content,keyboardShouldPersis
726
726
  /* @__PURE__ */jsx(Text,{style:styles.bodyText,children:RECORDS_RECOVERY_COPY.cancelConsequence}),
727
727
  /* @__PURE__ */jsx(Pill,{label:form.busy&&lastAction==="revoke"?REQUEST_SCREEN_COPY.cancelling:REQUEST_SCREEN_COPY.cancel,kind:"danger",busy:form.busy&&lastAction==="revoke",onPress:()=>run("revoke",form.revoke),testID:"records-revoke-do"}),
728
728
  /* @__PURE__ */jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onPress:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onPress:form.askRevoke,testID:"records-revoke"}):null]})}function useLocalStyles10(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles10(theme),[theme])}function makeLocalStyles10(theme){let{color:color,space:space,radius:radius,type:type}=theme,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg+space.xs/2},readyCta:{minHeight:space.xxl+space.lg+space.xs/2},sent:{gap:space.xs},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,gap:space.md,...slotBox(recordCardSlot(theme.slots),1)},cardTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...slotText(recordCardSlot(theme.slots))},detailRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.lg},detailValue:{flexShrink:1,textAlign:"right",...text4(type.size.body,type.lineHeight.normal,color.text.primary)},failureCard:{borderRadius:radius.lg-space.xs,borderWidth:1,padding:space.md+space.xs/2,gap:space.md},failureCritical:{borderColor:color.badgeBgCritical,backgroundColor:color.badgeBgCritical},failureCaution:{borderColor:color.badgeBgCaution,backgroundColor:color.badgeBgCaution},failureTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},failureTitleCritical:{color:color.danger},failureTitleCaution:{color:color.warningStrong},emailBlock:{gap:space.sm},callBlock:{gap:space.sm},block:{gap:space.sm},confirmTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")}})}var REF_MAX=128;var ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str4=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str4(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str4(value,REF_MAX);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
729
- return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str4(v,len),max);function focusOf(value){let o=obj(value),kicker=str4(o?.kicker,120),title=str4(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label=str4(obj(r)?.label,60);return label===null?null:clean({label:label,kind:kindOf(obj(r)?.kind)})},6),risk:str4(risk?.lead,300)===null?null:clean({lead:str4(risk?.lead,300),body:str4(risk?.body),kind:kindOf(risk?.kind)}),odds:str4(odds?.label,120)===null||str4(odds?.from,20)===null||str4(odds?.to,20)===null?null:clean({label:str4(odds?.label,120),tag:str4(odds?.tag,40),from:str4(odds?.from,20),to:str4(odds?.to,20),toLabel:str4(odds?.toLabel,120)}),quote:str4(quote?.kicker,120)===null||str4(quote?.text)===null?null:clean({kicker:str4(quote?.kicker,120),tag:str4(quote?.tag,40),text:str4(quote?.text)}),jump:str4(jump?.title,300)===null||str4(jump?.go,60)===null?null:clean({title:str4(jump?.title,300),go:str4(jump?.go,60)})})}function routineOf(value){let o=obj(value),title=str4(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str4(s?.title,300);return t===null?null:clean({title:t,body:str4(s?.body),source:str4(s?.source,200)})});return title===null||steps===null?null:clean({title:title,label:str4(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str4(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text4=str4(v?.text),by=str4(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text4===null||by===null?null:clean({stars:Math.round(stars),text:text4,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str4(v?.chip,40),t=str4(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str4(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str4(v?.value,40),label=str4(v?.label,120);return val===null||label===null?null:clean({value:val,label:label})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,productId:idOf(o.productId),partnerSku:str4(o.partnerSku,200),rating:str4(rating?.value,20)===null?null:clean({value:str4(rating?.value,20),label:str4(rating?.label,120)}),line:str4(o.line),reviews:str4(reviews?.label,200)===null||reviewItems===null?null:clean({label:str4(reviews?.label,200),items:reviewItems}),checkoutLine:str4(o.checkoutLine,300),why:str4(why?.title,200)===null||whyRows===null?null:clean({title:str4(why?.title,200),rows:whyRows,score:str4(score?.text,200)===null||str4(score?.value,20)===null?null:clean({text:str4(score?.text,200),value:str4(score?.value,20)})}),dose:str4(dose?.title,200)===null||stats===null?null:clean({title:str4(dose?.title,200),stats:stats,note:str4(dose?.note)}),ingredients:ingredientItems===null?null:clean({label:str4(ingredients?.label,200),items:ingredientItems}),proof:str4(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str4(v?.label,120);return icon===null||label===null?null:clean({icon:icon,label:label})},6),more:str4(o.more,120),fine:str4(o.fine),checkin:str4(o.checkin,200)})}function signsOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str4(v?.title,300),body=str4(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str4(o?.title,200),questions=words(o?.questions,12,300),add=str4(o?.add,80),added=str4(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str4(v?.key,REF_MAX),t=str4(v?.title,300),action=str4(v?.action,80),added=str4(v?.added,80);return key===null||t===null||action===null||added===null?null:clean({key:key,title:t,body:str4(v?.body),price:str4(v?.price,40),was:str4(v?.was,40),tag:str4(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added})},6);return title===null||items===null?null:clean({title:title,items:items})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str4(o?.title,300),pick2=pickOf(o?.pick);if(o===null||title===null||pick2===null)return null;let byline=obj(o.byline);return clean({eyebrow:str4(o.eyebrow,120),title:title,subtitle:str4(o.subtitle,300),headImageUrl:imageOf(o.headImageUrl),byline:str4(byline?.name,120)===null?null:clean({name:str4(byline?.name,120),role:str4(byline?.role,120),imageUrl:imageOf(byline?.imageUrl)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick2,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),fine:str4(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str4(v?.label,60),val=str4(v?.value,200);return icon===null||label===null||val===null?null:clean({icon:icon,label:label,value:val})},6)})}function healthPlanPageFromWire(raw,petRef){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
729
+ return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str4(v,len),max);function focusOf(value){let o=obj(value),kicker=str4(o?.kicker,120),title=str4(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label=str4(obj(r)?.label,60);return label===null?null:clean({label:label,kind:kindOf(obj(r)?.kind)})},6),risk:str4(risk?.lead,300)===null?null:clean({lead:str4(risk?.lead,300),body:str4(risk?.body),kind:kindOf(risk?.kind)}),odds:str4(odds?.label,120)===null||str4(odds?.from,20)===null||str4(odds?.to,20)===null?null:clean({label:str4(odds?.label,120),tag:str4(odds?.tag,40),from:str4(odds?.from,20),to:str4(odds?.to,20),toLabel:str4(odds?.toLabel,120)}),quote:str4(quote?.text)===null?null:clean({kicker:str4(quote?.kicker,120),tag:str4(quote?.tag,40),text:str4(quote?.text)}),jump:str4(jump?.title,300)===null||str4(jump?.go,60)===null?null:clean({title:str4(jump?.title,300),go:str4(jump?.go,60)})})}function routineOf(value){let o=obj(value),title=str4(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str4(s?.title,300);return t===null?null:clean({title:t,body:str4(s?.body),source:str4(s?.source,200),fromVet:s?.fromVet===true?true:null})});return title===null||steps===null?null:clean({title:title,label:str4(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str4(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text4=str4(v?.text),by=str4(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text4===null||by===null?null:clean({stars:Math.round(stars),text:text4,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str4(v?.chip,40),t=str4(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str4(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str4(v?.value,40),label=str4(v?.label,120),kind=v?.kind;return val===null||label===null?null:clean({value:val,label:label,kind:kind==="weight"||kind==="dose"||kind==="days"?kind:null})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,none:o.none===true?true:null,productId:idOf(o.productId),partnerSku:str4(o.partnerSku,200),rating:str4(rating?.value,20)===null?null:clean({value:str4(rating?.value,20),label:str4(rating?.label,120)}),line:str4(o.line),reviews:str4(reviews?.label,200)===null||reviewItems===null?null:clean({label:str4(reviews?.label,200),items:reviewItems}),checkoutLine:str4(o.checkoutLine,300),why:str4(why?.title,200)===null||whyRows===null?null:clean({title:str4(why?.title,200),rows:whyRows,score:str4(score?.text,200)===null||str4(score?.value,20)===null?null:clean({text:str4(score?.text,200),value:str4(score?.value,20)})}),dose:str4(dose?.title,200)===null||stats===null?null:clean({title:str4(dose?.title,200),stats:stats,note:str4(dose?.note)}),doseLabel:str4(o.doseLabel,120),ingredients:ingredientItems===null?null:clean({label:str4(ingredients?.label,200),items:ingredientItems}),proof:str4(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str4(v?.label,120);return icon===null||label===null?null:clean({icon:icon,label:label})},6),more:str4(o.more,120),fine:str4(o.fine),checkin:str4(o.checkin,200)})}function signsOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str4(v?.title,300),body=str4(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null,callVet:v?.callVet===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str4(o?.title,200),questions=words(o?.questions,12,300),add=str4(o?.add,80),added=str4(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str4(v?.key,REF_MAX),t=str4(v?.title,300),action=str4(v?.action,80),added=str4(v?.added,80);return key===null||t===null||action===null||added===null?null:clean({key:key,title:t,body:str4(v?.body),price:str4(v?.price,40),was:str4(v?.was,40),tag:str4(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added,owned:v?.owned===true?true:null})},6);return title===null||items===null?null:clean({title:title,items:items})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str4(o?.title,300),pick2=pickOf(o?.pick);if(o===null||title===null||pick2===null)return null;let byline=obj(o.byline);return clean({eyebrow:str4(o.eyebrow,120),title:title,subtitle:str4(o.subtitle,300),headImageUrl:imageOf(o.headImageUrl),byline:str4(byline?.name,120)===null?null:clean({name:str4(byline?.name,120),role:str4(byline?.role,120),imageUrl:imageOf(byline?.imageUrl),shortName:str4(byline?.shortName,60)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick2,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),fine:str4(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str4(v?.label,60),val=str4(v?.value,200);return icon===null||label===null||val===null?null:clean({icon:icon,label:label,value:val})},6)})}function healthPlanPageFromWire(raw,petRef){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
730
730
  return Object.freeze({petRef:str4(o.pet_ref,REF_MAX)??petRef,pet:/* @__PURE__ */Object.freeze({name:str4(pet?.name,120),species:str4(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str4(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function invalid3(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed3(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX;function base(petRef){return`/widget/v1/pets/${encodeURIComponent(petRef)}/plan`}async function readPage(funnel,petRef,opts){if(!validRef(petRef))return err(invalid3("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base(petRef)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef);return page===null?err(malformed3("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef,opts)}}}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=useRef(refreshKey);useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}var HEALTH_PLAN_PAGE_SHARE_MS=5e3,sharedReads=/* @__PURE__ */new WeakMap;function readShared(reader,userRef,petRef,fresh){let reads=sharedReads.get(reader);reads===void 0&&(reads=/* @__PURE__ */new Map,sharedReads.set(reader,reads));let map=reads,key=`${userRef}\0${petRef}`,hit=map.get(key);if(!fresh&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPage(options){let{userRef:userRef,runtime:runtime}=useEverfurContext(),own=useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=useCallback((pet,fresh)=>hostRepository!==void 0||userRef==null?repository.getPage(pet):readShared(own,userRef,pet,fresh),[hostRepository,repository,own,userRef]),{petRef:petRef}=options,enabled=options.enabled!==false&&userRef!=null&&petRef!==null,[state,setState]=useState({phase:"idle",petRef:null,page:null,error:null}),epoch=useRef(0),quiet=useRef(0),read=useCallback(async fresh=>{let mine=++epoch.current;if(!enabled||petRef===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef,page:prev.petRef===petRef?prev.page:null,error:null}));let res=await getPage(petRef,fresh);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef,page:null,error:res.error}))},[enabled,petRef,getPage]),load=useCallback(()=>read(true),[read]),ready=state.phase==="ready"&&state.petRef===petRef,revalidate=useCallback(async()=>{if(!enabled||petRef===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef?{phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state.petRef!==petRef;return useMemo(()=>({phase:stale?"loading":state.phase,page:stale?null:state.page,error:stale?null:state.error,missing:!stale&&state.missing===true,refresh:load}),[stale,state,load])}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX2=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE2=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE2.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text3=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text3(FOOD_MAX),foodType:text3(FOOD_MAX),microchipId:text3(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text3(REF_MAX2,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text3(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text3(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text3(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text3(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text3(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text3(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str5=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str5(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str5(o.ref),name:name,dose:str5(o.dose),frequency:str5(o.frequency),startDate:str5(o.start_date),endDate:str5(o.end_date),notes:str5(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
731
731
  return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str5(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str5(o.food_brand),foodType:str5(o.food_type),microchipId:str5(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str5(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str5(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str5(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str5(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str5(row.ref),conditionName:conditionName,diagnosedDate:str5(row.diagnosed_date),notes:str5(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX2=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid4(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid4(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid4(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid4(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid4("pet_ref must be a string");if(petRef.trim().length===0)return invalid4("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid4("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid4("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX2)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid4(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid4("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid4("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str6=v=>typeof v=="string"?v:null,num3=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
732
732
  return Object.freeze({petRef:str6(o.pet_ref)??petRef,name:str6(o.name),species:str6(o.species),breed:str6(o.breed),ageYears:num3(o.age_years),weightKg:num3(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef=str6(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str6(o.pet_id),petRef:petRef,name:str6(o.name),species:str6(o.species),breed:str6(o.breed),ageYears:num3(o.age_years),weightKg:num3(o.weight_kg),updatedAt:str6(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
733
- return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid5=validate(petRef,profile);if(invalid5!==null)return err(invalid5);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base2={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base2,signal:opts.signal}:base2);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners2=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners2.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners2.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark"}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let server=parsePresentation(input?.server??null)??{},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
734
- return Object.freeze(out)}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentation(client){return useEverfurPresentationState(client).presentation}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf(client);return useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}var capital=text4=>text4.charAt(0).toUpperCase()+text4.slice(1);function sheetPetWords(name,pronoun){let trimmed=name.trim(),shown=trimmed.length>0?trimmed:NAMELESS_PET,Name=capital(shown);return pronoun==="her"?{name:shown,Name:Name,poss:"her",Poss:"Her",subj:"she"}:pronoun==="his"?{name:shown,Name:Name,poss:"his",Poss:"His",subj:"he"}:{name:shown,Name:Name,poss:`${shown}'s`,Poss:`${Name}'s`,subj:shown}}var SHEET_COPY=/* @__PURE__ */Object.freeze({vitalsFrom:(w,visit,date2)=>`Vitals from ${w.poss} ${visit}, ${date2}`,temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",upcomingCare:"Upcoming care",overdueBy:date2=>`Overdue · due by ${date2}`,dueSoon:"Due soon",later:"Later",recordsHistory:"Records & history",labs:"Labs & bloodwork",results:"results",screenings:"Screenings",visits:"Visits & records",timeline:"Timeline",events:n=>`${n} ${n===1?"event":"events"}`,weight:"Weight",vetVisits:n=>`${n} vet ${n===1?"visit":"visits"}`,history:"History",theirClinic:w=>`${w.Poss} clinic`,bloodPanel:"Blood panel",aboveRange:"above range",belowRange:"below range",othersInRange:"Other values in range.",addRecords:w=>`Add ${w.name}'s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",visitsCount:n=>`${n} ${n===1?"visit":"visits"}`,panelsCount:n=>`${n} blood ${n===1?"panel":"panels"}`,requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onFileNow:"On file now",firstRecord:w=>`Add ${w.name}'s first record`,firstLead:w=>`Records can come from more than one clinic over a lifetime. Start with the one ${w.subj} sees most, and this page fills in from there.`,requestFromTheirClinic:w=>`Request from ${w.poss} clinic`,requestDetail:"We send a secure request and read every page they send back.",uploadDetail:"A PDF, or a photo of a paper record.",sayBeats:/* @__PURE__ */Object.freeze(["Hmmm","I wonder","what I may be","hiding"]),sayStill:"I wonder what I may be hiding",sample:"Sample",peekLead:w=>`A sneak peek at how ${w.name}'s records will read. Every number links back to the page it came from.`,sampleNote:w=>`Sample data until ${w.poss} records arrive.`,onTheWay:w=>`${w.Name}'s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",anotherClinic:"Another clinic",anotherClinicDetail:"Seen more than one vet? We ask each one.",noDueDate:"No due date on file",noLabs:w=>`No lab results on file for ${w.name} yet. They show up here when a record includes a blood or urine panel.`,noVisits:w=>`No visits in ${w.name}'s records yet. They show up here when a record includes one.`,oneReading:"One reading so far: we'll plot a trend as more come in.",takingNow:"Taking now",noCurrentMeds:"No current medications on file.",topRisk:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`,panelOn:date2=>`${date2} blood panel`,latestReading:"Latest reading",rangeLine:(low,high,unit)=>`range ${low} to ${high}${unit?` ${unit}`:""}`,noRange:"No range on the report",above:"Above",inRange:"In range",below:"Below",high:"High",belowRangePill:"Below range",changeUp:(delta,unit)=>`Up ${delta}${unit?` ${unit}`:""}`,changeDown:(delta,unit)=>`Down ${delta}${unit?` ${unit}`:""}`,changeSince:(date2,pct2)=>` since ${date2}, about ${pct2}%.`,whatIs:name=>`What ${name} is`,otherValues:panel=>`Other ${panel} values`,panelTitle:(panel,date2)=>`${panel} · ${date2}`,askAboutThis:"Ask about this"}),SHEET_SAMPLE=/* @__PURE__ */Object.freeze({labsTitle:"Labs & bloodwork",group:"Liver",groupLead:"What the liver makes and clears.",markers:/* @__PURE__ */Object.freeze([{name:"ALT",value:"118",unit:"U/L",range:"10 to 100 U/L",at:92,high:true},{name:"ALP",value:"64",unit:"U/L",range:"23 to 212 U/L",at:33,high:false},{name:"GGT",value:"3",unit:"U/L",range:"0 to 11 U/L",at:36,high:false},{name:"Total bilirubin",value:"0.2",unit:"mg/dL",range:"0 to 0.9 mg/dL",at:33,high:false}]),more:/* @__PURE__ */Object.freeze([{tint:"emb",icon:"efi-shield",title:"Screenings",lead:()=>"Tests that look for common problems early, and what came back.",rows:/* @__PURE__ */Object.freeze([{label:"Heartworm test",pill:"Negative",tone:"clear"},{label:"Tick panel (4Dx)",pill:"Negative",tone:"clear"}])},{tint:"blue",icon:"efi-folder",title:"Visits & records",lead:()=>"Every visit, with the vet's notes and the pages they came from.",rows:/* @__PURE__ */Object.freeze([{label:"Wellness exam",when:"38 pages"},{label:"Video visit",when:"3 pages"}])},{tint:"yellow",icon:"efi-clock",title:"Timeline",lead:w=>`${w.Poss} whole history in order, with what's due next.`,rows:/* @__PURE__ */Object.freeze([{label:"Rabies vaccine",pill:"Due soon",tone:"watch"},{label:"Heartworm test",when:"Apr 18"}])}])});var DAY_MS=864e5,DUE_SOON_DAYS=30,LB_PER_KG=2.20462,MONTHS2=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function dayMs(value){if(value==null||value.length===0)return null;let ms=Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(value)?`${value}T00:00:00Z`:value);return Number.isNaN(ms)?null:ms}function shortDate(ms){let d=new Date(ms);return`${MONTHS2[d.getUTCMonth()]??""} ${d.getUTCDate()}`}function longDate(ms){return`${shortDate(ms)}, ${new Date(ms).getUTCFullYear()}`}function monthTick(ms){let d=new Date(ms);return`${d.getUTCMonth()+1}/${String(d.getUTCFullYear()%100).padStart(2,"0")}`}var dayKey=ms=>new Date(ms).toISOString().slice(0,10);function num4(value){return String(Math.round(value*100)/100)}var lb=kg=>Math.round(kg*LB_PER_KG*10)/10;function midSentence(text4){let t=text4.trim();return t.length<2||t[1]===t[1]?.toUpperCase()?t:t.charAt(0).toLowerCase()+t.slice(1)}function vitalKind(text4){return/temp/i.test(text4)?"temp":/heart|pulse/i.test(text4)?"heart":/resp|breath/i.test(text4)?"breath":null}var VITAL_ORDER=["temp","heart","breath"],VITAL_LABEL={temp:SHEET_COPY.temperature,heart:SHEET_COPY.heartRate,breath:SHEET_COPY.breathing};function sheetVitals(record){if(record===null||record.withheld)return{vitals:[],observedMs:null};let best=/* @__PURE__ */new Map;for(let e of record.entities){if(e.category!=="vital"||e.value===null||e.value.trim().length===0)continue;let kind=vitalKind(`${e.canonicalKey??""} ${e.key} ${e.label}`);if(kind===null)continue;let ms=dayMs(e.observedAt)??0,prev=best.get(kind);(prev===void 0||ms>prev.ms)&&best.set(kind,{value:e.value.trim(),unit:e.unit,ms:ms})}let vitals=VITAL_ORDER.flatMap(kind=>{let v=best.get(kind);return v===void 0?[]:[{kind:kind,value:v.value,unit:v.unit,label:VITAL_LABEL[kind]}]}),observed=[...best.values()].map(v=>v.ms).filter(ms=>ms>0);return{vitals:vitals,observedMs:observed.length>0?Math.max(...observed):null}}function encounterOn(encounters,ms){let key=dayKey(ms);return encounters.find(e=>{let at=dayMs(e.date);return at!==null&&dayKey(at)===key})??null}function dueIcon(title){return/vaccin|rabies|dhpp|booster|bordetella|lepto|lyme|parvo|distemper/i.test(title)?"efi-shield":/\b(alt|alp|lab|labs|blood|panel|bloodwork|urinalysis|chemistry|cbc)\b/i.test(title)?"efi-flask-sm":"efi-calendar"}function sheetDue(items,nowMs){return items.map(item=>{let due=dayMs(item.dueAt),icon=dueIcon(item.title);if(due!==null&&due<nowMs-DAY_MS+1)return{item:item,title:item.title,when:SHEET_COPY.overdueBy(shortDate(due)),tone:"alert",pill:null,icon:icon};let when=item.detail??(due===null?SHEET_COPY.noDueDate:longDate(due));if(due===null)return{item:item,title:item.title,when:when,tone:"none",pill:null,icon:icon};let soon=due-nowMs<=DUE_SOON_DAYS*DAY_MS;return{item:item,title:item.title,when:when,tone:soon?"watch":"later",pill:soon?SHEET_COPY.dueSoon:SHEET_COPY.later,icon:icon}})}function pointFlag(status){return status==null?null:/above|high/i.test(status)?"above":/below|low/i.test(status)?"below":/in_range|normal|in range/i.test(status)?"in":null}var kgShown=kg=>Math.round(kg*10)/10;function weightText(kg,unit){let pounds=`${num4(lb(kg))} lb`,kilos=`${num4(kgShown(kg))} kg`;return unit==="kg"?{main:kilos,other:pounds}:{main:pounds,other:kilos}}function weightModel(timeline,unit){if(timeline===null||timeline.withheld)return null;let readings=timeline.weights.flatMap(w=>{let ms=dayMs(w.observedOn);return ms===null||w.weightKg===null?[]:[{ms:ms,kg:w.weightKg}]}).sort((a,b)=>a.ms-b.ms),last=readings[readings.length-1];if(last===void 0)return null;let lbs=readings.map(r=>lb(r.kg)),lo=Math.min(...lbs),hi=Math.max(...lbs),t0=readings[0]?.ms??last.ms,span=last.ms-t0,points=readings.map((r,i)=>({x:span>0?Math.round((3.55+93.45*(r.ms-t0)/span)*100)/100:50,y:hi>lo?Math.round((75-50*((lbs[i]??lo)-lo)/(hi-lo))*10)/10:50,lb:lbs[i]??0,value:unit==="kg"?kgShown(r.kg):lbs[i]??0,ms:r.ms})),tickPoints=points.length<=4?points:[points[0],points[points.length-1]].filter(p=>p!==void 0),text4=weightText(last.kg,unit);return{latest:text4.main,sub:`${text4.other} · ${shortDate(last.ms)}`,single:points.length===1,points:points,ticks:tickPoints.map(p=>({x:p.x,label:monthTick(p.ms)})),vetCount:points.length}}function labDays(markers){let days=/* @__PURE__ */new Map;if(markers===null||markers.withheld)return days;for(let marker of markers.markers)for(let point of marker.points){let ms=dayMs(point.at);if(ms===null)continue;let key=dayKey(ms),day=days.get(key)??{ms:ms,flagged:[],total:0,inRange:0,clinics:/* @__PURE__ */new Set};day.total+=1;let flag=pointFlag(point.status);flag==="in"&&(day.inRange+=1),(flag==="above"||flag==="below")&&day.flagged.push({marker:marker,point:point,ms:ms,flag:flag}),point.sourceClinic&&day.clinics.add(point.sourceClinic),days.set(key,day)}return days}function historyModel(inputs,days){let items=[];for(let[key,day]of days)day.flagged.forEach((f,i)=>{let value=f.point.value===null?f.point.qualitativeResult??"":num4(f.point.value),unit=f.point.unit??f.marker.unit,others=day.flagged.length===1&&day.inRange===day.total-1&&day.total>1;items.push({key:`lab-${key}-${f.marker.markerId}-${i}`,ms:day.ms,date:`${shortDate(day.ms)} · ${SHEET_COPY.bloodPanel}`,title:`${f.marker.name} ${value}${unit?` ${unit}`:""}, ${f.flag==="above"?SHEET_COPY.aboveRange:SHEET_COPY.belowRange}`,text:others?SHEET_COPY.othersInRange:null,alert:true,markerId:f.marker.markerId,order:0})});let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],visits=inputs.timeline?.withheld===false?inputs.timeline.visits:[],usedVisits=/* @__PURE__ */new Set;encounters.forEach((e,i)=>{let ms=dayMs(e.date);if(ms===null)return;let visit=visits.find(v=>e.docId!==null&&v.docId===e.docId||dayMs(v.visitDate)!==null&&dayKey(dayMs(v.visitDate)??0)===dayKey(ms))??null;visit!==null&&usedVisits.add(visit.visitId);let summary=visit?.summary?.trim()||null,type=e.type?.trim()||null,title=summary??type;title!==null&&items.push({key:`enc-${e.encounterId}-${i}`,ms:ms,date:summary!==null&&type!==null?`${shortDate(ms)} · ${type}`:shortDate(ms),title:title,text:null,alert:false,markerId:null,order:1})});for(let v of visits){let ms=dayMs(v.visitDate),summary=v.summary?.trim()||null;usedVisits.has(v.visitId)||ms===null||summary===null||items.push({key:`visit-${v.visitId}`,ms:ms,date:shortDate(ms),title:summary,text:null,alert:false,markerId:null,order:1})}items.sort((a,b)=>b.ms-a.ms||a.order-b.order);let years=[];for(let entry of items){let item={key:entry.key,ms:entry.ms,date:entry.date,title:entry.title,text:entry.text,alert:entry.alert,markerId:entry.markerId},year=String(new Date(item.ms).getUTCFullYear()),last=years[years.length-1];last!==void 0&&last.year===year?last.items.push(item):years.push({year:year,items:[item]})}return{years:years,count:items.length}}function sourcesModel(inputs,days){let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],clinicLabel=name=>name?.trim()||SHEET_COPY.theirClinic(inputs.words),visits=/* @__PURE__ */new Map;for(let e of encounters)visits.set(clinicLabel(e.clinicName),(visits.get(clinicLabel(e.clinicName))??0)+1);let panels=/* @__PURE__ */new Map,onlyClinic=visits.size===1?[...visits.keys()][0]:void 0;for(let day of days.values()){let names=day.clinics.size>0?[...day.clinics].map(clinicLabel):[onlyClinic??SHEET_COPY.theirClinic(inputs.words)];for(let n of names)panels.set(n,(panels.get(n)??0)+1)}return[.../* @__PURE__ */new Set([...visits.keys(),...panels.keys()])].map(label=>({label:label,detail:[(visits.get(label)??0)>0?SHEET_COPY.visitsCount(visits.get(label)??0):null,(panels.get(label)??0)>0?SHEET_COPY.panelsCount(panels.get(label)??0):null].filter(p=>p!==null).join(" · ")}))}var PULL_PCT={requested:15,awaiting_clinic:35,awaiting_upload:35,received:60,parsing:75,in_review:90};function sheetPull(requests){let open=requests.filter(r=>!isTerminalStatus(r.status)).sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(open===void 0)return null;let step=(open.waitingExpectation?.trim()||open.statusLabel).trim();return step.length===0?null:{step:step,pct:PULL_PCT[open.status]??15}}function sheetMedications(timeline){if(timeline===null||timeline.withheld)return null;let named=timeline.medications.filter(m=>(m.drugName?.trim()??"")!=="");return named.length===0?null:{current:named.filter(m=>(m.stoppedOn?.trim()??"")==="").map(m=>{let parts=[m.dose,m.frequency,m.route].map(p=>p?.trim()??"").filter(p=>p!==""),detail=m.sig?.trim()||(parts.length>0?parts.join(" · "):null);return{key:m.medicationId,name:(m.drugName??"").trim(),detail:detail}})}}function sheetFailedRequest(requests){if(requests.some(r=>!isTerminalStatus(r.status)))return null;let newest=[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(newest===void 0||newest.status!=="failed")return null;let words2=newest.statusLabel.trim();return words2.length>0?words2:null}function sheetHasRecord(record,markers,depth){return record!==null&&!record.withheld&&!record.isEmpty||markers!==null&&!markers.withheld&&markers.markers.length>0?true:depth!==null&&!depth.withheld&&depth.encounters.length>0}function buildRecordsSheetModel(inputs){let{record:record,depth:depth,markers:markers,nowMs:nowMs}=inputs,has=sheetHasRecord(record,markers,depth),pull=sheetPull(inputs.requests),days=labDays(markers),{vitals:vitals,observedMs:observedMs}=sheetVitals(record),encounters=depth?.withheld===false?depth.encounters:[],visitAt=observedMs===null?null:encounterOn(encounters,observedMs),vitalsFrom=observedMs!==null&&visitAt?.type?SHEET_COPY.vitalsFrom(inputs.words,midSentence(visitAt.type),shortDate(observedMs)):null,unit=inputs.weightUnit??"lb",weight=weightModel(inputs.timeline,unit),latestKg=weight!==null?null:inputs.petWeightKg,meta=[inputs.breed?.trim()||null,weight?.latest??(latestKg!==null?weightText(latestKg,unit).main:null)].filter(p=>p!==null),timelineVisits=inputs.timeline?.withheld===false?inputs.timeline.visits.length:0,history=historyModel(inputs,days),encounterDays=encounters.map(e=>dayMs(e.date)).filter(ms=>ms!==null),markerList=markers?.withheld===false?markers.markers:[],featured=markers?.featuredMarkerId??markerList.find(m=>pointFlag(m.latest?.status)==="above"||pointFlag(m.latest?.status)==="below")?.markerId??markerList[0]?.markerId??null;return{state:has?"full":pull!==null?"onTheWay":"none",meta:meta.length>0?meta.join(" · "):null,vitals:vitals,vitalsFrom:vitalsFrom,due:record!==null&&!record.withheld?sheetDue(record.forwardLooking,nowMs):[],labsCount:markers?.withheld===false?markers.summary?.totalMarkers??markers.markers.length:0,featuredMarkerId:featured,latestVisit:encounterDays.length>0?longDate(Math.max(...encounterDays)):null,weight:weight,history:history.years,historyCount:history.count,sources:sourcesModel(inputs,days),pull:pull,hasVisits:encounters.length>0||timelineVisits>0,medications:sheetMedications(inputs.timeline),failedRequest:pull===null?sheetFailedRequest(inputs.requests):null}}function lastPoint(marker){let dated=marker.points.filter(p=>p.value!==null);return dated[dated.length-1]??marker.points[marker.points.length-1]??null}function rangeOf(point){return point===null||point.refLow===null||point.refHigh===null||!Number.isFinite(point.refLow)||!Number.isFinite(point.refHigh)||point.refHigh<=point.refLow?null:{low:point.refLow,high:point.refHigh}}function markerRow(marker,point=lastPoint(marker)){let range=rangeOf(point),unit=point?.unit??marker.unit,value=point?.value??null;return{markerId:marker.markerId,name:marker.name,value:value===null?point?.qualitativeResult??"":num4(value),unit:unit,range:range===null?null:`${num4(range.low)} to ${num4(range.high)}${unit?` ${unit}`:""}`,at:range===null||value===null?null:Math.round(Math.min(100,Math.max(0,20+60*(value-range.low)/(range.high-range.low)))),flag:pointFlag(point?.status??marker.latest?.status??null)}}function flagPill(flag){return flag==="above"?SHEET_COPY.high:flag==="below"?SHEET_COPY.belowRangePill:flag==="in"?SHEET_COPY.inRange:null}var panelWord=panel=>{let name=panel.replace(/\s+panel$/i,"").trim()||panel;return name.length>1&&name[1]===name[1]?.toUpperCase()?name:name.charAt(0).toLowerCase()+name.slice(1)};function buildSheetLabModel(markers,markerId){let marker=markers.markers.find(m=>m.markerId===markerId);if(marker===void 0)return null;let last=lastPoint(marker),row=markerRow(marker,last),lastMs=dayMs(last?.at??marker.latest?.at??null),range=rangeOf(last),latestSub=[lastMs===null?null:shortDate(lastMs),range===null?SHEET_COPY.noRange:SHEET_COPY.rangeLine(num4(range.low),num4(range.high),row.unit)].filter(p=>p!==null).join(" · "),numeric2=marker.points.flatMap(p=>{let ms=dayMs(p.at);return p.value===null||ms===null?[]:[{p:p,ms:ms,v:p.value}]}),chart=[];if(numeric2.length>0){let values=numeric2.map(n=>n.v),lo=range?.low??Math.min(...values),hi=range?.high??Math.max(...values);chart=numeric2.map((n,i)=>({x:numeric2.length===1?50:Math.round((18+64*i/(numeric2.length-1))*100)/100,y:hi>lo?Math.min(98,Math.max(2,Math.round((75-50*(n.v-lo)/(hi-lo))*10)/10)):50,label:num4(n.v),out:pointFlag(n.p.status)==="above"||pointFlag(n.p.status)==="below",tick:shortDate(n.ms)}))}let first=numeric2[0],final=numeric2[numeric2.length-1],change=null;if(first!==void 0&&final!==void 0&&numeric2.length>=2&&final.v!==first.v){let delta=Math.abs(final.v-first.v),pct2=first.v!==0?Math.round(delta/Math.abs(first.v)*100):null,lead2=final.v>first.v?SHEET_COPY.changeUp(num4(delta),row.unit):SHEET_COPY.changeDown(num4(delta),row.unit);change=pct2===null?null:{lead:lead2,rest:SHEET_COPY.changeSince(shortDate(first.ms),pct2)}}let groups=[],lastKey=lastMs===null?null:dayKey(lastMs),others=markers.markers.filter(m=>m.markerId!==marker.markerId),samePanel=others.filter(m=>m.panel!==null&&m.panel===marker.panel);if(samePanel.length>0&&marker.panel!==null){let rows=samePanel.map(m=>markerRow(m));groups.push({title:SHEET_COPY.otherValues(panelWord(marker.panel)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}if(lastKey!==null&&lastMs!==null){let byPanel=/* @__PURE__ */new Map;for(let m of others){if(m.panel===null||m.panel===marker.panel)continue;let p=[...m.points].reverse().find(pt=>{let ms=dayMs(pt.at);return ms!==null&&dayKey(ms)===lastKey});p!==void 0&&byPanel.set(m.panel,[...byPanel.get(m.panel)??[],markerRow(m,p)])}for(let[panel,rows]of byPanel)groups.push({title:SHEET_COPY.panelTitle(panel,shortDate(lastMs)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}return{markerId:marker.markerId,name:marker.name,meta:lastMs===null?null:SHEET_COPY.panelOn(longDate(lastMs)),pill:flagPill(row.flag),flagged:row.flag==="above"||row.flag==="below",latest:`${row.value}${row.unit?` ${row.unit}`:""}`,latestSub:latestSub,hasRange:range!==null,chart:chart,change:change,meaning:(marker.meaning??"").split(/\n\s*\n/).map(p=>p.trim()).filter(p=>p.length>0),groups:groups}}var RAPH_V3_LIGHT=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),cache=/* @__PURE__ */new WeakMap;function v3Palette(theme){let hit=cache.get(theme);if(hit!==void 0)return hit;let c=theme.color,dark=theme.brightness==="dark",neutrals=dark?{dark:dark,ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.background,card:c.surface,line:c.borderRingCream,tile:c.surfaceSubtle,shadow:c.shadow,riskBg:c.badgeBgCritical,riskInk:c.danger,riskDot:c.danger,clearBg:c.badgeBgPositive,clearInk:c.success,clearDot:c.success,watchDot:c.warningStrong}:{dark:dark,...RAPH_V3_LIGHT},textOn=(ink,grounds)=>pushToContrast(ink,grounds,poleForGrounds(grounds),V3_TEXT_CONTRAST),labelOn=(ink,fill)=>contrastRatio(ink,fill)>=V3_TEXT_CONTRAST?ink:legibleOn(fill,V3_TEXT_CONTRAST),badgeGrounds=[neutrals.card,neutrals.paper].map(under=>flattenOnto(c.brandSoft,under)??under),brand={primary:c.primary,onPrimary:labelOn(c.onPrimary,c.primary),accent:c.accent,onAccent:labelOn(c.onAccent,c.accent),link:textOn(c.linkInk,[neutrals.card,neutrals.paper,neutrals.tile]),badge:c.brandSoft,onBadge:textOn(c.brandInk,badgeGrounds)},palette=/* @__PURE__ */Object.freeze({...neutrals,...brand});return cache.set(theme,palette),palette}var V3_TEXT_CONTRAST=4.5;function v3InkOn(fill,inks){for(let ink of inks)if(contrastRatio(ink,fill)>=V3_TEXT_CONTRAST)return ink;return legibleOn(fill,V3_TEXT_CONTRAST)}var RAPH_RN_PALETTE=/* @__PURE__ */Object.freeze({ink:"#10462E",go:"#07C168",muted:"#6B6B6B",line:"#E4E4E4",alert:"#C03410",alertDeep:"#6D1D14",tintSage:"#E6ECE8",tintBlue:"#EAEEF6",tintYellow:"#FCF0D6",tintRed:"#FBF1EE",tintGo:"#DCF6EA",icoSage:"#819E90",efWhite:"#FFFFFF",efBlack:"#000000",efCharcoal:"#3D3D3D",efSkyBlue:"#4E98C9",embCyan1:"#E0FDFF",bgMist:"#F1F5F2",watch:"#F9E6B9",barTrack:"#ECECEC",topCard:"#FFCE34",topKicker:"#4A4845",topInk:"#262523"}),RAPH_RN_METRICS=/* @__PURE__ */Object.freeze({gap:12,sheetPadTop:20,sheetPadX:16,sheetPadBottom:28,sheetRadius:28,cardPad:16,cardRadius:20,name:22,cardTitle:18,rowTitle:17,body:15,small:13,mono:12,tileNum:20,big:32,button:48,rowButton:40,pill:24,plot:148,rowRadius:10,tileGap:10,icon:22});function sameColour(a,b){return a.trim().toLowerCase()===b.trim().toLowerCase()}function mix(a,b,t){let over=withAlpha(a,t);return(over!==null?flattenOnto(over,b):null)??b}var same=(a,b)=>parseColor(a)===parseColor(b);function raphIdentity(theme){if(theme.brightness!=="light")return false;let c=theme.color,k=EVERFUR_LIGHT.color;return same(c.primary,k.primary)&&same(c.brandInk,k.brandInk)&&same(c.onPrimary,k.onPrimary)&&same(c.accent,k.accent)&&same(c.accentEdge,k.accentEdge)}function brandTints(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),dark=theme.brightness==="dark",identity=raphIdentity(theme),compiled=(dark?EVERFUR_DARK:EVERFUR_LIGHT).color,accentSet=!same(c.accent,compiled.accent),ground=dark?c.surface:P.efWhite,tint=(hue,lightT)=>mix(hue,ground,dark?.18:lightT),tintSage=identity?P.tintSage:tint(v.primary,.105),topFill=accentSet?v.accent:tintSage;return{tintSage:tintSage,chevron:identity?P.icoSage:mix(c.brandInk,ground,.527),rowGround:identity?P.bgMist:tint(v.primary,.059),tintPartner:accentSet?tint(v.accent,.14):P.embCyan1,topFill:topFill,topKicker:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink3:P.topKicker,P.topInk]),topInk:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink:P.topInk,P.topInk])}}function recordsSheetLook(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),tints=brandTints(theme),accentOnFill=sameColour(c.accent,c.primary)?c.onPrimary:c.accent;return theme.brightness==="dark"?/* @__PURE__ */Object.freeze({dark:true,ground:c.background,card:v.card,text:v.ink,muted:v.ink3,line:c.structureEdge,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:c.success,goTint:c.badgeBgPositive,alert:v.riskInk,alertDeep:v.riskInk,alertTint:c.badgeBgCritical,watch:c.badgeBgCaution,tintBlue:c.surfaceSubtle,tintYellow:c.surfaceSubtle,barTrack:c.structureEdge,...tints}):/* @__PURE__ */Object.freeze({dark:false,ground:P.efWhite,card:P.efWhite,text:P.efBlack,muted:P.muted,line:P.line,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:P.go,goTint:P.tintGo,alert:P.alert,alertDeep:P.alertDeep,alertTint:P.tintRed,watch:P.watch,tintBlue:P.tintBlue,tintYellow:P.tintYellow,barTrack:P.barTrack,...tints})}function iconKindOf(efi){switch(efi){case"efi-flask":case"efi-flask-sm":return"flask";case"efi-shield":return"shield";case"efi-folder":return"folder";case"efi-clock":return"clock";case"efi-calendar":return"calendar";default:return"clock"}}var HIDDEN3={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"};function SheetIcon({kind:kind,size:size=RAPH_RN_METRICS.icon,color:color}){let glyph;switch(kind){case"flask":case"thermo":case"heart":case"wind":glyph=/* @__PURE__ */jsx(ActivityGlyph,{size:size,color:color});break;case"shield":glyph=/* @__PURE__ */jsx(CheckGlyph,{size:size,color:color});break;case"folder":case"clip":glyph=/* @__PURE__ */jsx(FileTextGlyph,{size:size,color:color});break;case"clock":case"calendar":glyph=/* @__PURE__ */jsx(ClockGlyph,{size:size,color:color});break;case"chevron":glyph=/* @__PURE__ */jsx(ChevronGlyph,{size:size,color:color,direction:"right"});break;case"upload":glyph=/* @__PURE__ */jsx(UploadGlyph,{size:size,color:color});break;case"download":glyph=/* @__PURE__ */jsx(View,{style:{transform:[{rotate:"180deg"}]},children:/* @__PURE__ */jsx(UploadGlyph,{size:size,color:color})});break;default:glyph=null}/* @__PURE__ */
735
- return jsx(View,{style:{width:size,height:size,alignItems:"center",justifyContent:"center"},...HIDDEN3,children:glyph})}var SheetKitContext=createContext(null);function useSheetKitValue(){let theme=useEverfurTheme();return useMemo(()=>{let look=recordsSheetLook(theme);return{theme:theme,look:look,s:makeSheetStyles(theme,look)}},[theme])}var SheetKitProvider=SheetKitContext.Provider;function useSheetKit(){let own=useSheetKitValue();return useContext(SheetKitContext)??own}function SheetPill({label:label,tone:tone,small:small=false,testID:testID}){let{s:s,look:look}=useSheetKit();if(label.trim().length===0)return null;let tones={watch:{backgroundColor:look.watch},stable:{backgroundColor:look.goTint},later:{backgroundColor:look.card,borderWidth:1.25,borderColor:look.line},clear:{backgroundColor:look.card,borderWidth:1.5,borderColor:look.go},plain:{backgroundColor:look.card,borderWidth:1.5,borderColor:look.line},high:{backgroundColor:look.card,borderWidth:1.25,borderColor:look.alert}},ink=tone==="later"?look.muted:tone==="clear"?look.go:tone==="high"?look.alert:look.ink;/* @__PURE__ */
736
- return jsx(View,{style:[s.pill,small?s.pillSmall:null,tones[tone]],testID:testID,children:/* @__PURE__ */jsx(Text,{tier:"compact",style:[s.pillText,small?s.pillTextSmall:null,{color:ink}],children:label})})}function SheetCard({children:children,style:style,testID:testID}){let{s:s}=useSheetKit();/* @__PURE__ */
733
+ return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid5=validate(petRef,profile);if(invalid5!==null)return err(invalid5);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base2={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base2,signal:opts.signal}:base2);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners2=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners2.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners2.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=useRef(0),load=useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]),useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let server=parsePresentation(input?.server??null)??{},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
734
+ return Object.freeze(out)}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentation(client){return useEverfurPresentationState(client).presentation}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf(client);return useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}var COARSE_NOW_TICK_MS=3600*1e3;function useCoarseNow(fixed,shown=true){let[now,setNow]=useState(()=>fixed??Date.now()),first=useRef(true);return useEffect(()=>{if(first.current){first.current=false;return}fixed===void 0&&shown&&setNow(Date.now())},[fixed,shown]),useEffect(()=>{if(fixed!==void 0||!shown)return;let tick=setInterval(()=>setNow(Date.now()),COARSE_NOW_TICK_MS),onVisible=()=>{document.visibilityState==="visible"&&setNow(Date.now())},doc=typeof document<"u"&&typeof document.addEventListener=="function"?document:null;return doc?.addEventListener("visibilitychange",onVisible),()=>{clearInterval(tick),doc?.removeEventListener("visibilitychange",onVisible)}},[fixed,shown]),fixed??now}var capital=text4=>text4.charAt(0).toUpperCase()+text4.slice(1);function sheetPetWords(name,pronoun){let trimmed=name.trim(),shown=trimmed.length>0?trimmed:NAMELESS_PET,Name=capital(shown);return pronoun==="her"?{name:shown,Name:Name,poss:"her",Poss:"Her",subj:"she"}:pronoun==="his"?{name:shown,Name:Name,poss:"his",Poss:"His",subj:"he"}:{name:shown,Name:Name,poss:`${shown}'s`,Poss:`${Name}'s`,subj:shown}}var SHEET_COPY=/* @__PURE__ */Object.freeze({vitalsFrom:(w,visit,date2)=>`Vitals from ${w.poss} ${visit}, ${date2}`,vitalsSource:w=>`Where ${w.name}'s vitals come from`,temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",upcomingCare:"Upcoming care",overdueBy:date2=>`Overdue · due by ${date2}`,dueSoon:"Due soon",later:"Later",noDate:"No date",dueIn:(date2,days)=>`Due ${date2} · in ${days} ${days===1?"day":"days"}`,dueToday:date2=>`Due ${date2} · today`,overdueByDays:(date2,days)=>`Overdue by ${days} ${days===1?"day":"days"} · due ${date2}`,recordsHistory:"Records & history",labs:"Labs & bloodwork",results:"results",screenings:"Screenings",screeningsClear:"All clear",screeningsToReview:n2=>`${n2} to review`,noScreenings:"No screenings yet",visits:"Visits & records",timeline:"Timeline",events:n2=>`${n2} ${n2===1?"event":"events"}`,weight:"Weight",vetVisits:n2=>`${n2} vet ${n2===1?"visit":"visits"}`,history:"History",theirClinic:w=>`${w.Poss} clinic`,bloodPanel:"Blood panel",aboveRange:"above range",belowRange:"below range",othersInRange:"Other values in range.",addRecords:w=>`Add ${w.name}'s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",visitsCount:n2=>`${n2} ${n2===1?"visit":"visits"}`,panelsCount:n2=>`${n2} blood ${n2===1?"panel":"panels"}`,requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onFileNow:"On file now",firstRecord:w=>`Add ${w.name}'s first record`,firstLead:w=>`Records can come from more than one clinic over a lifetime. Start with the one ${w.subj} sees most, and this page fills in from there.`,requestFromTheirClinic:w=>`Request from ${w.poss} clinic`,requestDetail:"We send a secure request and read every page they send back.",uploadDetail:"A PDF, or a photo of a paper record.",findClinic:w=>`Find ${w.name}'s clinic`,chooseFile:"Choose a file",sayBeats:/* @__PURE__ */Object.freeze(["Hmmm","I wonder","what I may be","hiding"]),sayStill:"I wonder what I may be hiding",sample:"Sample",peekLead:w=>`A sneak peek at how ${w.name}'s records will read. Every number links back to the page it came from.`,sampleNote:w=>`Sample data until ${w.poss} records arrive.`,onTheWay:w=>`${w.Name}'s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",anotherClinic:"Another clinic",anotherClinicDetail:"Seen more than one vet? We ask each one.",noDueDate:"No due date on file",noLabs:w=>`No lab results on file for ${w.name} yet. They show up here when a record includes a blood or urine panel.`,noVisits:w=>`No visits in ${w.name}'s records yet. They show up here when a record includes one.`,oneReading:"One reading so far: we'll plot a trend as more come in.",takingNow:"Taking now",noCurrentMeds:"No current medications on file.",noVetTitle:w=>`When ${w.name} has a vet, start here.`,requestedFrom:clinic=>`Requested from ${clinic}. Clinics usually take 2 to 5 days.`,onTheWayFrom:(w,clinic)=>`${w.Name}'s records from ${clinic} are on the way.`,readingUpload:"We're reading the document you uploaded.",seeWhereItStands:"See where it stands",topRisk:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`,panelOn:date2=>`${date2} blood panel`,latestReading:"Latest reading",rangeLine:(low,high,unit)=>`range ${low} to ${high}${unit?` ${unit}`:""}`,noRange:"No range on the report",above:"Above",inRange:"In range",below:"Below",high:"High",belowRangePill:"Below range",changeUp:(delta,unit)=>`Up ${delta}${unit?` ${unit}`:""}`,changeDown:(delta,unit)=>`Down ${delta}${unit?` ${unit}`:""}`,changeSince:(date2,pct2)=>` since ${date2}, about ${pct2}%.`,whatIs:name=>`What ${name} is`,otherValues:panel=>`Other ${panel} values`,panelTitle:(panel,date2)=>`${panel} · ${date2}`,askAboutThis:"Ask about this"});var DAY_MS=864e5,DUE_SOON_DAYS=30,LB_PER_KG=2.20462,MONTHS2=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function dayMs(value){if(value==null||value.length===0)return null;let ms2=Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(value)?`${value}T00:00:00Z`:value);return Number.isNaN(ms2)?null:ms2}function shortDate(ms2){let d=new Date(ms2);return`${MONTHS2[d.getUTCMonth()]??""} ${d.getUTCDate()}`}function longDate(ms2){return`${shortDate(ms2)}, ${new Date(ms2).getUTCFullYear()}`}function monthTick(ms2){let d=new Date(ms2);return`${d.getUTCMonth()+1}/${String(d.getUTCFullYear()%100).padStart(2,"0")}`}var dayKey=ms2=>new Date(ms2).toISOString().slice(0,10);function num4(value){return String(Math.round(value*100)/100)}var lb=kg=>Math.round(kg*LB_PER_KG*10)/10;function midSentence(text4){let t=text4.trim();return t.length<2||t[1]===t[1]?.toUpperCase()?t:t.charAt(0).toLowerCase()+t.slice(1)}function vitalKind(text4){return/temp/i.test(text4)?"temp":/heart|pulse/i.test(text4)?"heart":/resp|breath/i.test(text4)?"breath":null}var VITAL_ORDER=["temp","heart","breath"],VITAL_LABEL={temp:SHEET_COPY.temperature,heart:SHEET_COPY.heartRate,breath:SHEET_COPY.breathing};function sheetVitals(record){if(record===null||record.withheld)return{vitals:[],observedMs:null};let best=/* @__PURE__ */new Map;for(let e of record.entities){if(e.category!=="vital"||e.value===null||e.value.trim().length===0)continue;let kind=vitalKind(`${e.canonicalKey??""} ${e.key} ${e.label}`);if(kind===null)continue;let ms2=dayMs(e.observedAt)??0,prev=best.get(kind);(prev===void 0||ms2>prev.ms)&&best.set(kind,{value:e.value.trim(),unit:e.unit,ms:ms2})}let vitals=VITAL_ORDER.flatMap(kind=>{let v=best.get(kind);return v===void 0?[]:[{kind:kind,value:v.value,unit:v.unit,label:VITAL_LABEL[kind]}]}),observed=[...best.values()].map(v=>v.ms).filter(ms2=>ms2>0);return{vitals:vitals,observedMs:observed.length>0?Math.max(...observed):null}}function encounterOn(encounters,ms2){let key=dayKey(ms2);return encounters.find(e=>{let at=dayMs(e.date);return at!==null&&dayKey(at)===key})??null}function dueIcon(title){return/vaccin|rabies|dhpp|booster|bordetella|lepto|lyme|parvo|distemper/i.test(title)?"efi-shield":/\b(alt|alp|lab|labs|blood|panel|bloodwork|urinalysis|chemistry|cbc)\b/i.test(title)?"efi-flask-sm":"efi-calendar"}function sheetDue(items,nowMs){return items.map(item=>{let due=dayMs(item.dueAt),icon=dueIcon(item.title);if(due!==null&&due<nowMs-DAY_MS+1)return{item:item,title:item.title,when:SHEET_COPY.overdueBy(shortDate(due)),tone:"alert",pill:null,icon:icon};let when=item.detail??(due===null?SHEET_COPY.noDueDate:longDate(due));if(due===null)return{item:item,title:item.title,when:when,tone:"none",pill:null,icon:icon};let soon=due-nowMs<=DUE_SOON_DAYS*DAY_MS;return{item:item,title:item.title,when:when,tone:soon?"watch":"later",pill:soon?SHEET_COPY.dueSoon:SHEET_COPY.later,icon:icon}})}function pointFlag(status){return status==null?null:/above|high/i.test(status)?"above":/below|low/i.test(status)?"below":/in_range|normal|in range/i.test(status)?"in":null}var kgShown=kg=>Math.round(kg*10)/10;function weightText(kg,unit){let pounds=`${num4(lb(kg))} lb`,kilos=`${num4(kgShown(kg))} kg`;return unit==="kg"?{main:kilos,other:pounds}:{main:pounds,other:kilos}}function weightModel(timeline,unit){if(timeline===null||timeline.withheld)return null;let readings=timeline.weights.flatMap(w=>{let ms2=dayMs(w.observedOn);return ms2===null||w.weightKg===null?[]:[{ms:ms2,kg:w.weightKg}]}).sort((a,b)=>a.ms-b.ms),last=readings[readings.length-1];if(last===void 0)return null;let lbs=readings.map(r=>lb(r.kg)),lo=Math.min(...lbs),hi=Math.max(...lbs),t0=readings[0]?.ms??last.ms,span=last.ms-t0,points=readings.map((r,i)=>({x:span>0?Math.round((3.55+93.45*(r.ms-t0)/span)*100)/100:50,y:hi>lo?Math.round((75-50*((lbs[i]??lo)-lo)/(hi-lo))*10)/10:50,lb:lbs[i]??0,value:unit==="kg"?kgShown(r.kg):lbs[i]??0,ms:r.ms})),tickPoints=points.length<=4?points:[points[0],points[points.length-1]].filter(p=>p!==void 0),text4=weightText(last.kg,unit);return{latest:text4.main,sub:`${text4.other} · ${shortDate(last.ms)}`,single:points.length===1,points:points,ticks:tickPoints.map(p=>({x:p.x,label:monthTick(p.ms)})),vetCount:points.length}}function labDays(markers){let days=/* @__PURE__ */new Map;if(markers===null||markers.withheld)return days;for(let marker of markers.markers)for(let point of marker.points){let ms2=dayMs(point.at);if(ms2===null)continue;let key=dayKey(ms2),day=days.get(key)??{ms:ms2,flagged:[],total:0,inRange:0,clinics:/* @__PURE__ */new Set};day.total+=1;let flag=pointFlag(point.status);flag==="in"&&(day.inRange+=1),(flag==="above"||flag==="below")&&day.flagged.push({marker:marker,point:point,ms:ms2,flag:flag}),point.sourceClinic&&day.clinics.add(point.sourceClinic),days.set(key,day)}return days}function historyModel(inputs,days){let items=[];for(let[key,day]of days)day.flagged.forEach((f,i)=>{let value=f.point.value===null?f.point.qualitativeResult??"":num4(f.point.value),unit=f.point.unit??f.marker.unit,others=day.flagged.length===1&&day.inRange===day.total-1&&day.total>1;items.push({key:`lab-${key}-${f.marker.markerId}-${i}`,ms:day.ms,date:`${shortDate(day.ms)} · ${SHEET_COPY.bloodPanel}`,title:`${f.marker.name} ${value}${unit?` ${unit}`:""}, ${f.flag==="above"?SHEET_COPY.aboveRange:SHEET_COPY.belowRange}`,text:others?SHEET_COPY.othersInRange:null,alert:true,markerId:f.marker.markerId,order:0})});let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],visits=inputs.timeline?.withheld===false?inputs.timeline.visits:[],usedVisits=/* @__PURE__ */new Set;encounters.forEach((e,i)=>{let ms2=dayMs(e.date);if(ms2===null)return;let visit=visits.find(v=>e.docId!==null&&v.docId===e.docId||dayMs(v.visitDate)!==null&&dayKey(dayMs(v.visitDate)??0)===dayKey(ms2))??null;visit!==null&&usedVisits.add(visit.visitId);let summary=visit?.summary?.trim()||null,type=e.type?.trim()||null,title=summary??type;title!==null&&items.push({key:`enc-${e.encounterId}-${i}`,ms:ms2,date:summary!==null&&type!==null?`${shortDate(ms2)} · ${type}`:shortDate(ms2),title:title,text:null,alert:false,markerId:null,order:1})});for(let v of visits){let ms2=dayMs(v.visitDate),summary=v.summary?.trim()||null;usedVisits.has(v.visitId)||ms2===null||summary===null||items.push({key:`visit-${v.visitId}`,ms:ms2,date:shortDate(ms2),title:summary,text:null,alert:false,markerId:null,order:1})}items.sort((a,b)=>b.ms-a.ms||a.order-b.order);let years=[];for(let entry of items){let item={key:entry.key,ms:entry.ms,date:entry.date,title:entry.title,text:entry.text,alert:entry.alert,markerId:entry.markerId},year=String(new Date(item.ms).getUTCFullYear()),last=years[years.length-1];last!==void 0&&last.year===year?last.items.push(item):years.push({year:year,items:[item]})}return{years:years,count:items.length}}function sourcesModel(inputs,days){let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],clinicLabel=name=>name?.trim()||SHEET_COPY.theirClinic(inputs.words),visits=/* @__PURE__ */new Map;for(let e of encounters)visits.set(clinicLabel(e.clinicName),(visits.get(clinicLabel(e.clinicName))??0)+1);let panels=/* @__PURE__ */new Map,onlyClinic=visits.size===1?[...visits.keys()][0]:void 0;for(let day of days.values()){let names=day.clinics.size>0?[...day.clinics].map(clinicLabel):[onlyClinic??SHEET_COPY.theirClinic(inputs.words)];for(let n2 of names)panels.set(n2,(panels.get(n2)??0)+1)}return[.../* @__PURE__ */new Set([...visits.keys(),...panels.keys()])].map(label=>({label:label,detail:[(visits.get(label)??0)>0?SHEET_COPY.visitsCount(visits.get(label)??0):null,(panels.get(label)??0)>0?SHEET_COPY.panelsCount(panels.get(label)??0):null].filter(p=>p!==null).join(" · ")}))}var PULL_PCT={requested:15,awaiting_clinic:35,awaiting_upload:35,received:60,parsing:75,in_review:90};function sheetPull(requests){let open=requests.filter(r=>!isTerminalStatus(r.status)).sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(open===void 0)return null;let step=(open.waitingExpectation?.trim()||open.statusLabel).trim();return step.length===0?null:{step:step,pct:PULL_PCT[open.status]??15}}var newestFirst=requests=>[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0)),sentence=label=>/[.!?]$/.test(label)?label:`${label}.`;function sheetOnTheWay(words2,requests){let active=newestFirst(requests).filter(r=>!isTerminalStatus(r.status)),waiting=active.filter(r=>r.status==="awaiting_upload"),moving=active.filter(r=>r.status!=="awaiting_upload"),lines=[],clinics=/* @__PURE__ */new Map;for(let r of moving){let clinic=r.clinicName?.trim()??"";r.source!=="clinic_request"||clinic===""||clinics.has(clinic)||clinics.set(clinic,r)}for(let[clinic,newest]of clinics)lines.push({key:`clinic-${clinic}`,text:SHEET_COPY.onTheWayFrom(words2,clinic),requestId:newest.id});let upload=moving.find(r=>r.source==="owner_provided");upload!==void 0&&lines.push({key:"upload",text:SHEET_COPY.readingUpload,requestId:upload.id});let wait=waiting[0],label=wait?.statusLabel.trim()??"";return wait!==void 0&&label!==""&&lines.push({key:"awaiting-upload",text:sentence(label),requestId:wait.id}),lines}function sheetRequestedClinic(requests){return newestFirst(requests).find(r=>!isTerminalStatus(r.status)&&r.status!=="awaiting_upload"&&r.source==="clinic_request"&&(r.clinicName?.trim()??"")!=="")?.clinicName?.trim()??null}function sheetMedications(timeline){if(timeline===null||timeline.withheld)return null;let named=timeline.medications.filter(m=>(m.drugName?.trim()??"")!=="");return named.length===0?null:{current:named.filter(m=>(m.stoppedOn?.trim()??"")==="").map(m=>{let parts=[m.dose,m.frequency,m.route].map(p=>p?.trim()??"").filter(p=>p!==""),detail=m.sig?.trim()||(parts.length>0?parts.join(" · "):null);return{key:m.medicationId,name:(m.drugName??"").trim(),detail:detail}})}}function sheetFailedRequest(requests){if(requests.some(r=>!isTerminalStatus(r.status)))return null;let newest=[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(newest===void 0||newest.status!=="failed")return null;let words2=newest.statusLabel.trim();return words2.length>0?words2:null}function sheetHasRecord(record,markers,depth){return record!==null&&!record.withheld&&!record.isEmpty||markers!==null&&!markers.withheld&&markers.markers.length>0?true:depth!==null&&!depth.withheld&&depth.encounters.length>0}function buildRecordsSheetModel(inputs){let{record:record,depth:depth,markers:markers,nowMs:nowMs}=inputs,has=sheetHasRecord(record,markers,depth),pull=sheetPull(inputs.requests),days=labDays(markers),{vitals:vitals,observedMs:observedMs}=sheetVitals(record),encounters=depth?.withheld===false?depth.encounters:[],visitAt=observedMs===null?null:encounterOn(encounters,observedMs),vitalsFrom=observedMs!==null&&visitAt?.type?SHEET_COPY.vitalsFrom(inputs.words,midSentence(visitAt.type),shortDate(observedMs)):null,unit=inputs.weightUnit??"lb",weight=weightModel(inputs.timeline,unit),latestKg=weight!==null?null:inputs.petWeightKg,meta=[inputs.breed?.trim()||null,weight?.latest??(latestKg!==null?weightText(latestKg,unit).main:null)].filter(p=>p!==null),timelineVisits=inputs.timeline?.withheld===false?inputs.timeline.visits.length:0,history=historyModel(inputs,days),encounterDays=encounters.map(e=>dayMs(e.date)).filter(ms2=>ms2!==null),markerList=markers?.withheld===false?markers.markers:[],featured=markers?.featuredMarkerId??markerList.find(m=>pointFlag(m.latest?.status)==="above"||pointFlag(m.latest?.status)==="below")?.markerId??markerList[0]?.markerId??null;return{state:has?"full":pull!==null?"onTheWay":"none",meta:meta.length>0?meta.join(" · "):null,vitals:vitals,vitalsFrom:vitalsFrom,due:record!==null&&!record.withheld?sheetDue(record.forwardLooking,nowMs):[],labsCount:markers?.withheld===false?markers.summary?.totalMarkers??markers.markers.length:0,featuredMarkerId:featured,latestVisit:encounterDays.length>0?longDate(Math.max(...encounterDays)):null,weight:weight,history:history.years,historyCount:history.count,sources:sourcesModel(inputs,days),pull:pull,hasVisits:encounters.length>0||timelineVisits>0,medications:sheetMedications(inputs.timeline),failedRequest:pull===null?sheetFailedRequest(inputs.requests):null,inFlight:sheetOnTheWay(inputs.words,inputs.requests),requestedClinic:sheetRequestedClinic(inputs.requests)}}function lastPoint(marker){let dated=marker.points.filter(p=>p.value!==null);return dated[dated.length-1]??marker.points[marker.points.length-1]??null}function rangeOf(point){return point===null||point.refLow===null||point.refHigh===null||!Number.isFinite(point.refLow)||!Number.isFinite(point.refHigh)||point.refHigh<=point.refLow?null:{low:point.refLow,high:point.refHigh}}function markerRow(marker,point=lastPoint(marker)){let range=rangeOf(point),unit=point?.unit??marker.unit,value=point?.value??null;return{markerId:marker.markerId,name:marker.name,value:value===null?point?.qualitativeResult??"":num4(value),unit:unit,range:range===null?null:`${num4(range.low)} to ${num4(range.high)}${unit?` ${unit}`:""}`,at:range===null||value===null?null:Math.round(Math.min(100,Math.max(0,20+60*(value-range.low)/(range.high-range.low)))),flag:pointFlag(point?.status??marker.latest?.status??null)}}function flagPill(flag){return flag==="above"?SHEET_COPY.high:flag==="below"?SHEET_COPY.belowRangePill:flag==="in"?SHEET_COPY.inRange:null}var panelWord=panel=>{let name=panel.replace(/\s+panel$/i,"").trim()||panel;return name.length>1&&name[1]===name[1]?.toUpperCase()?name:name.charAt(0).toLowerCase()+name.slice(1)};function buildSheetLabModel(markers,markerId){let marker=markers.markers.find(m=>m.markerId===markerId);if(marker===void 0)return null;let last=lastPoint(marker),row=markerRow(marker,last),lastMs=dayMs(last?.at??marker.latest?.at??null),range=rangeOf(last),latestSub=[lastMs===null?null:shortDate(lastMs),range===null?SHEET_COPY.noRange:SHEET_COPY.rangeLine(num4(range.low),num4(range.high),row.unit)].filter(p=>p!==null).join(" · "),numeric2=marker.points.flatMap(p=>{let ms2=dayMs(p.at);return p.value===null||ms2===null?[]:[{p:p,ms:ms2,v:p.value}]}),chart=[];if(numeric2.length>0){let values=numeric2.map(n2=>n2.v),lo=range?.low??Math.min(...values),hi=range?.high??Math.max(...values);chart=numeric2.map((n2,i)=>({x:numeric2.length===1?50:Math.round((18+64*i/(numeric2.length-1))*100)/100,y:hi>lo?Math.min(98,Math.max(2,Math.round((75-50*(n2.v-lo)/(hi-lo))*10)/10)):50,label:num4(n2.v),out:pointFlag(n2.p.status)==="above"||pointFlag(n2.p.status)==="below",tick:shortDate(n2.ms)}))}let first=numeric2[0],final=numeric2[numeric2.length-1],change=null;if(first!==void 0&&final!==void 0&&numeric2.length>=2&&final.v!==first.v){let delta=Math.abs(final.v-first.v),pct2=first.v!==0?Math.round(delta/Math.abs(first.v)*100):null,lead2=final.v>first.v?SHEET_COPY.changeUp(num4(delta),row.unit):SHEET_COPY.changeDown(num4(delta),row.unit);change=pct2===null?null:{lead:lead2,rest:SHEET_COPY.changeSince(shortDate(first.ms),pct2)}}let groups=[],lastKey=lastMs===null?null:dayKey(lastMs),others=markers.markers.filter(m=>m.markerId!==marker.markerId),samePanel=others.filter(m=>m.panel!==null&&m.panel===marker.panel);if(samePanel.length>0&&marker.panel!==null){let rows=samePanel.map(m=>markerRow(m));groups.push({title:SHEET_COPY.otherValues(panelWord(marker.panel)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}if(lastKey!==null&&lastMs!==null){let byPanel=/* @__PURE__ */new Map;for(let m of others){if(m.panel===null||m.panel===marker.panel)continue;let p=[...m.points].reverse().find(pt=>{let ms2=dayMs(pt.at);return ms2!==null&&dayKey(ms2)===lastKey});p!==void 0&&byPanel.set(m.panel,[...byPanel.get(m.panel)??[],markerRow(m,p)])}for(let[panel,rows]of byPanel)groups.push({title:SHEET_COPY.panelTitle(panel,shortDate(lastMs)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}return{markerId:marker.markerId,name:marker.name,meta:lastMs===null?null:SHEET_COPY.panelOn(longDate(lastMs)),pill:flagPill(row.flag),flagged:row.flag==="above"||row.flag==="below",latest:`${row.value}${row.unit?` ${row.unit}`:""}`,latestSub:latestSub,hasRange:range!==null,chart:chart,change:change,meaning:(marker.meaning??"").split(/\n\s*\n/).map(p=>p.trim()).filter(p=>p.length>0),groups:groups}}var HUB_COPY=/* @__PURE__ */Object.freeze({temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",vitalsLabel:pet=>`Vitals at ${pet}’s last exam`,vitalLabel:(name,value,unit)=>`${name}, ${value} ${unit}. More about it`,sayLine:"I wonder what I may be hiding",sayPhrases:["Hmmm","I wonder","what I may be","hiding"],upcomingCare:"Upcoming Care",viewAll:"View all →",dueSoon:"Due soon",later:"Later",nothingDue:pet=>`Nothing due for ${pet} right now.`,overdueBy:n2=>`Overdue by ${n2} ${n2===1?"day":"days"}`,dueToday:"Due today",dueIn:n2=>`Due in ${n2} ${n2===1?"day":"days"}`,noDueDate:"No due date on file",withDue:(relative,date2)=>`${relative} · due ${date2}`,dueOn:date2=>`Due ${date2}`,thisDay:(dated,weekday)=>`${dated} · this ${weekday}`,inWeeks:(dated,weeks)=>`${dated} · in ${weeks} ${weeks===1?"week":"weeks"}`,recordsHistory:"Records & History",labs:"Labs & bloodwork",labsA11y:(n2,noun)=>`Labs and bloodwork, ${n2} ${noun}`,labsA11yUnknown:"Labs and bloodwork",labsCountUnknown:"--",markers:n2=>n2===1?"marker":"markers",results:n2=>n2===1?"result":"results",screenings:"Screenings",screeningsA11y:pill=>`Screenings${pill!==null?`, ${pill}`:""}`,toReview:n2=>`${n2} to review`,allClear:"All clear",visits:"Visits & records",visitsA11y:date2=>`Visits and records${date2!==null?`, latest ${date2}`:""}`,timeline:"Timeline",events:n2=>`${n2} events`,timelineA11y:n2=>`Timeline${n2>0?`, ${n2} events`:""}`,weight:"Weight",estimatedRange:"Estimated Optimal Adult Range",noWeights:pet=>`No weights on file yet. They show up here from ${pet}’s vet visits.`,legendOver:["OVER","WEIGHT"],legendStable:["STABLE"],legendUnder:["UNDER","WEIGHT"],trendSummary:(n2,latest,trend,low,high)=>`${n2===1?"1 reading":`${n2} readings`}, latest ${latest}${n2===1?"":`, trend ${trend}`}.${low!==null&&high!==null?` Healthy range ${low} to ${high}.`:""}`,pointLabel:(when,value,unit)=>when!==null?`${when}, ${value} ${unit}`:`${value} ${unit}`,addRecords:pet=>`Add ${pet}’s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",onFileNow:"On file now",videoVisit:"Everfur video visit",pages:n2=>`${n2} ${n2===1?"page":"pages"}`,requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onTheWay:pet=>`${pet}’s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",requestSentTo:clinic=>clinic!==null?`Request sent to ${clinic}`:"Request sent",signedRelease:when=>`${when} · you signed the release`,waitingFor:whose=>`Waiting for ${whose} records`,inHealthTab:whose=>`In ${whose} Health tab`,everyPageRead:"Every page read: vaccines, labs, visits, meds",today:"Today",anotherClinic:"Another clinic",anotherClinicText:"Seen more than one vet? We ask each one.",uploadText:"A PDF, or a photo of a paper record.",requestTitle:pet=>`${pet}’s records request`,requestA11y:(pet,status)=>`Records request for ${pet}. ${status}`,sample:"Sample",peekLead:pet=>`A sneak peek at how ${pet}’s records will read. Every number links back to the page it came from.`,previousGroup:"Previous group",nextGroup:"Next group",markerGroups:"Marker groups",sampleNotTheirs:pet=>`This is a sample, not ${pet}’s result.`,sampleNote:" Add her records to see her own numbers. Anything outside the range gets flagged like this, with what it measures and what to ask her vet.",columns:["Test","Result","Unit","Range"],slideOf:(chip,n2,of)=>`${chip}, ${n2} of ${of}`,high:"High",legal:RECORDS_FOOTNOTE,noVetTitle:w=>`When ${w.name} has a vet, start here.`});function hubAge(totalMonths){let years=Math.floor(totalMonths/12),months=totalMonths%12;return years<=0?`${months}m`:months>0?`${years}y ${months}m`:`${years}y`}var CHEM_P2={cap:"Read from the lab report, page 2",who:"Chemistry panel",page:"p. 2 of 12"},HUB_SAMPLE_GROUPS=/* @__PURE__ */Object.freeze([{key:"liver",chip:"Liver",lead:"What the liver makes and clears.",markers:[{name:"ALT",flag:"High",what:"An enzyme found mostly in liver cells.",at:92,value:"118",unit:"U/L"},{name:"ALP",what:"An enzyme from the liver and bones.",at:33,value:"64",unit:"U/L"},{name:"GGT",what:"An enzyme tied to the liver’s bile ducts.",at:36,value:"3",unit:"U/L"},{name:"Total bilirubin",what:"A yellow pigment the liver clears.",at:33,value:"0.2",unit:"mg/dL"}],from:{...CHEM_P2,rows:[{test:"ALB",result:"3.2",unit:"g/dL",range:"2.3-4.0"},{test:"ALP",result:"64",unit:"U/L",range:"23-212",lit:true},{test:"ALT",result:"118 H",unit:"U/L",range:"10-100",lit:true},{test:"BUN",result:"18",unit:"mg/dL",range:"7-27"},{test:"GGT",result:"3",unit:"U/L",range:"0-11",lit:true},{test:"T. BILI",result:"0.2",unit:"mg/dL",range:"0.0-0.9",lit:true}]}},{key:"kidney",chip:"Kidney",lead:"What the kidneys filter out and keep in balance.",markers:[{name:"BUN",what:"Protein waste the kidneys filter out.",at:53,value:"18",unit:"mg/dL"},{name:"Creatinine",what:"Muscle waste the kidneys filter out.",at:48,value:"1.1",unit:"mg/dL"},{name:"SDMA",what:"Another measure of kidney filtering.",at:59,value:"9",unit:"µg/dL"},{name:"Phosphorus",what:"A mineral the kidneys keep in balance.",at:42,value:"4.1",unit:"mg/dL"}],from:{...CHEM_P2,rows:[{test:"ALT",result:"45",unit:"U/L",range:"10-100"},{test:"BUN",result:"18",unit:"mg/dL",range:"7-27",lit:true},{test:"CA",result:"10.1",unit:"mg/dL",range:"7.9-12.0"},{test:"CREA",result:"1.1",unit:"mg/dL",range:"0.5-1.8",lit:true},{test:"PHOS",result:"4.1",unit:"mg/dL",range:"2.5-6.8",lit:true},{test:"SDMA",result:"9",unit:"µg/dL",range:"0-14",lit:true}]}},{key:"blood",chip:"Blood cells",lead:"The cells that carry oxygen, fight infection and help blood clot.",markers:[{name:"Red blood cells",what:"Cells that carry oxygen around the body.",at:43,value:"6.9",unit:"M/µL"},{name:"Hemoglobin",what:"The part of red cells that holds oxygen.",at:42,value:"15.8",unit:"g/dL"},{name:"White blood cells",what:"Cells that fight infection.",at:44,value:"9.8",unit:"K/µL"},{name:"Platelets",what:"Cell fragments that help blood clot.",at:41,value:"265",unit:"K/µL"}],from:{cap:"Read from the lab report, page 3",who:"Complete blood count",page:"p. 3 of 12",rows:[{test:"HCT",result:"46",unit:"%",range:"37.3-61.7"},{test:"HGB",result:"15.8",unit:"g/dL",range:"13.1-20.5",lit:true},{test:"NEUT",result:"6.1",unit:"K/µL",range:"2.95-11.64"},{test:"PLT",result:"265",unit:"K/µL",range:"148-484",lit:true},{test:"RBC",result:"6.9",unit:"M/µL",range:"5.65-8.87",lit:true},{test:"WBC",result:"9.8",unit:"K/µL",range:"5.05-16.76",lit:true}]}},{key:"sugar",chip:"Sugar and salts",lead:"Fuel, and the salts that keep fluids, nerves and muscles steady.",markers:[{name:"Glucose",what:"Blood sugar, the body’s main fuel.",at:41,value:"96",unit:"mg/dL"},{name:"Sodium",what:"A salt that keeps fluids in balance.",at:31,value:"147",unit:"mmol/L"},{name:"Potassium",what:"A salt that helps nerves and muscles work.",at:49,value:"4.6",unit:"mmol/L"},{name:"Calcium",what:"A mineral for bones, muscles and nerves.",at:52,value:"10.1",unit:"mg/dL"}],from:{...CHEM_P2,rows:[{test:"CA",result:"10.1",unit:"mg/dL",range:"7.9-12.0",lit:true},{test:"CL",result:"112",unit:"mmol/L",range:"109-122"},{test:"GLU",result:"96",unit:"mg/dL",range:"70-143",lit:true},{test:"K",result:"4.6",unit:"mmol/L",range:"3.5-5.8",lit:true},{test:"NA",result:"147",unit:"mmol/L",range:"144-160",lit:true},{test:"PHOS",result:"4.1",unit:"mg/dL",range:"2.5-6.8"}]}}]),HUB_SAMPLE_MORE=/* @__PURE__ */Object.freeze([{key:"screenings",title:"Screenings",tint:"pink",lead:"Tests that look for common problems early, and what came back.",rows:[{title:"Heartworm test",pill:"Negative",tone:"clear"},{title:"Tick panel (4Dx)",pill:"Negative",tone:"clear"}]},{key:"visits",title:"Visits & records",tint:"blue",lead:"Every visit, with the vet’s notes and the pages they came from.",rows:[{title:"Wellness exam",text:"38 pages"},{title:"Everfur video visit",text:"3 pages"}]},{key:"timeline",title:"Timeline",tint:"yellow",lead:"Her whole history in order, with what’s due next.",rows:[{title:"Rabies vaccine",pill:"Due soon",tone:"soon"},{title:"Heartworm test",text:"Apr 18"}]}]);var APP_HUB_PALETTE=/* @__PURE__ */Object.freeze({ink:"#10462E",go:"#07C168",muted:"#6B6B6B",line:"#E4E4E4",text:"#000000",bg:"#FFFFFF",white:"#FFFFFF",mist:"#F1F5F2",charcoal:"#3D3D3D",alert:"#C03410",alertDeep:"#6D1D14",pink:"#FFC3BC",yellow:"#F2C763",skyBlue:"#4E98C9",tintSage:"#E6ECE8",tintPink:"#FFEAE8",tintPinkSoft:"#FFF6F5",tintBlue:"#EAEEF6",tintYellow:"#FCF0D6",tintYellowEdge:"#F6D892",tintRed:"#FBF1EE",tintGo:"#DCF6EA",icoGrey:"#6B6B6B",icoSage:"#819E90",icoBlue:"#4E98C9",barTrack:"#ECECEC",pillPlainEdge:"rgba(16, 70, 46, 0.2)"}),APP_HUB_TYPE=/* @__PURE__ */Object.freeze({screenTitle:/* @__PURE__ */Object.freeze({size:22,lineHeight:26.4,face:"medium",color:"ink",letterSpacing:-.33}),cardTitle:/* @__PURE__ */Object.freeze({size:18,lineHeight:22.5,face:"bold",color:"ink",letterSpacing:-.36}),body:/* @__PURE__ */Object.freeze({size:17,lineHeight:26.35,face:"regular",color:"text",letterSpacing:0}),bodySm:/* @__PURE__ */Object.freeze({size:15,lineHeight:21.75,face:"regular",color:"text",letterSpacing:0}),bodySmBold:/* @__PURE__ */Object.freeze({size:15,lineHeight:21.75,face:"bold",color:"ink",letterSpacing:0}),fine:/* @__PURE__ */Object.freeze({size:13,lineHeight:18.2,face:"regular",color:"muted",letterSpacing:0}),labelMono:/* @__PURE__ */Object.freeze({size:12,lineHeight:16.8,face:"monoBold",color:"muted",letterSpacing:.72,upper:true}),pill:/* @__PURE__ */Object.freeze({size:12,lineHeight:14.4,face:"monoBold",color:"ink",letterSpacing:.72,upper:true}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:18,face:"bold",color:"ink",letterSpacing:0}),buttonRow:/* @__PURE__ */Object.freeze({size:14,lineHeight:16.8,face:"bold",color:"ink",letterSpacing:0}),chip:/* @__PURE__ */Object.freeze({size:14,lineHeight:16.8,face:"medium",color:"ink",letterSpacing:0}),hand:/* @__PURE__ */Object.freeze({size:22,lineHeight:26.4,face:"hand",color:"ink",letterSpacing:0})}),APP_HUB_LEGACY=/* @__PURE__ */Object.freeze({surface:"#FFFFFF",textPrimary:"#111111",textMuted:"#6E6660",border:"#C8BEB4",brand:"#10462E",brandSoft:"rgba(16, 70, 46, 0.1)",danger:"#B91C1C"}),APP_HUB_TIMELINE=/* @__PURE__ */Object.freeze({dot:24,check:12,core:10,ring:2,rowGap:12,bodyBottom:18,bodyGap:2,titleGap:8,rail:2,railMin:22,railGap:2,titleSize:14,titleLineHeight:18,dateSize:12,dateLineHeight:16,detailSize:13,detailLineHeight:17,upcomingOpacity:.7});var APP_HUB=/* @__PURE__ */Object.freeze({screen:{gap:12,padX:16,padBottom:24,legalTop:20},hero:{nameSize:22,nameLineHeight:26,nameTracking:-.44,metaTop:2,metaLineHeight:18,metaTracking:.26,stageHeight:280,stageTop:4,grassFraction:.46,petBottom:40,petBoxHeight:224,petTop:16,sayWidth:230,sayHeight:61,sayFontSize:22,sayArcPath:"M 12 60 Q 120 -4 228 60",sayViewBox:[240,64],vitalsTop:8,vitalsLeft:8,vitalMinHeight:40,vitalPadX:8,vitalGap:6,vitalIcon:22,vitalValueSize:17,vitalUnitSize:13,lawnOverlap:26,lawnRadius:28},card:{pad:16,radius:20,border:1,headGap:8,headBottom:12},button:{md:52,sm:46,row:36,padMd:24,padSm:16,padRow:14,iconMd:22,iconSm:20,iconRow:17,edge:1.5,gap:8,mdLabel:17,textGap:6,textMinHeight:24},pill:{minHeight:24,padX:10,edgeThin:1.25,edgeThick:1.5},upcoming:{listGap:4,bleed:8,rowPadY:10,rowPadX:8,rowGap:12,rowRadius:10,icon:20,maxRows:4},tiles:{top:8,titleBottom:12,gap:12,pad:16,radius:20,innerGap:8,icon:22,chevron:20,titleLineHeight:19,footMinHeight:28,numSize:20,numLineHeight:22,numTracking:-.4,countGap:8},weight:{headGap:4,headBottom:16,numSize:32,numLineHeight:34,numTracking:-.64,numGap:8},chart:{height:176,plotTop:24,axisBand:20,rightInset:14,indicatorWidth:8,plotLeft:62,dataLeft:76,dot:6,dotRing:1.5,lineWidth:2,labelGap:7,labelMax:12,labelMin:9,labelCharWidth:.62,edgePad:4,legendX:14,legendLine:14.4,legendSize:12,legendTracking:.24,monthY:172,monthSize:12,maxTicks:5,maxValues:8,bandFrom:.3,bandTo:.7,reach:.88,bandPct:.1,lineColor:"#111111",gridColor:"#EAEAEA",bandColor:"#D8F3E3"},add:{gap:12,headGap:8,icon:26,sourcesGap:6,sourcesTop:4,sourcePadY:10,sourcePadX:14,sourceRadius:10,sourceColumnGap:12,actsGap:12,actsTop:4},peek:{top:12,headGap:12,leadTop:8,labsTop:16,chipsTop:10,chipsGap:8,slideTop:16,slideGap:4,slideLeadTop:2,slideLeadBottom:8,markerPad:12,markerGap:8,markerRadius:10,markerTopGap:12,barHeight:8,barDot:12,barDotRing:2,valueGap:4,fromMinHeight:40,fromGap:6,fromIcon:16,fromChevron:18,moreGap:12,moreTop:16,morePad:16,moreInnerGap:12,moreRadius:20,moreIcon:22,moreHeadGap:8,rowsGap:6,rowMinHeight:44,rowPadY:8,rowPadX:14,rowRadius:10,roundButton:36,chipHeight:36,chipPadX:14},onTheWay:{dot:28,titleSize:22,titleLineHeight:25,titleTracking:-.44,wayIcon:26,wayPad:16,wayRadius:20},inProgress:{radius:18,pad:18,gap:16,titleSize:16,titleLineHeight:20,statusRadius:14,statusPad:14,statusSize:13,statusLineHeight:19}});var HIDDEN3={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"},frame=size=>({width:size,height:size});function bar2(x1,y1,x2,y2,w,color){let len=Math.hypot(x2-x1,y2-y1)+w;return{position:"absolute",left:(x1+x2)/2-len/2,top:(y1+y2)/2-w/2,width:len,height:w,borderRadius:w/2,backgroundColor:color,transform:[{rotate:`${Math.atan2(y2-y1,x2-x1)}rad`}]}}function DownloadGlyph2({size:size,color:color}){let u=size/24.7029,w=2.05857*u;/* @__PURE__ */
735
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
736
+ /* @__PURE__ */jsx(View,{style:bar2(12.35*u,3.09*u,12.35*u,15.44*u,w,color)}),
737
+ /* @__PURE__ */jsx(View,{style:bar2(7.2*u,10.29*u,12.35*u,15.44*u,w,color)}),
738
+ /* @__PURE__ */jsx(View,{style:bar2(17.5*u,10.29*u,12.35*u,15.44*u,w,color)}),
739
+ /* @__PURE__ */jsx(Tray,{u:u,w:w,color:color})]})}function UploadArrowGlyph({size:size,color:color}){let u=size/24.7029,w=2.05857*u;/* @__PURE__ */
740
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
741
+ /* @__PURE__ */jsx(View,{style:bar2(12.35*u,3.09*u,12.35*u,15.44*u,w,color)}),
742
+ /* @__PURE__ */jsx(View,{style:bar2(7.2*u,8.23*u,12.35*u,3.09*u,w,color)}),
743
+ /* @__PURE__ */jsx(View,{style:bar2(17.5*u,8.23*u,12.35*u,3.09*u,w,color)}),
744
+ /* @__PURE__ */jsx(Tray,{u:u,w:w,color:color})]})}function Tray({u:u,w:w,color:color}){/* @__PURE__ */
745
+ return jsx(View,{style:{position:"absolute",left:3.09*u-w/2,top:15.44*u,width:(21.61-3.09)*u+w,height:(21.62-15.44)*u+w/2,borderLeftWidth:w,borderRightWidth:w,borderBottomWidth:w,borderColor:color,borderBottomLeftRadius:2.06*u+w/2,borderBottomRightRadius:2.06*u+w/2}})}function FolderGlyph({size:size,color:color}){let u=size/22.5814,w=1.88179*u,r=1.88*u+w/2;/* @__PURE__ */
746
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
747
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:1.88*u-w/2,top:5.645*u-w/2,width:(20.7-1.88)*u+w,height:(18.82-5.645)*u+w,borderLeftWidth:w,borderRightWidth:w,borderBottomWidth:w,borderColor:color,borderTopRightRadius:r,borderBottomLeftRadius:r,borderBottomRightRadius:r}}),
748
+ /* @__PURE__ */jsx(View,{style:bar2(10.5*u,5.645*u,18.82*u,5.645*u,w,color)}),
749
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:1.88*u-w/2,top:2.82*u-w/2,width:(7.46-1.88)*u+w,height:(5.645-2.82)*u+w,borderLeftWidth:w,borderTopWidth:w,borderColor:color,borderTopLeftRadius:r}}),
750
+ /* @__PURE__ */jsx(View,{style:bar2(7.46*u,2.82*u,8.6*u,3.3*u,w,color)}),
751
+ /* @__PURE__ */jsx(View,{style:bar2(8.9*u,3.6*u,10.5*u,5.645*u,w,color)})]})}function ShieldGlyph({size:size,color:color}){let u=size/22.5814,w=1.88179*u,half=(18.82-3.76)/2*u;/* @__PURE__ */
752
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
753
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:3.76*u-w/2,top:4.7*u,width:(18.82-3.76)*u+w,height:(12.23-4.7)*u,borderLeftWidth:w,borderRightWidth:w,borderColor:color}}),
754
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:3.76*u-w/2,top:12.23*u,width:half+w/2,height:(20.65-12.23)*u+w/2,borderLeftWidth:w,borderBottomWidth:w,borderColor:color,borderBottomLeftRadius:half+w/2}}),
755
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:11.29*u,top:12.23*u,width:half+w/2,height:(20.65-12.23)*u+w/2,borderRightWidth:w,borderBottomWidth:w,borderColor:color,borderBottomRightRadius:half+w/2}}),
756
+ /* @__PURE__ */jsx(View,{style:bar2(3.76*u,4.95*u,11.29*u,1.88*u,w,color)}),
757
+ /* @__PURE__ */jsx(View,{style:bar2(18.82*u,4.95*u,11.29*u,1.88*u,w,color)}),
758
+ /* @__PURE__ */jsx(View,{style:bar2(8.47*u,11.29*u,10.35*u,13.17*u,w,color)}),
759
+ /* @__PURE__ */jsx(View,{style:bar2(10.35*u,13.17*u,14.11*u,9.41*u,w,color)})]})}function ClockFaceGlyph({size:size,color:color}){let u=size/22.5814,w=1.88179*u,r=9.41*u+w/2;/* @__PURE__ */
760
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
761
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:11.29*u-r,top:11.29*u-r,width:2*r,height:2*r,borderRadius:r,borderWidth:w,borderColor:color}}),
762
+ /* @__PURE__ */jsx(View,{style:bar2(11.29*u,5.65*u,11.29*u,11.29*u,w,color)}),
763
+ /* @__PURE__ */jsx(View,{style:bar2(11.29*u,11.29*u,15.05*u,13.17*u,w,color)})]})}function FlaskGlyph({size:size,color:color}){let u=size/22.5814,w=1.88179*u,seg=[[8,1.88,14.58,1.88],[9.41,1.88,9.41,7.53],[13.17,1.88,13.17,7.53],[9.41,7.53,3.95,17.95],[13.17,7.53,18.63,17.95],[3.95,17.95,5.65,20.7],[18.63,17.95,16.94,20.7],[5.65,20.7,16.94,20.7],[6.07,14.11,16.51,14.11]];/* @__PURE__ */
764
+ return jsx(View,{style:frame(size),...HIDDEN3,children:seg.map(([x1,y1,x2,y2],i)=>/* @__PURE__ */jsx(View,{style:bar2(x1*u,y1*u,x2*u,y2*u,w,color)},i))})}function arc(cx,cy,r,w,color,sides,turn){let d=2*r+w,on=side=>sides.includes(side)?color:"transparent";return{position:"absolute",left:cx-d/2,top:cy-d/2,width:d,height:d,borderRadius:d/2,borderWidth:w,borderTopColor:on("top"),borderRightColor:on("right"),borderBottomColor:on("bottom"),borderLeftColor:on("left"),transform:[{rotate:`${turn}deg`}]}}function CalendarGlyph({size:size,color:color}){let u=size/24,w=2*u;/* @__PURE__ */
765
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
766
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:3*u-w/2,top:4*u-w/2,width:18*u+w,height:18*u+w,borderRadius:2*u+w/2,borderWidth:w,borderColor:color}}),
767
+ /* @__PURE__ */jsx(View,{style:bar2(8*u,2*u,8*u,6*u,w,color)}),
768
+ /* @__PURE__ */jsx(View,{style:bar2(16*u,2*u,16*u,6*u,w,color)}),
769
+ /* @__PURE__ */jsx(View,{style:bar2(3*u,10*u,21*u,10*u,w,color)})]})}function ClipboardGlyph({size:size,color:color}){let u=size/28.0714,w=2.33929*u,r=2.34*u+w/2;/* @__PURE__ */
770
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
771
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:4.68*u-w/2,top:4.68*u-w/2,width:(9.36-4.68)*u+w,height:4*u,borderLeftWidth:w,borderTopWidth:w,borderColor:color,borderTopLeftRadius:r}}),
772
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:18.71*u-w/2,top:4.68*u-w/2,width:(23.39-18.71)*u+w,height:4*u,borderRightWidth:w,borderTopWidth:w,borderColor:color,borderTopRightRadius:r}}),
773
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:4.68*u-w/2,top:7*u,width:(23.39-4.68)*u+w,height:(25.73-7)*u+w/2,borderLeftWidth:w,borderRightWidth:w,borderBottomWidth:w,borderColor:color,borderBottomLeftRadius:r,borderBottomRightRadius:r}}),
774
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:9.36*u-w/2,top:2.34*u-w/2,width:(18.71-9.36)*u+w,height:(7.02-2.34)*u+w,borderRadius:1.17*u+w/2,borderWidth:w,borderColor:color}}),
775
+ /* @__PURE__ */jsx(View,{style:bar2(10.53*u,16.38*u,17.54*u,16.38*u,w,color)}),
776
+ /* @__PURE__ */jsx(View,{style:bar2(14.04*u,12.87*u,14.04*u,19.88*u,w,color)})]})}function ThermoGlyph({size:size,color:color}){let u=size/25.7143,w=2.14286*u,tube=(15-10.71)*u+w;/* @__PURE__ */
777
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
778
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:10.71*u-w/2,top:2.14*u-w/2,width:tube,height:(16.3-2.14)*u+w/2,borderLeftWidth:w,borderRightWidth:w,borderTopWidth:w,borderColor:color,borderTopLeftRadius:tube/2,borderTopRightRadius:tube/2}}),
779
+ /* @__PURE__ */jsx(View,{style:arc(12.86*u,19.29*u,4.29*u,w,color,["right","bottom","left"],0)})]})}function HeartGlyph({size:size,color:color}){let u=size/25.7143,w=2.14286*u,a=12*u,cx=12.86*u,cy=4.3*u+.854*a,off=a/(2*Math.SQRT2);/* @__PURE__ */
780
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
781
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:cx-a/2,top:cy-a/2,width:a,height:a,borderRightWidth:w,borderBottomWidth:w,borderColor:color,borderBottomRightRadius:w,transform:[{rotate:"45deg"}]}}),
782
+ /* @__PURE__ */jsx(View,{style:arc(cx-off,cy-off,a/2-w/2,w,color,["top","left"],0)}),
783
+ /* @__PURE__ */jsx(View,{style:arc(cx+off,cy-off,a/2-w/2,w,color,["top","right"],0)})]})}function WindGlyph({size:size,color:color}){let u=size/25.7143,w=2.14286*u;/* @__PURE__ */
784
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[
785
+ /* @__PURE__ */jsx(View,{style:bar2(2.14*u,8.57*u,11.79*u,8.57*u,w,color)}),
786
+ /* @__PURE__ */jsx(View,{style:arc(11.79*u,6.43*u,2.14*u,w,color,["right","top"],45)}),
787
+ /* @__PURE__ */jsx(View,{style:bar2(2.14*u,12.86*u,20.89*u,12.86*u,w,color)}),
788
+ /* @__PURE__ */jsx(View,{style:arc(20.89*u,10.18*u,2.68*u,w,color,["right","top"],45)}),
789
+ /* @__PURE__ */jsx(View,{style:bar2(2.14*u,17.14*u,15*u,17.14*u,w,color)}),
790
+ /* @__PURE__ */jsx(View,{style:arc(15*u,19.29*u,2.14*u,w,color,["right","bottom"],-45)})]})}function SyringeGlyph({size:size,color:color}){let u=size/19.5956,w=1.63296*u,seg=[[14.53,1.63,17.8,4.9],[13.72,5.72,16.17,3.27],[15.35,7.35,6.94,15.76],[12.08,4.08,3.67,12.49],[6.94,15.76,5.55,16.37],[5.55,16.37,4.16,15.76],[4.16,15.76,3.67,15.27],[3.67,15.27,3.06,13.88],[3.06,13.88,3.67,12.49],[7.18,8.98,10.45,12.25],[3.92,15.51,1.47,17.96],[11.27,3.27,16.17,8.17]];/* @__PURE__ */
791
+ return jsx(View,{style:frame(size),...HIDDEN3,children:seg.map(([x1,y1,x2,y2],i)=>/* @__PURE__ */jsx(View,{style:bar2(x1*u,y1*u,x2*u,y2*u,w,color)},i))})}var CORNERS=[[6,4,"left"],[18,20,"right"],[6,20,"bottom"],[16,6,"bottom"]];function FileGlyph({size:size,color:color}){let u=size/24,w=2*u,seg=[[6,2,15,2],[4,4,4,20],[6,22,18,22],[20,7,20,20],[15,2,20,7],[14,2,14,6],[16,8,20,8],[8,9,10,9],[8,13,16,13],[8,17,16,17]];/* @__PURE__ */
792
+ return jsxs(View,{style:frame(size),...HIDDEN3,children:[seg.map(([x1,y1,x2,y2],i)=>/* @__PURE__ */jsx(View,{style:bar2(x1*u,y1*u,x2*u,y2*u,w,color)},i)),CORNERS.map(([cx,cy,side],i)=>/* @__PURE__ */jsx(View,{style:arc(cx*u,cy*u,2*u,w,color,[side],45)},`c${i}`))]})}var RAPH_V3_LIGHT=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),cache=/* @__PURE__ */new WeakMap;function v3Palette(theme){let hit=cache.get(theme);if(hit!==void 0)return hit;let c=theme.color,dark=theme.brightness==="dark",neutrals=dark?{dark:dark,ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.background,card:c.surface,line:c.borderRingCream,tile:c.surfaceSubtle,shadow:c.shadow,riskBg:c.badgeBgCritical,riskInk:c.danger,riskDot:c.danger,clearBg:c.badgeBgPositive,clearInk:c.success,clearDot:c.success,watchDot:c.warningStrong}:{dark:dark,...RAPH_V3_LIGHT},textOn=(ink,grounds)=>pushToContrast(ink,grounds,poleForGrounds(grounds),V3_TEXT_CONTRAST),labelOn=(ink,fill)=>contrastRatio(ink,fill)>=V3_TEXT_CONTRAST?ink:legibleOn(fill,V3_TEXT_CONTRAST),badgeGrounds=[neutrals.card,neutrals.paper].map(under=>flattenOnto(c.brandSoft,under)??under),brand={primary:c.primary,onPrimary:labelOn(c.onPrimary,c.primary),accent:c.accent,onAccent:labelOn(c.onAccent,c.accent),link:textOn(c.linkInk,[neutrals.card,neutrals.paper,neutrals.tile]),badge:c.brandSoft,onBadge:textOn(c.brandInk,badgeGrounds)},palette=/* @__PURE__ */Object.freeze({...neutrals,...brand});return cache.set(theme,palette),palette}var V3_TEXT_CONTRAST=4.5;function v3InkOn(fill,inks){for(let ink of inks)if(contrastRatio(ink,fill)>=V3_TEXT_CONTRAST)return ink;return legibleOn(fill,V3_TEXT_CONTRAST)}var RAPH_RN_PALETTE=/* @__PURE__ */Object.freeze({ink:"#10462E",go:"#07C168",muted:"#6B6B6B",line:"#E4E4E4",alert:"#C03410",alertDeep:"#6D1D14",tintSage:"#E6ECE8",tintBlue:"#EAEEF6",tintYellow:"#FCF0D6",tintRed:"#FBF1EE",tintGo:"#DCF6EA",icoSage:"#819E90",efWhite:"#FFFFFF",efBlack:"#000000",efCharcoal:"#3D3D3D",efSkyBlue:"#4E98C9",embCyan1:"#E0FDFF",bgMist:"#F1F5F2",paper:"#F8F7F4",watch:"#F9E6B9",barTrack:"#ECECEC",topCard:"#FFCE34",topKicker:"#4A4845",topInk:"#262523",plainEdge:"rgba(16, 70, 46, 0.2)"}),RAPH_RN_RULES=/* @__PURE__ */Object.freeze({".rec-note":/* @__PURE__ */Object.freeze({fontSize:12.5}),".efh":/* @__PURE__ */Object.freeze({gap:12,fontSize:15}),".efh-sheet":/* @__PURE__ */Object.freeze({marginTop:20,paddingTop:20,paddingBottom:28,paddingLeft:16,borderTopLeftRadius:28}),".efh-ico":/* @__PURE__ */Object.freeze({width:22}),".efh-label":/* @__PURE__ */Object.freeze({fontSize:12}),".efh-pill":/* @__PURE__ */Object.freeze({minHeight:24}),".efh-card":/* @__PURE__ */Object.freeze({paddingTop:16,borderRadius:20}),".efh-card__title":/* @__PURE__ */Object.freeze({fontSize:18}),".efh-btn":/* @__PURE__ */Object.freeze({minHeight:48}),".efh-btn--row":/* @__PURE__ */Object.freeze({minHeight:40}),".efh-head":/* @__PURE__ */Object.freeze({marginBottom:8}),".efh-name":/* @__PURE__ */Object.freeze({fontSize:22}),".efh-meta":/* @__PURE__ */Object.freeze({fontSize:13}),".efh-stage":/* @__PURE__ */Object.freeze({height:236,marginTop:4,marginLeft:-16}),".efh-stage__grass":/* @__PURE__ */Object.freeze({height:"44%"}),".efh-stage__pet":/* @__PURE__ */Object.freeze({left:"58%",bottom:22,height:"86%"}),".efh-stage .efh-vitals":/* @__PURE__ */Object.freeze({top:14,left:16,gap:12}),".efh-head__from":/* @__PURE__ */Object.freeze({marginTop:12}),".efh-due li":/* @__PURE__ */Object.freeze({borderRadius:10}),".efh-tiles":/* @__PURE__ */Object.freeze({gap:10}),".efh-tile__num":/* @__PURE__ */Object.freeze({fontSize:20}),".efh-wt b":/* @__PURE__ */Object.freeze({fontSize:32}),".efh-wchart__plot":/* @__PURE__ */Object.freeze({height:148}),".efh-sheet .rec-note":/* @__PURE__ */Object.freeze({marginTop:4}),".efh-mk__name":/* @__PURE__ */Object.freeze({fontSize:17}),".efh-mk__line":/* @__PURE__ */Object.freeze({rowGap:0,columnGap:6,marginTop:1,fontSize:13,lineHeight:18.2}),".efh-mk__line b":/* @__PURE__ */Object.freeze({fontSize:17}),".efh-none":/* @__PURE__ */Object.freeze({paddingTop:0}),".efh-none__scene":/* @__PURE__ */Object.freeze({marginBottom:16,marginLeft:-16}),".efh-none__t":/* @__PURE__ */Object.freeze({fontSize:22,lineHeight:25.3,letterSpacing:-.44}),".efh-none__lead":/* @__PURE__ */Object.freeze({marginTop:8,fontSize:15,lineHeight:22.5}),".efh-ways":/* @__PURE__ */Object.freeze({gap:12,marginTop:16}),".efh-way":/* @__PURE__ */Object.freeze({columnGap:12,paddingTop:16,borderRadius:20}),".efh-way__w":/* @__PURE__ */Object.freeze({gap:2}),".efh-way__t":/* @__PURE__ */Object.freeze({fontSize:16,lineHeight:20.8}),".efh-way__x":/* @__PURE__ */Object.freeze({fontSize:15,lineHeight:21.75}),".efh-peek__labs .efh-card__title":/* @__PURE__ */Object.freeze({marginBottom:8}),".efh-peek__g":/* @__PURE__ */Object.freeze({fontSize:15,lineHeight:21.75,marginBottom:6}),".efh-peek__g b":/* @__PURE__ */Object.freeze({fontSize:16})}),RAPH_RN_SAY=/* @__PURE__ */Object.freeze({viewBox:[0,0,240,64],path:{x0:12,y0:60,cx:120,cy:-4,x1:228,y1:60},width:210,headX:.34,headTop:0,gap:2,fontSize:22,fontWeight:"500",beats:4,keyframes:[{offset:0,opacity:0},{offset:.025,opacity:1},{offset:.052,opacity:1},{offset:.077,opacity:0},{offset:1,opacity:0}],durationMs:44e3,easing:"ease-in-out",delayMs:1200,staggerMs:3600}),RAPH_RN_SCENE=/* @__PURE__ */Object.freeze({height:212,grassHeight:64,petHeight:150,petBottom:16,petAspect:.731,grassSize:[1520,479],petSize:[307,420]});var R=RAPH_RN_RULES;function raphPx(selector,prop){let v=R[selector]?.[prop];return typeof v=="number"?v:Number.NaN}var n=raphPx;function raphPct(selector,prop){let v=R[selector]?.[prop];return typeof v=="string"&&v.endsWith("%")?Number(v.slice(0,-1))/100:Number.NaN}var RAPH_RN_METRICS=/* @__PURE__ */Object.freeze({gap:n(".efh","gap"),sheetPadTop:n(".efh-sheet","paddingTop"),sheetPadX:n(".efh-sheet","paddingLeft"),sheetPadBottom:n(".efh-sheet","paddingBottom"),sheetRadius:n(".efh-sheet","borderTopLeftRadius"),sheetGap:n(".efh-sheet","marginTop"),cardPad:n(".efh-card","paddingTop"),cardRadius:n(".efh-card","borderRadius"),name:n(".efh-name","fontSize"),cardTitle:n(".efh-card__title","fontSize"),rowTitle:n(".efh-mk__name","fontSize"),body:n(".efh","fontSize"),small:n(".efh-meta","fontSize"),mono:n(".efh-label","fontSize"),tileNum:n(".efh-tile__num","fontSize"),big:n(".efh-wt b","fontSize"),button:n(".efh-btn","minHeight"),rowButton:n(".efh-btn--row","minHeight"),pill:n(".efh-pill","minHeight"),plot:n(".efh-wchart__plot","height"),rowRadius:n(".efh-due li","borderRadius"),tileGap:n(".efh-tiles","gap"),icon:n(".efh-ico","width")});function sameColour(a,b){return a.trim().toLowerCase()===b.trim().toLowerCase()}function mix(a,b,t){let over=withAlpha(a,t);return(over!==null?flattenOnto(over,b):null)??b}var same=(a,b)=>parseColor(a)===parseColor(b);function raphIdentity(theme){if(theme.brightness!=="light")return false;let c=theme.color,k=EVERFUR_LIGHT.color;return same(c.primary,k.primary)&&same(c.brandInk,k.brandInk)&&same(c.onPrimary,k.onPrimary)&&same(c.accent,k.accent)&&same(c.accentEdge,k.accentEdge)}function brandTints(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),dark=theme.brightness==="dark",identity=raphIdentity(theme),compiled=(dark?EVERFUR_DARK:EVERFUR_LIGHT).color,accentSet=!same(c.accent,compiled.accent),ground=dark?c.surface:P.efWhite,tint=(hue,lightT)=>mix(hue,ground,dark?.18:lightT),tintSage=identity?P.tintSage:tint(v.primary,.105),topFill=accentSet?v.accent:tintSage;return{tintSage:tintSage,chevron:identity?P.icoSage:mix(c.brandInk,ground,.527),rowGround:identity?P.bgMist:tint(v.primary,.059),tintPartner:accentSet?tint(v.accent,.14):P.embCyan1,topFill:topFill,plainEdge:identity?P.plainEdge:withAlpha(c.brandInk,.2)??c.structureEdge,topKicker:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink3:P.topKicker,P.topInk]),topInk:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink:P.topInk,P.topInk])}}function recordsSheetLook(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),tints=brandTints(theme),accentOnFill=raphIdentity(theme)?P.go:sameColour(c.accent,c.primary)?c.onPrimary:c.accent;return theme.brightness==="dark"?/* @__PURE__ */Object.freeze({dark:true,paper:v.paper,ground:c.background,card:v.card,text:v.ink,muted:v.ink3,line:c.structureEdge,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:c.success,goTint:c.badgeBgPositive,alert:v.riskInk,alertDeep:v.riskInk,alertTint:c.badgeBgCritical,watch:c.badgeBgCaution,wind:P.efSkyBlue,tintBlue:c.surfaceSubtle,tintYellow:c.surfaceSubtle,barTrack:c.structureEdge,...tints}):/* @__PURE__ */Object.freeze({dark:false,paper:v.paper,ground:P.efWhite,card:P.efWhite,text:P.efBlack,muted:P.muted,line:P.line,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:P.go,goTint:P.tintGo,alert:P.alert,alertDeep:P.alertDeep,alertTint:P.tintRed,watch:P.watch,wind:P.efSkyBlue,tintBlue:P.tintBlue,tintYellow:P.tintYellow,barTrack:P.barTrack,...tints})}function isRecordsSheetIdentity(theme){return raphIdentity(theme)}function partnerAccentSet(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color;return!same(theme.color.accent,compiled.accent)}function hubLook(theme){let look=recordsSheetLook(theme);if(look.dark)/* @__PURE__ */
793
+ return Object.freeze({dark:true,bg:look.ground,white:look.card,text:look.text,muted:look.muted,line:look.line,charcoal:look.muted,ink:look.ink,fill:look.fill,onFill:look.onFill,accentOnFill:look.accentOnFill,go:look.go,alert:look.alert,alertDeep:look.alertDeep,yellow:look.watch,tintSage:look.tintSage,tintPink:look.tintPartner,tintPinkSoft:look.card,tintBlue:look.tintBlue,tintYellow:look.tintYellow,tintYellowEdge:look.watch,tintRed:look.alertTint,tintGo:look.goTint,icoGrey:look.muted,icoSage:look.chevron,icoBlue:look.wind,barTrack:look.barTrack,pillPlainEdge:look.plainEdge,chartLine:look.text,chartGrid:look.line,chartBand:look.goTint,legacyText:look.text,legacyMuted:look.muted,legacyBorder:look.line,brand:look.ink,brandSoft:withAlpha(look.ink,.1)??look.tintSage});let identity=isRecordsSheetIdentity(theme),brand=identity?APP_HUB_PALETTE.ink:look.ink;/* @__PURE__ */
794
+ return Object.freeze({dark:false,bg:APP_HUB_PALETTE.bg,white:APP_HUB_PALETTE.white,text:APP_HUB_PALETTE.text,muted:APP_HUB_PALETTE.muted,line:APP_HUB_PALETTE.line,charcoal:APP_HUB_PALETTE.charcoal,ink:brand,fill:identity?APP_HUB_PALETTE.ink:look.fill,onFill:identity?APP_HUB_PALETTE.white:look.onFill,accentOnFill:identity?APP_HUB_PALETTE.go:look.accentOnFill,go:APP_HUB_PALETTE.go,alert:APP_HUB_PALETTE.alert,alertDeep:APP_HUB_PALETTE.alertDeep,yellow:APP_HUB_PALETTE.yellow,tintSage:identity?APP_HUB_PALETTE.tintSage:look.tintSage,tintPink:identity||!partnerAccentSet(theme)?APP_HUB_PALETTE.tintPink:look.tintPartner,tintPinkSoft:APP_HUB_PALETTE.tintPinkSoft,tintBlue:APP_HUB_PALETTE.tintBlue,tintYellow:APP_HUB_PALETTE.tintYellow,tintYellowEdge:APP_HUB_PALETTE.tintYellowEdge,tintRed:APP_HUB_PALETTE.tintRed,tintGo:APP_HUB_PALETTE.tintGo,icoGrey:APP_HUB_PALETTE.icoGrey,icoSage:identity?APP_HUB_PALETTE.icoSage:look.chevron,icoBlue:APP_HUB_PALETTE.icoBlue,barTrack:APP_HUB_PALETTE.barTrack,pillPlainEdge:identity?APP_HUB_PALETTE.pillPlainEdge:look.plainEdge,chartLine:APP_HUB.chart.lineColor,chartGrid:APP_HUB.chart.gridColor,chartBand:APP_HUB.chart.bandColor,legacyText:APP_HUB_LEGACY.textPrimary,legacyMuted:APP_HUB_LEGACY.textMuted,legacyBorder:APP_HUB_LEGACY.border,brand:identity?APP_HUB_LEGACY.brand:brand,brandSoft:identity?APP_HUB_LEGACY.brandSoft:withAlpha(brand,.1)??look.tintSage})}var HubContext=createContext(null);function buildKit(theme,handFamily){let look=hubLook(theme),faceOf=key=>key==="hand"?handFamily!==null?{fontFamily:handFamily}:face(theme,"regular"):face(theme,key),cache2=/* @__PURE__ */new Map;return{theme:theme,look:look,type:name=>{let hit=cache2.get(name);if(hit!==void 0)return hit;let t=APP_HUB_TYPE[name],style={...faceOf(t.face),fontSize:t.size,lineHeight:t.lineHeight,color:look[t.color],...t.letterSpacing!==0?{letterSpacing:t.letterSpacing}:{},...t.upper===true?{textTransform:"uppercase"}:{}};return cache2.set(name,style),style},face:faceOf}}function HubKitProvider({handFamily:handFamily,children:children}){let theme=useEverfurTheme(),kit=useMemo(()=>buildKit(theme,handFamily),[theme,handFamily]);/* @__PURE__ */
795
+ return jsx(HubContext.Provider,{value:kit,children:children})}function useHub(){let theme=useEverfurTheme(),own=useMemo(()=>buildKit(theme,null),[theme]);return useContext(HubContext)??own}function HubText({variant:variant="bodySm",color:color,style:style,children:children,...rest}){let{type:type}=useHub();/* @__PURE__ */
796
+ return jsx(Text,{tier:variant==="screenTitle"||variant==="cardTitle"?"heading":variant==="button"||variant==="buttonRow"?"control":variant==="pill"||variant==="labelMono"||variant==="chip"?"compact":"content",...rest,style:[type(variant),color!==void 0?{color:color}:null,style],children:children})}var HIDDEN4={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"};function HubIcon({name:name,size:size=24,color:color,style:style}){let{look:look}=useHub(),c=color??look.ink,glyph;switch(name){case"flask":glyph=/* @__PURE__ */jsx(FlaskGlyph,{size:size,color:c});break;case"flask-sm":glyph=/* @__PURE__ */jsx(FlaskGlyph,{size:size,color:c});break;case"syringe":glyph=/* @__PURE__ */jsx(SyringeGlyph,{size:size,color:c});break;case"calendar":glyph=/* @__PURE__ */jsx(CalendarGlyph,{size:size,color:c});break;case"shield":glyph=/* @__PURE__ */jsx(ShieldGlyph,{size:size,color:c});break;case"folder":glyph=/* @__PURE__ */jsx(FolderGlyph,{size:size,color:c});break;case"clock":glyph=/* @__PURE__ */jsx(ClockFaceGlyph,{size:size,color:c});break;case"clip":glyph=/* @__PURE__ */jsx(ClipboardGlyph,{size:size,color:c});break;case"download":glyph=/* @__PURE__ */jsx(DownloadGlyph2,{size:size,color:c});break;case"upload":glyph=/* @__PURE__ */jsx(UploadArrowGlyph,{size:size,color:c});break;case"thermo":glyph=/* @__PURE__ */jsx(ThermoGlyph,{size:size,color:c});break;case"heart":glyph=/* @__PURE__ */jsx(HeartGlyph,{size:size,color:c});break;case"wind":glyph=/* @__PURE__ */jsx(WindGlyph,{size:size,color:c});break;case"file":glyph=/* @__PURE__ */jsx(FileGlyph,{size:size,color:c});break;case"check":glyph=/* @__PURE__ */jsx(CheckGlyph,{size:size,color:c});break;case"chevron":glyph=/* @__PURE__ */jsx(ChevronGlyph,{size:size,color:c,direction:"right"});break;default:glyph=null}/* @__PURE__ */
797
+ return jsx(View,{style:[{width:size,height:size,alignItems:"center",justifyContent:"center"},style],...HIDDEN4,children:glyph})}function HubCard({title:title,titleEnd:titleEnd,style:style,children:children,testID:testID}){let{look:look}=useHub();/* @__PURE__ */
798
+ return jsxs(View,{style:[{padding:APP_HUB.card.pad,backgroundColor:look.white,borderWidth:APP_HUB.card.border,borderColor:look.line,borderRadius:APP_HUB.card.radius},style],testID:testID,children:[title!==void 0?/* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:APP_HUB.card.headGap,marginBottom:APP_HUB.card.headBottom},children:[
799
+ /* @__PURE__ */jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{flex:1},children:title}),titleEnd]}):null,children]})}function HubPill({label:label,tone:tone="plain",testID:testID}){let{look:look}=useHub(),t={stable:{bg:look.tintGo,fg:look.ink},overdue:{bg:look.white,fg:look.alert,edge:look.alert,w:APP_HUB.pill.edgeThin},soon:{bg:look.white,fg:look.ink,edge:look.tintYellowEdge,w:APP_HUB.pill.edgeThin},later:{bg:look.white,fg:look.muted,edge:look.line,w:APP_HUB.pill.edgeThin},clear:{bg:look.white,fg:look.go,edge:look.go,w:APP_HUB.pill.edgeThick},plain:{bg:look.white,fg:look.ink,edge:look.pillPlainEdge,w:APP_HUB.pill.edgeThick},high:{bg:look.white,fg:look.alert,edge:look.alert,w:APP_HUB.pill.edgeThin}}[tone];/* @__PURE__ */
800
+ return jsx(View,{testID:testID,style:[{alignSelf:"flex-start",maxWidth:"100%",minHeight:APP_HUB.pill.minHeight,paddingHorizontal:APP_HUB.pill.padX,borderRadius:999,justifyContent:"center",backgroundColor:t.bg},t.edge!==void 0?{borderWidth:t.w,borderColor:t.edge}:null],children:/* @__PURE__ */jsx(HubText,{variant:"pill",color:t.fg,numberOfLines:1,children:label})})}function HubButton({label:label,onPress:onPress,variant:variant="primary",size:size="md",icon:icon,block:block=false,bold:bold=false,style:style,accessibilityLabel:accessibilityLabel,testID:testID}){let{look:look,face:faceOf}=useHub(),isText=variant==="text",fg=variant==="primary"?look.onFill:look.ink,h=size==="md"?APP_HUB.button.md:size==="sm"?APP_HUB.button.sm:APP_HUB.button.row,padX=size==="md"?APP_HUB.button.padMd:size==="sm"?APP_HUB.button.padSm:APP_HUB.button.padRow,iconSize=size==="row"?APP_HUB.button.iconRow:size==="sm"?APP_HUB.button.iconSm:APP_HUB.button.iconMd,box3=isText?{flexDirection:"row",alignItems:"center",gap:APP_HUB.button.textGap,minHeight:APP_HUB.button.textMinHeight}:[{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:APP_HUB.button.gap,borderRadius:999,minHeight:h,paddingHorizontal:padX},variant==="primary"?{backgroundColor:look.fill,borderWidth:APP_HUB.button.edge,borderColor:look.white}:{backgroundColor:"transparent",borderWidth:APP_HUB.button.edge,borderColor:look.ink}];/* @__PURE__ */
801
+ return jsxs(Pressable,{onPress:onPress,disabled:onPress===void 0,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label,hitSlop:size==="row"||isText?4:void 0,style:[block?{alignSelf:"stretch"}:null,box3,style],testID:testID,children:[icon!==void 0?/* @__PURE__ */jsx(HubIcon,{name:icon,size:iconSize,color:fg}):null,
802
+ /* @__PURE__ */jsx(HubText,{variant:size==="row"?"buttonRow":"button",color:fg,numberOfLines:1,style:[size==="md"&&!isText?{fontSize:APP_HUB.button.mdLabel}:null,variant==="secondary"&&!bold?faceOf("regular"):null],children:label})]})}function HubChip({label:label,selected:selected,onPress:onPress,testID:testID}){let{look:look}=useHub();/* @__PURE__ */
803
+ return jsx(Pressable,{onPress:onPress,hitSlop:4,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{selected:selected},style:{flexDirection:"row",alignItems:"center",gap:6,borderRadius:999,minHeight:APP_HUB.peek.chipHeight,paddingHorizontal:APP_HUB.peek.chipPadX,borderWidth:1.5,borderColor:selected?look.fill:look.line,backgroundColor:selected?look.fill:look.white},testID:testID,children:/* @__PURE__ */jsx(HubText,{variant:"chip",color:selected?look.onFill:look.ink,numberOfLines:1,children:label})})}function HubRound({icon:icon,rotate:rotate=0,label:label,disabled:disabled,onPress:onPress,testID:testID}){let{look:look}=useHub(),d=APP_HUB.peek.roundButton;/* @__PURE__ */
804
+ return jsx(Pressable,{onPress:onPress,disabled:disabled,hitSlop:4,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{disabled:disabled},style:{width:d,height:d,borderRadius:d/2,alignItems:"center",justifyContent:"center",borderWidth:1.5,borderColor:look.ink,backgroundColor:look.white},testID:testID,children:/* @__PURE__ */jsx(HubIcon,{name:icon,size:18,style:rotate!==0?{transform:[{rotate:`${rotate}deg`}]}:void 0})})}var DAY_MS2=864e5,DUE_SOON_DAYS2=30,WEEKS_WINDOW_DAYS=60,LB_PER_KG2=2.20462,MONTH_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],MONTH_LONG=["January","February","March","April","May","June","July","August","September","October","November","December"],WEEKDAY=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function ms(iso){if(iso==null||iso.trim()==="")return null;let t=Date.parse(iso);return Number.isNaN(t)?null:t}function calendarDay(iso){let t=ms(iso);if(t===null)return null;let at=new Date(t),y=at.getUTCFullYear(),m=at.getUTCMonth(),d=at.getUTCDate();return{y:y,m:m,d:d,ms:Date.UTC(y,m,d)}}function today(nowMs){let n2=new Date(nowMs);return{y:n2.getFullYear(),ms:Date.UTC(n2.getFullYear(),n2.getMonth(),n2.getDate()),weekday:n2.getDay()}}function oneDecimal(value){let r=Math.round(value*10)/10;return Number.isInteger(r)?String(r):r.toFixed(1)}function hubMeta(breed,ageYears,weight){let age=typeof ageYears=="number"&&Number.isFinite(ageYears)&&ageYears>0?hubAge(Math.floor(ageYears*12+1e-9)):null,parts=[breed?.trim()||null,age,weight?.primary??null].filter(p=>p!==null);return parts.length>0?parts.join(" · "):null}var ACRONYMS=/* @__PURE__ */Object.freeze({dhpp:"DHPP",dhlpp:"DHLPP",dhppi:"DHPPi",dapp:"DAPP",dap:"DAP",fvrcp:"FVRCP",felv:"FeLV",fiv:"FIV",hw:"HW",bcs:"BCS","4dx":"4DX"});function humanizeKey(key){return key.split(/[_\s]+/).filter(Boolean).map(w=>ACRONYMS[w.toLowerCase()]??w.charAt(0).toUpperCase()+w.slice(1)).join(" ")}function iconForKey(key){let k=key.toLowerCase();return k.includes("vacc")||k.includes("booster")||k.includes("rabies")||k.includes("dhpp")?"syringe":k.includes("test")||k.includes("screen")||k.includes("fecal")||k.includes("heartworm")||k.includes("worm")?"flask-sm":"calendar"}function hubUpcoming(items,nowMs){let byKey=/* @__PURE__ */new Map;for(let item of items){let key=item.careItemKey?.trim()||item.title,held=byKey.get(key),a=ms(item.dueAt),b=held===void 0?null:ms(held.dueAt);(held===void 0||a!==null&&(b===null||a<b))&&byKey.set(key,item)}let t=today(nowMs);return[...byKey.entries()].map(([key,item])=>{let due=calendarDay(item.dueAt),label=item.careItemKey?.trim()?humanizeKey(item.careItemKey.trim()):item.title;if(due===null)return{at:Number.POSITIVE_INFINITY,row:{key:key,label:label,when:HUB_COPY.noDueDate,tone:"upcoming",icon:iconForKey(key),pill:{label:HUB_COPY.later,tone:"later"}}};let diff=Math.round((ms(item.dueAt)-nowMs)/DAY_MS2),tone=diff<0?"overdue":diff<=DUE_SOON_DAYS2?"dueSoon":"upcoming",relative=diff<0?HUB_COPY.overdueBy(-diff):diff===0?HUB_COPY.dueToday:HUB_COPY.dueIn(diff),shortDue=`${MONTH_SHORT[due.m]} ${due.d}`,days=Math.round((due.ms-t.ms)/DAY_MS2),when;tone==="overdue"||days<0?when=HUB_COPY.withDue(relative,shortDue):days===0?when=relative:days<=6?when=new Date(due.ms).getUTCDay()>t.weekday?HUB_COPY.thisDay(HUB_COPY.dueOn(shortDue),WEEKDAY[new Date(due.ms).getUTCDay()]):HUB_COPY.dueOn(shortDue):days<WEEKS_WINDOW_DAYS?when=HUB_COPY.inWeeks(HUB_COPY.dueOn(shortDue),Math.round(days/7)):when=HUB_COPY.dueOn(due.y===t.y?MONTH_LONG[due.m]:`${MONTH_LONG[due.m]} ${due.y}`);let pill=tone==="dueSoon"?{label:HUB_COPY.dueSoon,tone:"soon"}:tone==="upcoming"?{label:HUB_COPY.later,tone:"later"}:null;return{at:due.ms,row:{key:key,label:label,when:when,tone:tone,icon:iconForKey(key),pill:pill}}}).sort((a,b)=>a.at-b.at).slice(0,APP_HUB.upcoming.maxRows).map(r=>r.row)}function hubTiles(record,markers,depth,timeline){let summaryTotal=markers!==null&&!markers.withheld?markers.summary?.totalMarkers??markers.markers.length:0,labResults=record!==null&&!record.withheld?record.entities.filter(e=>e.category==="lab_result").length:0,labsTotal=summaryTotal+labResults,labsNoun=labResults>0?HUB_COPY.results(labsTotal):HUB_COPY.markers(labsTotal),encounters=depth!==null&&!depth.withheld?depth.encounters:[],visits=timeline!==null&&!timeline.withheld?timeline.visits:[],latest=[...encounters.map(e=>calendarDay(e.date)),...encounters.length>0?[]:visits.map(v=>calendarDay(v.visitDate))].filter(d=>d!==null).sort((a,b)=>b.ms-a.ms)[0]??null,visitDate=latest===null?null:`${String(latest.m+1).padStart(2,"0")}.${String(latest.d).padStart(2,"0")}.${latest.y}`,rails=timeline!==null&&!timeline.withheld?timeline.visits.length+timeline.vaccines.length+timeline.weights.length+timeline.medications.length:0,series=record!==null&&!record.withheld?record.entitySeries.filter(s=>/^(medication|problem)[:|]/.test(s.key)&&s.points.length>0).length:0;return{labsTotal:labsTotal,labsNoun:labsNoun,screeningsPill:null,visitDate:visitDate,timelineCount:rails+series}}function hubWeight(record,timeline,unit){let fromTimeline=timeline!==null&&!timeline.withheld?timeline.weights.filter(w=>w.weightKg!==null&&Number.isFinite(w.weightKg)).map(w=>({kg:w.weightKg,date:w.observedOn})):[],fromRecord=record!==null&&!record.withheld?record.entities.filter(e=>e.category==="body_weight"&&e.value!==null).map(e=>{let v=Number(e.value);return{kg:/lb/i.test(e.unit??"")?v/LB_PER_KG2:v,date:e.observedAt}}).filter(p=>Number.isFinite(p.kg)&&p.kg>0):[],raw=(fromTimeline.length>0?fromTimeline:fromRecord).slice().sort((a,b)=>(ms(a.date)??0)-(ms(b.date)??0));if(raw.length===0)return null;let kgs=raw.map(p=>p.kg),band=null;if(kgs.length>=2){let sorted=kgs.slice().sort((a,b)=>a-b),mid=Math.floor(sorted.length/2),center=sorted.length%2===1?sorted[mid]:(sorted[mid-1]+sorted[mid])/2;center>0&&(band={lowKg:center*(1-APP_HUB.chart.bandPct),highKg:center*(1+APP_HUB.chart.bandPct)})}let points=raw.map(p=>({...p,status:band===null?null:p.kg>band.highKg?"over":p.kg<band.lowKg?"under":"in"})),latest=kgs[kgs.length-1],lb2=`${oneDecimal(latest*LB_PER_KG2)} lb`,kg=`${oneDecimal(latest)} kg`;return{primary:unit==="kg"?kg:lb2,secondary:unit==="kg"?lb2:kg,unit:unit,points:points,band:band}}function kitMonthLabel(date2){let t=ms(date2);if(t===null)return null;let d=new Date(t);return`${d.getUTCMonth()+1}/${String(d.getUTCFullYear()%100).padStart(2,"0")}`}function monthLabel(date2){let t=ms(date2);if(t===null)return null;let d=new Date(t);return`${d.getUTCMonth()+1}/${d.getUTCFullYear()}`}var clamp=(v,lo,hi)=>Math.max(lo,Math.min(hi,v));function anchorClampX(x,width,anchor,safeLeft,safeRight){return anchor==="start"?clamp(x,safeLeft,Math.max(safeLeft,safeRight-width)):anchor==="end"?clamp(x,Math.min(safeRight,safeLeft+width),safeRight):clamp(x,safeLeft+width/2,Math.max(safeLeft+width/2,safeRight-width/2))}function pickIndices(count,max){if(count<=0)return[];if(count<=max)return Array.from({length:count},(_,i)=>i);let out=/* @__PURE__ */new Set;for(let i=0;i<max;i+=1)out.add(Math.round(i*(count-1)/(max-1)));return[...out]}var MAX_VALUE_LABELS=8,VALUE_ASCENT_RATIO=.82,VALUE_TOP_PAD=2,AXIS_CHAR_RATIO=.6;function hubChart(weight,width){let G=APP_HUB.chart,plotTop=G.plotTop,plotBottom=G.height-G.axisBand,plotH=plotBottom-plotTop,toShown=kg=>weight.unit==="kg"?kg:kg*LB_PER_KG2,points=weight.points.slice(-36),values=points.map(p=>p.kg),yOf,yBandTop=0,yBandBottom=0,band=weight.band,hasBand=band!==null&&band.highKg>band.lowKg;if(hasBand){let mid=(band.highKg+band.lowKg)/2,half=(band.highKg-band.lowKg)/2,reach=values.reduce((m,v)=>Math.max(m,Math.abs(v-mid)),0),domainHalf=Math.max(half/(G.bandTo-G.bandFrom),reach/G.reach),top=mid+domainHalf;yOf=v=>plotTop+(top-v)/(2*domainHalf)*plotH,yBandTop=yOf(band.highKg),yBandBottom=yOf(band.lowKg)}else{let lo=Math.min(...values),hi=Math.max(...values);lo===hi&&(lo-=1,hi+=1);let pad=(hi-lo)*.15;lo-=pad,hi+=pad,yOf=v=>plotBottom-(v-lo)/(hi-lo)*plotH}let dataLeft=hasBand?G.dataLeft:64,plotLeft=hasBand?G.plotLeft:12,dataRight=width-G.rightInset,n2=points.length,colX=i=>n2<=1?(dataLeft+dataRight)/2:dataLeft+i/(n2-1)*(dataRight-dataLeft),labels=points.map(p=>oneDecimal(toShown(p.kg))),maxChars=labels.reduce((m,t)=>Math.max(m,t.length),1),pitch=n2>1?(dataRight-dataLeft)/(n2-1):dataRight-dataLeft,valueFont=clamp(Math.min(G.labelMax,(pitch-G.edgePad)/(maxChars*G.labelCharWidth)),G.labelMin,G.labelMax),dots=points.map((p,i)=>{let x=colX(i),y=yOf(p.kg),label=labels[i],anchor=i===0?"start":i===n2-1?"end":"middle",ascent=valueFont*VALUE_ASCENT_RATIO,maxBaseline=plotBottom-2,below=y+G.dot+G.labelGap+ascent,preferBelow=p.status==="under"&&below<=maxBaseline,labelBaseline=clamp(preferBelow?below:y-G.dot-G.labelGap,VALUE_TOP_PAD+ascent,maxBaseline),labelX=anchorClampX(x,label.length*G.labelCharWidth*valueFont,anchor,G.edgePad,width-G.edgePad);return{x:x,y:y,status:p.status,label:label,labelX:labelX,labelAnchor:anchor,labelBaseline:labelBaseline,spoken:HUB_COPY.pointLabel(monthLabel(p.date),label,weight.unit)}}),months=pickIndices(n2,G.maxTicks).flatMap(i=>{let label=hasBand?kitMonthLabel(points[i].date):monthLabel(points[i].date);if(label===null)return[];let anchor=i===0?"start":i===n2-1?"end":"middle";return[{x:anchorClampX(colX(i),label.length*AXIS_CHAR_RATIO*G.monthSize,anchor,G.edgePad,width-G.edgePad),anchor:anchor,label:label}]}),lineH=G.legendLine,baselines=(lines,top,bottom)=>{let h=lines*lineH,start=clamp((top+bottom)/2-h/2,0,Math.max(0,plotBottom-h));return Array.from({length:lines},(_,i)=>start+i*lineH+lineH/2+G.legendSize*.35)},legend=hasBand?[{zone:"over",lines:HUB_COPY.legendOver,top:plotTop,bottom:yBandTop},{zone:"in",lines:HUB_COPY.legendStable,top:yBandTop,bottom:yBandBottom},{zone:"under",lines:HUB_COPY.legendUnder,top:yBandBottom,bottom:plotBottom}].map(z11=>({zone:z11.zone,lines:z11.lines,baselines:baselines(z11.lines.length,z11.top,z11.bottom)})):[],shown=values.map(toShown),latest=shown[shown.length-1]??0,first=shown[0]??0,trend=latest>first?"rising":latest<first?"falling":"steady",summary=HUB_COPY.trendSummary(shown.length,oneDecimal(latest),trend,hasBand?oneDecimal(toShown(band.lowKg)):null,hasBand?oneDecimal(toShown(band.highKg)):null);return{width:width,hasBand:hasBand,yBandTop:yBandTop,yBandBottom:yBandBottom,plotTop:plotTop,plotBottom:plotBottom,plotLeft:plotLeft,dataRight:dataRight,cols:points.map((_,i)=>colX(i)),dots:dots,showValues:n2<=MAX_VALUE_LABELS,valueFont:valueFont,months:months,legend:legend,summary:summary}}function hubOnFile(record){if(record===null||record.withheld)return[];let bySource=/* @__PURE__ */new Map;for(let doc of Object.values(record.documents)){let name=documentTitle(doc),entry=bySource.get(name)??{pages:0,latest:null};entry.pages+=doc.pageCount!==null&&doc.pageCount>0?doc.pageCount:0,doc.receivedAt!==null&&ms(doc.receivedAt)!==null&&(entry.latest===null||doc.receivedAt>entry.latest)&&(entry.latest=doc.receivedAt),bySource.set(name,entry)}return[...bySource.entries()].sort(([,a],[,b])=>(a.latest??"").localeCompare(b.latest??"")).map(([name,e])=>{let day=e.latest!==null?new Date(ms(e.latest)):null,parts=[e.pages>0?HUB_COPY.pages(e.pages):null,day!==null?`${MONTH_SHORT[day.getMonth()]} ${day.getDate()}`:null].filter(p=>p!==null);return{key:name,name:name,meta:parts.length>0?parts.join(" · "):null}})}function recordsDate(iso){let t=ms(iso);if(t===null)return null;let d=new Date(t);return`${MONTH_SHORT[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`}function arcGeometry(width){let scale=width/(RAPH_RN_SAY.viewBox[2]-RAPH_RN_SAY.viewBox[0]),font=RAPH_RN_SAY.fontSize*scale,line2=Math.round(font*1.25),{x0:x0,y0:y0,cx:cx,cy:cy,x1:x1,y1:y1}=RAPH_RN_SAY.path,pt=t=>{let u=1-t;return[(u*u*x0+2*u*t*cx+t*t*x1)*scale,(u*u*y0+2*u*t*cy+t*t*y1)*scale]},STEPS=120,table=[{len:0,t:0}],[px,py]=pt(0),total=0;for(let i=1;i<=STEPS;i+=1){let t=i/STEPS,[x,y]=pt(t);total+=Math.hypot(x-px,y-py),table.push({len:total,t:t}),px=x,py=y}let at=len=>{let clamped=Math.min(total,Math.max(0,len)),i=1;for(;i<table.length-1&&table[i].len<clamped;)i+=1;let a=table[i-1],b=table[i],t=a.t+(b.t-a.t)*((clamped-a.len)/Math.max(1e-6,b.len-a.len)),[x,y]=pt(t),u=1-t,dx=2*u*(cx-x0)+2*t*(x1-cx),dy=2*u*(cy-y0)+2*t*(y1-cy);return{x:x,y:y,angle:Math.atan2(dy,dx)}};return{width:width,boxH:(RAPH_RN_SAY.viewBox[3]-RAPH_RN_SAY.viewBox[1])*scale,font:font,line:line2,baseline:(line2-font)/2+font*.8,length:total,at:at}}var ARC=arcGeometry(RAPH_RN_SAY.width);function sayArcAt(width){return width===RAPH_RN_SAY.width?ARC:arcGeometry(width)}function ArcLine({line:line2,text:text4,geom:geom,opacity:opacity}){let chars=useMemo(()=>Array.from(line2),[line2]),[widths,setWidths]=useState(()=>chars.map(()=>null)),onMeasure=i=>e=>{let w=e.nativeEvent.layout.width;setWidths(prev=>prev[i]===w?prev:prev.map((v,k)=>k===i?w:v))},ready=widths.every(w=>w!==null),placed=null;if(ready){let ws=widths,total=ws.reduce((a,b)=>a+b,0),run=geom.length/2-total/2;placed=chars.map((ch,i)=>{let w=ws[i],p=geom.at(run+w/2);run+=w;let up=geom.baseline-geom.line/2,cx=p.x+Math.sin(p.angle)*up,cy=p.y-Math.cos(p.angle)*up;/* @__PURE__ */
805
+ return jsx(Text,{allowFontScaling:false,style:[text4,{position:"absolute",left:cx-w/2,top:cy-geom.line/2,width:w,textAlign:"center",transform:[{rotate:`${p.angle}rad`}]}],children:ch},i)})}/* @__PURE__ */
806
+ return jsxs(Animated.View,{style:{position:"absolute",left:0,top:0,right:0,bottom:0,opacity:opacity},children:[
807
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:0,top:0,width:geom.width*4,flexDirection:"row",opacity:0},children:chars.map((ch,i)=>/* @__PURE__ */jsx(Text,{allowFontScaling:false,style:[text4,{flexShrink:0}],onLayout:onMeasure(i),children:ch},i))}),placed]})}var HIDDEN5={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"},SAY=sayArcAt(APP_HUB.hero.sayWidth),GRASS_H=APP_HUB.hero.stageHeight*APP_HUB.hero.grassFraction;function vitalNumber(value){let n2=Number(value);return value.trim()!==""&&Number.isFinite(n2)?String(n2):value}var SAY_CYCLE_MS=44e3,SAY_FADE_MS=1100,SAY_HOLD_MS=1188,SAY_FIRST_MS=1200,SAY_STEP_MS=3600;function SayPhrase({text:text4,index:index,family:family}){let{look:look}=useHub(),opacity=useRef(new Animated.Value(0)).current;return useEffect(()=>{opacity.setValue(0);let ease=Easing.inOut(Easing.ease),run=Animated.sequence([Animated.delay(SAY_FIRST_MS+index*SAY_STEP_MS),Animated.loop(Animated.sequence([Animated.timing(opacity,{toValue:1,duration:SAY_FADE_MS,easing:ease,useNativeDriver:true}),Animated.delay(SAY_HOLD_MS),Animated.timing(opacity,{toValue:0,duration:SAY_FADE_MS,easing:ease,useNativeDriver:true}),Animated.delay(SAY_CYCLE_MS-SAY_FADE_MS*2-SAY_HOLD_MS)]))]);return run.start(),()=>run.stop()},[index,opacity]),/* @__PURE__ */jsx(ArcLine,{line:text4,geom:SAY,opacity:opacity,text:{fontFamily:family,fontWeight:"500",fontSize:SAY.font,lineHeight:SAY.line,color:look.ink}})}function HubSay({family:family}){let{look:look}=useHub();return useEverfurTheme().motion.reducedMotion?/* @__PURE__ */jsx(ArcLine,{line:HUB_COPY.sayLine,geom:SAY,opacity:1,text:{fontFamily:family,fontWeight:"500",fontSize:SAY.font,lineHeight:SAY.line,color:look.ink}}):/* @__PURE__ */jsx(Fragment,{children:HUB_COPY.sayPhrases.map((text4,index)=>/* @__PURE__ */jsx(SayPhrase,{text:text4,index:index,family:family},text4))})}function HubHero({name:name,meta:meta,stage:stage,say:say,vitals:vitals,vitalsName:vitalsName,renderStage:renderStage}){let{look:look,face:face2}=useHub(),list=vitals.length>0?/* @__PURE__ */jsx(View,{style:stage!==void 0?{position:"absolute",top:APP_HUB.hero.vitalsTop,left:APP_HUB.hero.vitalsLeft}:{paddingHorizontal:APP_HUB.hero.vitalsLeft,marginTop:4},accessibilityLabel:HUB_COPY.vitalsLabel(vitalsName),testID:"everfur-records-sheet-vitals",children:vitals.map(v=>{let value=vitalNumber(v.value),nameWord=v.kind==="temp"?HUB_COPY.temperature:v.kind==="heart"?HUB_COPY.heartRate:HUB_COPY.breathing,icon=v.kind==="temp"?"thermo":v.kind==="heart"?"heart":"wind",color=v.kind==="temp"?look.ink:v.kind==="heart"?look.alert:look.icoBlue;/* @__PURE__ */
808
+ return jsxs(View,{accessible:true,accessibilityLabel:HUB_COPY.vitalLabel(nameWord,value,v.unit??""),style:{flexDirection:"row",alignItems:"center",gap:APP_HUB.hero.vitalGap,minHeight:APP_HUB.hero.vitalMinHeight,paddingHorizontal:APP_HUB.hero.vitalPadX},children:[
809
+ /* @__PURE__ */jsx(HubIcon,{name:icon,size:APP_HUB.hero.vitalIcon,color:color}),
810
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",color:look.text,style:{fontSize:APP_HUB.hero.vitalValueSize},children:value}),v.unit?/* @__PURE__ */jsx(HubText,{variant:"fine",style:[face2("medium"),{fontSize:APP_HUB.hero.vitalUnitSize}],children:v.unit}):null]},v.kind)})}):null,hand=stage?.handFontFamily??null;/* @__PURE__ */
811
+ return jsxs(View,{style:{marginTop:4,marginHorizontal:-APP_HUB.screen.padX},testID:"everfur-records-hub-hero",children:[
812
+ /* @__PURE__ */jsx(View,{style:{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:APP_HUB.screen.padX},children:/* @__PURE__ */jsx(HubText,{variant:"screenTitle",accessibilityRole:"header",numberOfLines:1,testID:"everfur-records-sheet-name",style:[face2("bold"),{flexShrink:1,fontSize:APP_HUB.hero.nameSize,lineHeight:APP_HUB.hero.nameLineHeight,letterSpacing:APP_HUB.hero.nameTracking}],children:name})}),meta!==null?/* @__PURE__ */jsx(HubText,{variant:"fine",testID:"everfur-records-sheet-meta",style:{marginTop:APP_HUB.hero.metaTop,paddingHorizontal:APP_HUB.screen.padX,lineHeight:APP_HUB.hero.metaLineHeight,textTransform:"uppercase",letterSpacing:APP_HUB.hero.metaTracking},children:meta}):null,stage!==void 0?/* @__PURE__ */jsxs(View,{style:{height:APP_HUB.hero.stageHeight,marginTop:APP_HUB.hero.stageTop,overflow:"hidden"},testID:"everfur-records-sheet-stage",children:[
813
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:0,right:0,bottom:0,height:GRASS_H,overflow:"hidden"},...HIDDEN5,children:/* @__PURE__ */jsx(Image,{source:stage.grassSource,style:{position:"absolute",top:0,left:0,right:0,height:"100%"},resizeMode:"cover"})}),
814
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:0,right:0,top:say?APP_HUB.hero.sayHeight-4:APP_HUB.hero.petTop,bottom:APP_HUB.hero.petBottom,alignItems:"center"},...HIDDEN5,children:/* @__PURE__ */jsx(Image,{source:stage.petSource,style:{width:"100%",height:"100%"},resizeMode:"contain"})}),say&&hand!==null?/* @__PURE__ */jsx(View,{style:{position:"absolute",top:0,left:"50%",width:APP_HUB.hero.sayWidth,height:APP_HUB.hero.sayHeight,marginLeft:-APP_HUB.hero.sayWidth/2},testID:"everfur-records-sheet-say",...HIDDEN5,children:/* @__PURE__ */jsx(HubSay,{family:hand})}):null,list,
815
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:0,right:0,bottom:0,height:APP_HUB.hero.lawnOverlap,borderTopLeftRadius:APP_HUB.hero.lawnRadius,borderTopRightRadius:APP_HUB.hero.lawnRadius,backgroundColor:look.white},...HIDDEN5})]}):/* @__PURE__ */jsxs(Fragment,{children:[renderStage!==void 0?/* @__PURE__ */jsx(HostRender,{render:renderStage,fallback:null,resetKey:name}):null,list]})]})}function HubPrompt({title:title,canAct:canAct,canRequest:canRequest,onRequest:onRequest,onUpload:onUpload}){/* @__PURE__ */
816
+ return jsxs(HubCard,{title:title,testID:"everfur-records-records-prompt",children:[
817
+ /* @__PURE__ */jsx(HubText,{variant:"bodySm",children:HUB_COPY.moreThanOneClinic}),canAct&&canRequest?/* @__PURE__ */jsx(HubButton,{label:HUB_COPY.requestFromClinic,icon:"download",block:true,onPress:onRequest,style:{marginTop:12},testID:"everfur-records-sheet-none-request"}):null,canAct?/* @__PURE__ */jsx(HubButton,{label:HUB_COPY.uploadDocument,icon:"upload",variant:"secondary",block:true,onPress:onUpload,style:{marginTop:12},testID:"everfur-records-sheet-none-upload"}):null]})}function HubUpcoming({rows:rows,items:items,onViewAll:onViewAll,renderAction:renderAction}){let{look:look}=useHub(),U=APP_HUB.upcoming;/* @__PURE__ */
818
+ return jsx(HubCard,{title:HUB_COPY.upcomingCare,titleEnd:onViewAll!==void 0?/* @__PURE__ */jsx(HubButton,{label:HUB_COPY.viewAll,variant:"text",onPress:onViewAll,testID:"everfur-records-sheet-upcoming-all"}):void 0,testID:"everfur-records-hub-upcoming",children:/* @__PURE__ */jsx(View,{style:{gap:U.listGap,marginHorizontal:-U.bleed},children:rows.map((row,index)=>{let overdue=row.tone==="overdue",item=items.get(row.key);/* @__PURE__ */
819
+ return jsxs(View,{style:[{flexDirection:"row",alignItems:"center",gap:U.rowGap,paddingVertical:U.rowPadY,paddingHorizontal:U.rowPadX,borderRadius:U.rowRadius},overdue?{backgroundColor:look.tintRed}:null],testID:`everfur-records-sheet-due-${index}`,children:[
820
+ /* @__PURE__ */jsxs(View,{style:{flex:1,flexDirection:"row",alignItems:"center",gap:U.rowGap},accessible:true,accessibilityLabel:`${row.label}, ${row.when}`,children:[
821
+ /* @__PURE__ */jsx(HubIcon,{name:row.icon,size:U.icon,color:overdue?look.alert:look.icoGrey}),
822
+ /* @__PURE__ */jsxs(View,{style:{flex:1,minWidth:0},children:[
823
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",numberOfLines:2,color:overdue?look.alertDeep:void 0,style:{fontSize:17,lineHeight:22},children:row.label}),
824
+ /* @__PURE__ */jsx(HubText,{variant:"fine",numberOfLines:2,color:overdue?look.alert:void 0,children:row.when})]})]}),overdue&&renderAction!==void 0&&item!==void 0?/* @__PURE__ */jsx(HostRender,{render:()=>renderAction(item),fallback:null,resetKey:item}):row.pill!==null?/* @__PURE__ */jsx(HubPill,{label:row.pill.label,tone:row.pill.tone}):null]},row.key)})})})}function HubUpcomingEmpty({name:name}){/* @__PURE__ */
825
+ return jsx(HubCard,{title:HUB_COPY.upcomingCare,testID:"everfur-records-hub-upcoming-empty",children:/* @__PURE__ */jsx(HubText,{variant:"bodySm",children:HUB_COPY.nothingDue(name)})})}function Tile({tint:tint,icon:icon,title:title,label:label,foot:foot,onOpen:onOpen,testID:testID}){let{look:look}=useHub(),G=APP_HUB.tiles,inner=/* @__PURE__ */jsxs(Fragment,{children:[
826
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},children:[
827
+ /* @__PURE__ */jsx(HubIcon,{name:icon,size:G.icon}),onOpen!==void 0?/* @__PURE__ */jsx(HubIcon,{name:"chevron",size:G.chevron,color:look.icoSage}):null]}),
828
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",style:{lineHeight:G.titleLineHeight},children:title}),
829
+ /* @__PURE__ */jsx(View,{style:{minHeight:G.footMinHeight,flexDirection:"row",alignItems:"center"},children:foot})]}),box3={padding:G.pad,borderRadius:G.radius,gap:G.innerGap,backgroundColor:tint};/* @__PURE__ */
830
+ return jsx(View,{style:{width:"48%",flexGrow:1},children:onOpen!==void 0?/* @__PURE__ */jsx(Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:label,style:box3,testID:testID,children:inner}):/* @__PURE__ */jsx(View,{style:box3,accessible:true,accessibilityLabel:label,testID:testID,children:inner})})}function HubTilesSection({tiles:tiles,labsUnknown:labsUnknown,onOpenLabs:onOpenLabs,onOpenScreenings:onOpenScreenings,onOpenVisits:onOpenVisits,onOpenTimeline:onOpenTimeline}){let{look:look}=useHub(),G=APP_HUB.tiles;/* @__PURE__ */
831
+ return jsxs(View,{style:{marginTop:G.top},testID:"everfur-records-hub-records",children:[
832
+ /* @__PURE__ */jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{marginBottom:G.titleBottom},children:HUB_COPY.recordsHistory}),
833
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",gap:G.gap},children:[
834
+ /* @__PURE__ */jsx(Tile,{tint:look.tintSage,icon:"flask",title:HUB_COPY.labs,label:labsUnknown?HUB_COPY.labsA11yUnknown:HUB_COPY.labsA11y(tiles.labsTotal,tiles.labsNoun),onOpen:onOpenLabs,testID:"everfur-records-sheet-tile-labs",foot:/* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"baseline",gap:G.countGap},children:[
835
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",style:{fontSize:G.numSize,lineHeight:G.numLineHeight,letterSpacing:G.numTracking},testID:"everfur-records-sheet-labs-count",children:labsUnknown?HUB_COPY.labsCountUnknown:String(tiles.labsTotal)}),labsUnknown?null:/* @__PURE__ */jsx(HubText,{variant:"fine",children:tiles.labsNoun})]})}),
836
+ /* @__PURE__ */jsx(Tile,{tint:look.tintPink,icon:"shield",title:HUB_COPY.screenings,label:HUB_COPY.screeningsA11y(tiles.screeningsPill?.label??null),onOpen:onOpenScreenings,testID:"everfur-records-sheet-tile-screenings",foot:tiles.screeningsPill!==null?/* @__PURE__ */jsx(HubPill,{label:tiles.screeningsPill.label,tone:tiles.screeningsPill.tone}):null}),
837
+ /* @__PURE__ */jsx(Tile,{tint:look.tintBlue,icon:"folder",title:HUB_COPY.visits,label:HUB_COPY.visitsA11y(tiles.visitDate),onOpen:onOpenVisits,testID:"everfur-records-sheet-tile-record",foot:tiles.visitDate!==null?/* @__PURE__ */jsx(HubPill,{label:tiles.visitDate,tone:"plain"}):null}),
838
+ /* @__PURE__ */jsx(Tile,{tint:look.tintYellow,icon:"clock",title:HUB_COPY.timeline,label:HUB_COPY.timelineA11y(tiles.timelineCount),onOpen:onOpenTimeline,testID:"everfur-records-sheet-tile-timeline",foot:tiles.timelineCount>0?/* @__PURE__ */jsx(HubPill,{label:HUB_COPY.events(tiles.timelineCount),tone:"plain"}):null})]})]})}var BASELINE=.85;function ChartText({x:x,y:y,anchor:anchor,size:size,style:style,children:children}){let top=y-size*BASELINE,W=160,place=anchor==="start"?{left:x}:anchor==="end"?{left:x-W,width:W,textAlign:"right"}:{left:x-W/2,width:W,textAlign:"center"};/* @__PURE__ */
839
+ return jsx(Text,{allowFontScaling:false,numberOfLines:1,style:[style,{position:"absolute",top:top,fontSize:size,lineHeight:size},place],children:children})}function WeightChart({weight:weight}){let{look:look,face:face2}=useHub(),[width,setWidth]=useState(0),[selected,setSelected]=useState(null),onLayout=e=>{let w=Math.round(e.nativeEvent.layout.width);w>0&&w!==width&&setWidth(w)},G=APP_HUB.chart;if(width===0)/* @__PURE__ */return jsx(View,{onLayout:onLayout,style:{height:G.height}});let c=hubChart(weight,width),ring=G.dot+G.dotRing/2,pitch=c.cols.length>1?c.cols[1]-c.cols[0]:c.dataRight-(c.cols[0]??0),pick2=selected!==null?c.dots[selected]??null:null;/* @__PURE__ */
840
+ return jsxs(View,{onLayout:onLayout,style:{height:G.height},children:[
841
+ /* @__PURE__ */jsxs(View,{accessible:true,accessibilityRole:"image",accessibilityLabel:c.summary,style:{position:"absolute",left:0,top:0,right:0,bottom:0},children:[c.hasBand?/* @__PURE__ */jsxs(Fragment,{children:[
842
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:0,top:c.plotTop,width:G.indicatorWidth,height:c.plotBottom-c.plotTop,borderRadius:G.indicatorWidth/2,backgroundColor:look.chartGrid}}),
843
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:0,top:c.yBandTop,width:G.indicatorWidth,height:Math.max(0,c.yBandBottom-c.yBandTop),borderRadius:G.indicatorWidth/2,backgroundColor:look.go}}),
844
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",left:c.plotLeft,top:c.yBandTop,width:Math.max(0,c.dataRight-c.plotLeft),height:Math.max(0,c.yBandBottom-c.yBandTop),backgroundColor:look.chartBand}})]}):null,c.cols.map((x,i)=>/* @__PURE__ */jsx(View,{style:{position:"absolute",left:x-.5,top:c.plotTop,width:1,height:c.plotBottom-c.plotTop,backgroundColor:look.chartGrid}},`g-${i}`)),c.hasBand?[c.yBandTop,c.yBandBottom].map((y,i)=>/* @__PURE__ */jsx(View,{style:{position:"absolute",left:c.plotLeft,top:y-.5,width:Math.max(0,c.dataRight-c.plotLeft),height:1,backgroundColor:look.line}},`e-${i}`)):null,c.dots.slice(1).map((b,i)=>{let a=c.dots[i],len=Math.hypot(b.x-a.x,b.y-a.y),w=G.lineWidth;/* @__PURE__ */
845
+ return jsx(View,{style:{position:"absolute",left:(a.x+b.x)/2-(len+w)/2,top:(a.y+b.y)/2-w/2,width:len+w,height:w,borderRadius:w/2,backgroundColor:look.chartLine,transform:[{rotate:`${Math.atan2(b.y-a.y,b.x-a.x)}rad`}]}},`l-${i}`)}),c.dots.map((d,i)=>/* @__PURE__ */jsx(View,{style:{position:"absolute",left:d.x-ring,top:d.y-ring,width:ring*2,height:ring*2,borderRadius:ring,borderWidth:G.dotRing,borderColor:look.white,backgroundColor:d.status==="over"||d.status==="under"?look.yellow:look.go}},`d-${i}`)),c.showValues?c.dots.map((d,i)=>/* @__PURE__ */jsx(ChartText,{x:d.labelX,y:d.labelBaseline,anchor:d.labelAnchor,size:c.valueFont,style:[face2("bold"),{color:look.text}],children:d.label},`v-${i}`)):null,c.legend.flatMap(z11=>z11.lines.map((line2,i)=>/* @__PURE__ */jsx(ChartText,{x:G.legendX,y:z11.baselines[i],anchor:"start",size:G.legendSize,style:[face2("monoBold"),{color:look.charcoal,letterSpacing:G.legendTracking}],children:line2},`k-${z11.zone}-${i}`))),c.months.map((m,i)=>/* @__PURE__ */jsx(ChartText,{x:m.x,y:G.monthY,anchor:m.anchor,size:G.monthSize,style:[face2("mono"),{color:look.muted}],children:m.label},`m-${i}`))]}),c.dots.map((d,i)=>{let half=pitch/2;/* @__PURE__ */
846
+ return jsx(Pressable,{onPress:()=>setSelected(cur=>cur===i?null:i),accessibilityRole:"button",accessibilityLabel:d.spoken,style:{position:"absolute",left:Math.max(0,d.x-half),top:c.plotTop,width:Math.max(1,half*2),height:Math.max(1,c.plotBottom-c.plotTop)}},`t-${i}`)}),pick2!==null?
847
+ /* @__PURE__ */jsx(View,{pointerEvents:"none",style:{position:"absolute",width:92,height:40,borderRadius:8,paddingHorizontal:8,paddingVertical:5,backgroundColor:look.chartLine,alignItems:"center",justifyContent:"center",left:Math.min(Math.max(pick2.x-46,G.edgePad),Math.max(G.edgePad,width-92-G.edgePad)),top:pick2.y-40-G.dot-4>=0?pick2.y-40-G.dot-4:pick2.y+G.dot+4},children:/* @__PURE__ */jsx(Text,{style:[face2("bold"),{fontSize:13,color:look.white}],children:`${pick2.label} ${weight.unit}`})}):null]})}function HubWeightCard({weight:weight,name:name}){let{look:look}=useHub(),W=APP_HUB.weight;return weight===null?/* @__PURE__ */jsx(HubCard,{title:HUB_COPY.weight,testID:"everfur-records-hub-weight",children:/* @__PURE__ */jsx(HubText,{variant:"bodySm",children:HUB_COPY.noWeights(name)})}):/* @__PURE__ */jsxs(HubCard,{title:HUB_COPY.weight,testID:"everfur-records-hub-weight",children:[
848
+ /* @__PURE__ */jsx(View,{style:{gap:W.headGap,marginBottom:W.headBottom},children:/* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"baseline",gap:W.numGap},children:[
849
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",testID:"everfur-records-sheet-weight-latest",style:{fontSize:W.numSize,lineHeight:W.numLineHeight,letterSpacing:W.numTracking},children:weight.primary}),weight.secondary!==null?/* @__PURE__ */jsx(HubText,{variant:"bodySm",color:look.muted,children:weight.secondary}):null]})}),weight.points.length>=2?/* @__PURE__ */jsxs(View,{children:[
850
+ /* @__PURE__ */jsx(WeightChart,{weight:weight}),weight.band!==null?/* @__PURE__ */jsx(HubText,{variant:"fine",children:HUB_COPY.estimatedRange}):null]}):null]})}function HubAddRecords({words:words2,sources:sources,canRequest:canRequest,onRequest:onRequest,onUpload:onUpload}){let{look:look}=useHub(),A=APP_HUB.add;/* @__PURE__ */
851
+ return jsx(HubCard,{style:{backgroundColor:look.tintPinkSoft},testID:"everfur-records-hub-add-records",children:/* @__PURE__ */jsxs(View,{style:{gap:A.gap},children:[
852
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:A.headGap},children:[
853
+ /* @__PURE__ */jsx(HubIcon,{name:"clip",size:A.icon,color:look.alert}),
854
+ /* @__PURE__ */jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{flex:1},children:HUB_COPY.addRecords(words2.name)})]}),
855
+ /* @__PURE__ */jsx(HubText,{variant:"bodySm",children:HUB_COPY.moreThanOneClinic}),sources.length>0?/* @__PURE__ */jsx(View,{style:{gap:A.sourcesGap,marginTop:A.sourcesTop},accessibilityLabel:HUB_COPY.onFileNow,testID:"everfur-records-sheet-sources",children:sources.map(src=>/* @__PURE__ */jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",columnGap:A.sourceColumnGap,paddingVertical:A.sourcePadY,paddingHorizontal:A.sourcePadX,borderRadius:A.sourceRadius,backgroundColor:look.white},children:[
856
+ /* @__PURE__ */jsx(HubText,{variant:"bodySm",style:{flexShrink:1},children:src.name}),src.meta!==null?/* @__PURE__ */jsx(HubText,{variant:"fine",children:src.meta}):null]},src.key))}):null,
857
+ /* @__PURE__ */jsxs(View,{style:{gap:A.actsGap,paddingTop:A.actsTop},children:[canRequest?/* @__PURE__ */jsx(HubButton,{label:HUB_COPY.requestFromClinic,icon:"download",size:"sm",block:true,onPress:onRequest,testID:"everfur-records-sheet-request"}):null,
858
+ /* @__PURE__ */jsx(HubButton,{label:HUB_COPY.uploadDocument,icon:"upload",size:"sm",variant:"secondary",bold:true,block:true,onPress:onUpload,style:{backgroundColor:look.white,borderRadius:999},testID:"everfur-records-sheet-upload"})]})]})})}function Step({state:state,title:title,when:when,last:last=false,testID:testID}){let{look:look}=useHub(),D=APP_HUB.onTheWay.dot;/* @__PURE__ */
859
+ return jsxs(View,{style:{flexDirection:"row",gap:16,paddingBottom:last?0:20},accessible:true,accessibilityLabel:when!==null?`${title}. ${when}`:title,testID:`${testID}-${state}`,children:[last?null:/* @__PURE__ */jsx(View,{style:{position:"absolute",left:D/2-1,top:D+2,bottom:2,width:2,borderRadius:1,backgroundColor:state==="done"?look.ink:look.line}}),
860
+ /* @__PURE__ */jsxs(View,{style:{width:D,height:D,borderRadius:D/2,borderWidth:2,borderColor:state!=="next"?look.ink:look.line,backgroundColor:state==="done"?look.fill:look.white,alignItems:"center",justifyContent:"center"},children:[state==="done"?/* @__PURE__ */jsx(CheckGlyph,{size:16,color:look.onFill}):null,state==="now"?/* @__PURE__ */jsx(View,{style:{width:10,height:10,borderRadius:5,backgroundColor:look.go}}):null]}),
861
+ /* @__PURE__ */jsxs(View,{style:{flex:1,minWidth:0,paddingTop:3,gap:2},children:[
862
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",color:state==="next"?look.muted:void 0,style:{fontSize:17,lineHeight:22},children:title}),when!==null?/* @__PURE__ */jsx(HubText,{variant:"fine",children:when}):null]})]})}function Way({ink:ink,icon:icon,title:title,text:text4,onPress:onPress,testID:testID}){let{look:look}=useHub(),fg=ink?look.onFill:look.ink,O=APP_HUB.onTheWay;/* @__PURE__ */
863
+ return jsxs(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:`${title}. ${text4}`,style:[{flexDirection:"row",alignItems:"center",gap:12,padding:O.wayPad,borderRadius:O.wayRadius},ink?{backgroundColor:look.fill}:{borderWidth:1.5,borderStyle:"dashed",borderColor:look.ink,backgroundColor:look.white}],testID:testID,children:[
864
+ /* @__PURE__ */jsx(HubIcon,{name:icon,size:O.wayIcon,color:fg}),
865
+ /* @__PURE__ */jsxs(View,{style:{flex:1,minWidth:0,gap:2},children:[
866
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",color:fg,style:{fontSize:17,lineHeight:22},children:title}),
867
+ /* @__PURE__ */jsx(HubText,{variant:"bodySm",color:fg,children:text4})]}),
868
+ /* @__PURE__ */jsx(HubIcon,{name:"chevron",size:20,color:ink?look.accentOnFill:look.ink})]})}function HubOnTheWay({words:words2,request:request,steps:steps,sentWhen:sentWhen,canAct:canAct,canRequest:canRequest,onAnotherClinic:onAnotherClinic,onUpload:onUpload}){let whose=words2.poss==="her"||words2.poss==="his"?words2.poss:`${words2.name}’s`,O=APP_HUB.onTheWay,[sent,waiting,inTab]=steps,clinic=request.clinicName?.trim()||null,status=request.statusLabel.trim()||null,waitingLine=request.waitingExpectation?.trim()||(waiting==="now"?status:null);/* @__PURE__ */
869
+ return jsxs(HubCard,{testID:"everfur-records-hub-on-the-way",children:[
870
+ /* @__PURE__ */jsx(HubText,{variant:"screenTitle",accessibilityRole:"header",style:{fontSize:O.titleSize,lineHeight:O.titleLineHeight,letterSpacing:O.titleTracking},children:HUB_COPY.onTheWay(words2.Name)}),
871
+ /* @__PURE__ */jsx(HubText,{variant:"body",style:{marginTop:8},children:HUB_COPY.clinicsTake}),
872
+ /* @__PURE__ */jsxs(View,{style:{marginTop:16},accessibilityRole:"list",testID:"everfur-records-sheet-tracker",children:[
873
+ /* @__PURE__ */jsx(Step,{state:sent,title:HUB_COPY.requestSentTo(clinic),when:sentWhen!==null?HUB_COPY.signedRelease(sentWhen):null,testID:"everfur-records-sheet-step-sent"}),
874
+ /* @__PURE__ */jsx(Step,{state:waiting,title:HUB_COPY.waitingFor(whose),when:waitingLine,testID:"everfur-records-sheet-step-waiting"}),
875
+ /* @__PURE__ */jsx(Step,{state:inTab,last:true,title:HUB_COPY.inHealthTab(whose),when:inTab==="now"?status:HUB_COPY.everyPageRead,testID:"everfur-records-sheet-step-ready"})]}),canAct?/* @__PURE__ */jsxs(View,{style:{gap:12,marginTop:16},testID:"everfur-records-sheet-none-ways",children:[canRequest?/* @__PURE__ */jsx(Way,{ink:true,icon:"download",title:HUB_COPY.anotherClinic,text:HUB_COPY.anotherClinicText,onPress:onAnotherClinic,testID:"everfur-records-sheet-another-clinic"}):null,
876
+ /* @__PURE__ */jsx(Way,{ink:false,icon:"upload",title:HUB_COPY.uploadDocument,text:HUB_COPY.uploadText,onPress:onUpload,testID:"everfur-records-sheet-none-upload"})]}):null]})}function RailDot({state:state}){let{look:look}=useHub(),box3={width:APP_HUB_TIMELINE.dot,height:APP_HUB_TIMELINE.dot,borderRadius:APP_HUB_TIMELINE.dot/2,alignItems:"center",justifyContent:"center"};return state==="done"?/* @__PURE__ */jsx(View,{style:[box3,{backgroundColor:look.brand}],...HIDDEN5,children:/* @__PURE__ */jsx(CheckGlyph,{size:APP_HUB_TIMELINE.check,color:look.white})}):state==="failed"?/* @__PURE__ */jsxs(View,{style:[box3,{backgroundColor:look.alert}],...HIDDEN5,children:[
877
+ /* @__PURE__ */jsx(View,{style:{width:2,height:6,borderRadius:1,backgroundColor:look.white}}),
878
+ /* @__PURE__ */jsx(View,{style:{width:2,height:2,borderRadius:1,marginTop:1.5,backgroundColor:look.white}})]}):state==="current"?/* @__PURE__ */jsx(View,{style:[box3,{borderWidth:APP_HUB_TIMELINE.ring,borderColor:look.brand,backgroundColor:look.white}],...HIDDEN5,children:/* @__PURE__ */jsx(View,{style:{width:APP_HUB_TIMELINE.core,height:APP_HUB_TIMELINE.core,borderRadius:APP_HUB_TIMELINE.core/2,backgroundColor:look.brand}})}):/* @__PURE__ */jsx(View,{style:[box3,{borderWidth:APP_HUB_TIMELINE.ring,borderColor:look.legacyBorder,backgroundColor:look.white}],...HIDDEN5})}function HubInProgress({words:words2,request:request}){let{look:look,face:face2}=useHub(),P=APP_HUB.inProgress,events=buildRequestRail(request),title=request.clinicName?.trim()||HUB_COPY.requestTitle(words2.Name),status=request.statusLabel.trim();/* @__PURE__ */
879
+ return jsxs(View,{style:{borderRadius:P.radius,backgroundColor:look.white,padding:P.pad,gap:P.gap},accessibilityRole:"summary",accessibilityLabel:HUB_COPY.requestA11y(words2.name,status),testID:"everfur-records-records-in-progress",children:[
880
+ /* @__PURE__ */jsx(View,{style:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},children:/* @__PURE__ */jsx(Text,{style:[face2("bold"),{flex:1,fontSize:P.titleSize,lineHeight:P.titleLineHeight,color:look.legacyText}],children:title})}),
881
+ /* @__PURE__ */jsx(View,{accessibilityRole:"summary",testID:"everfur-records-sheet-rail",children:events.map((event,idx)=>{let date2=event.at!==null?recordsDate(event.at):null,a11yState=event.state==="done"?"completed":event.state==="current"?"in progress":event.state==="failed"?"needs attention":"not started",upcoming=event.state==="upcoming";/* @__PURE__ */
882
+ return jsxs(View,{style:{flexDirection:"row",alignItems:"flex-start",gap:APP_HUB_TIMELINE.rowGap},accessibilityRole:"text",accessibilityLabel:[event.title,event.detail,date2,a11yState].filter(Boolean).join(", "),testID:`everfur-records-sheet-rail-${event.key}`,children:[
883
+ /* @__PURE__ */jsxs(View,{style:{alignItems:"center",width:APP_HUB_TIMELINE.dot,alignSelf:"stretch"},children:[
884
+ /* @__PURE__ */jsx(RailDot,{state:event.state}),idx<events.length-1?/* @__PURE__ */jsx(View,{style:{width:APP_HUB_TIMELINE.rail,flex:1,minHeight:APP_HUB_TIMELINE.railMin,marginVertical:APP_HUB_TIMELINE.railGap,backgroundColor:event.state==="done"?look.brand:look.legacyBorder},...HIDDEN5}):null]}),
885
+ /* @__PURE__ */jsxs(View,{style:{flex:1,paddingBottom:APP_HUB_TIMELINE.bodyBottom,gap:APP_HUB_TIMELINE.bodyGap},children:[
886
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:APP_HUB_TIMELINE.titleGap},children:[
887
+ /* @__PURE__ */jsx(Text,{style:[face2(upcoming?"regular":"bold"),{flex:1,fontSize:APP_HUB_TIMELINE.titleSize,lineHeight:APP_HUB_TIMELINE.titleLineHeight,color:event.state==="current"?look.brand:event.state==="failed"?look.alert:upcoming?look.legacyMuted:look.legacyText}],children:event.title}),date2!==null?/* @__PURE__ */jsx(Text,{style:[face2("regular"),{fontSize:APP_HUB_TIMELINE.dateSize,lineHeight:APP_HUB_TIMELINE.dateLineHeight,color:look.legacyMuted}],children:date2}):null]}),event.detail!==null?/* @__PURE__ */jsx(Text,{style:[face2("regular"),{fontSize:APP_HUB_TIMELINE.detailSize,lineHeight:APP_HUB_TIMELINE.detailLineHeight,color:look.legacyMuted},upcoming?{opacity:APP_HUB_TIMELINE.upcomingOpacity}:null],children:event.detail}):null]})]},event.key)})}),status.length>0?/* @__PURE__ */jsx(View,{style:{borderRadius:P.statusRadius,backgroundColor:look.brandSoft,padding:P.statusPad},children:/* @__PURE__ */jsx(Text,{style:[face2("regular"),{fontSize:P.statusSize,lineHeight:P.statusLineHeight,color:look.legacyText}],children:status})}):null]})}function MarkerLine({marker:marker}){let{look:look}=useHub(),S=APP_HUB.peek,alert=marker.flag!==void 0;/* @__PURE__ */
888
+ return jsxs(Fragment,{children:[
889
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:S.markerTopGap},children:[
890
+ /* @__PURE__ */jsxs(View,{style:{flex:1,minWidth:0},children:[
891
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:8},children:[
892
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",style:{fontSize:17,lineHeight:22},children:marker.name}),alert?/* @__PURE__ */jsx(HubPill,{label:HUB_COPY.high,tone:"high"}):null]}),
893
+ /* @__PURE__ */jsx(HubText,{variant:"bodySm",color:look.muted,children:marker.what})]}),
894
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"baseline",gap:S.valueGap},children:[
895
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",color:alert?look.alert:void 0,style:{fontSize:17,lineHeight:22},children:marker.value}),
896
+ /* @__PURE__ */jsx(HubText,{variant:"fine",color:look.muted,children:marker.unit})]})]}),
897
+ /* @__PURE__ */jsxs(View,{style:{height:S.barHeight,borderRadius:999,backgroundColor:look.barTrack},...HIDDEN5,children:[
898
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",top:0,bottom:0,left:"20%",right:"20%",borderRadius:999,backgroundColor:look.go}}),
899
+ /* @__PURE__ */jsx(View,{style:{position:"absolute",top:-(S.barDot-S.barHeight)/2,left:`${marker.at}%`,width:S.barDot,height:S.barDot,marginLeft:-S.barDot/2,borderRadius:S.barDot/2,borderWidth:S.barDotRing,borderColor:look.white,backgroundColor:alert?look.alert:look.ink}})]})]})}function FlaggedMarker({marker:marker,name:name}){let{look:look}=useHub(),S=APP_HUB.peek,[open,setOpen]=useState(false);/* @__PURE__ */
900
+ return jsxs(View,{style:[{borderRadius:S.markerRadius},open?{backgroundColor:look.tintRed}:null],children:[
901
+ /* @__PURE__ */jsx(Pressable,{onPress:()=>setOpen(o=>!o),accessibilityRole:"button",accessibilityState:{expanded:open},style:{gap:S.markerGap,padding:S.markerPad,borderRadius:S.markerRadius,backgroundColor:look.tintRed},testID:`everfur-records-sheet-sample-flag-${marker.name}`,children:/* @__PURE__ */jsx(MarkerLine,{marker:marker})}),open?/* @__PURE__ */jsx(View,{style:{gap:8,paddingHorizontal:S.markerPad,paddingBottom:S.markerPad,alignItems:"flex-start"},testID:"everfur-records-sheet-sample-flag-note",children:/* @__PURE__ */jsxs(HubText,{variant:"bodySm",children:[
902
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",color:look.alertDeep,children:HUB_COPY.sampleNotTheirs(name)}),HUB_COPY.sampleNote]})}):null]})}function FromPage({from:from}){let{look:look,face:face2}=useHub(),S=APP_HUB.peek,[open,setOpen]=useState(false),meta=[face2("mono"),{color:look.muted}];/* @__PURE__ */
903
+ return jsxs(View,{style:{marginTop:8},testID:"everfur-records-sheet-sample-from",children:[
904
+ /* @__PURE__ */jsxs(Pressable,{onPress:()=>setOpen(v=>!v),accessibilityRole:"button",accessibilityLabel:from.cap,accessibilityState:{expanded:open},style:[{flexDirection:"row",alignItems:"center",gap:S.fromGap,minHeight:S.fromMinHeight,alignSelf:"flex-start"},open?{marginBottom:8}:null],testID:"everfur-records-sheet-sample-from-cap",children:[
905
+ /* @__PURE__ */jsx(HubIcon,{name:"file",size:S.fromIcon,color:look.icoSage}),
906
+ /* @__PURE__ */jsx(HubText,{variant:"buttonRow",style:{lineHeight:20},children:from.cap}),
907
+ /* @__PURE__ */jsx(HubIcon,{name:"chevron",size:S.fromChevron,style:open?{transform:[{rotate:"90deg"}]}:void 0})]}),open?/* @__PURE__ */jsxs(View,{style:{gap:4,padding:12,borderWidth:1,borderColor:look.line,borderRadius:10,backgroundColor:look.white},testID:"everfur-records-sheet-sample-doc",children:[
908
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:8},children:[
909
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",children:from.who}),
910
+ /* @__PURE__ */jsx(Text,{style:[meta,{fontSize:12,lineHeight:18}],children:from.page})]}),
911
+ /* @__PURE__ */jsx(View,{style:{flexDirection:"row"},children:HUB_COPY.columns.map((head,i)=>/* @__PURE__ */jsx(Text,{style:[meta,{flex:i===0?1.1:1,paddingHorizontal:8,paddingBottom:2,fontSize:12,lineHeight:16,letterSpacing:.48,textTransform:"uppercase"}],children:head},head))}),from.rows.map(r=>/* @__PURE__ */jsx(View,{style:[{flexDirection:"row",marginTop:3,borderRadius:6},r.lit===true?{backgroundColor:look.tintYellow}:null],children:[r.test,r.result,r.unit,r.range].map((cell,i)=>/* @__PURE__ */jsx(Text,{numberOfLines:1,style:[face2("mono"),{flex:i===0?1.1:1,paddingHorizontal:8,paddingVertical:5,fontSize:13,lineHeight:18,color:look.text,fontVariant:["tabular-nums"]}],children:cell},i))},r.test))]}):null]})}var DOG_ONLY=/heartworm|4dx/i;function HubSamplePeek({name:name,species:species}){let{look:look}=useHub(),S=APP_HUB.peek,[index,setIndex]=useState(0),last=HUB_SAMPLE_GROUPS.length-1,group=HUB_SAMPLE_GROUPS[index],dog=species!==null&&/^(dog|canine)$/i.test(species.trim()),tints={pink:look.tintPink,blue:look.tintBlue,yellow:look.tintYellow},icons={screenings:"shield",visits:"folder",timeline:"clock"};/* @__PURE__ */
912
+ return jsxs(View,{style:{marginTop:S.top},testID:"everfur-records-sample-peek",children:[
913
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:S.headGap},children:[
914
+ /* @__PURE__ */jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",children:HUB_COPY.recordsHistory}),
915
+ /* @__PURE__ */jsx(HubPill,{label:HUB_COPY.sample,tone:"plain"})]}),
916
+ /* @__PURE__ */jsx(HubText,{variant:"bodySm",style:{marginTop:S.leadTop},children:HUB_COPY.peekLead(name)}),
917
+ /* @__PURE__ */jsxs(HubCard,{style:{marginTop:S.labsTop},testID:"everfur-records-sheet-sample-labs",children:[
918
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:6},children:[
919
+ /* @__PURE__ */jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{flex:1},children:HUB_COPY.labs}),
920
+ /* @__PURE__ */jsx(View,{style:index===0?{opacity:.35}:null,children:/* @__PURE__ */jsx(HubRound,{icon:"chevron",rotate:180,label:HUB_COPY.previousGroup,disabled:index===0,onPress:()=>setIndex(i=>Math.max(0,i-1)),testID:"everfur-records-sheet-sample-prev"})}),
921
+ /* @__PURE__ */jsx(View,{style:index===last?{opacity:.35}:null,children:/* @__PURE__ */jsx(HubRound,{icon:"chevron",label:HUB_COPY.nextGroup,disabled:index===last,onPress:()=>setIndex(i=>Math.min(last,i+1)),testID:"everfur-records-sheet-sample-next"})})]}),
922
+ /* @__PURE__ */jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,style:{marginTop:S.chipsTop,flexGrow:0},contentContainerStyle:{flexDirection:"row",gap:S.chipsGap},accessibilityLabel:HUB_COPY.markerGroups,children:HUB_SAMPLE_GROUPS.map((g,i)=>/* @__PURE__ */jsx(HubChip,{label:g.chip,selected:i===index,onPress:()=>setIndex(i),testID:`everfur-records-sheet-sample-group-${g.key}`},g.key))}),
923
+ /* @__PURE__ */jsxs(View,{style:{marginTop:S.slideTop,gap:S.slideGap},accessibilityLabel:HUB_COPY.slideOf(group.chip,index+1,HUB_SAMPLE_GROUPS.length),testID:"everfur-records-sheet-sample-slide",children:[
924
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",style:{fontSize:17,lineHeight:22},children:group.chip}),
925
+ /* @__PURE__ */jsx(HubText,{variant:"bodySm",style:{marginTop:S.slideLeadTop,marginBottom:S.slideLeadBottom},children:group.lead}),group.markers.map(m=>m.flag!==void 0?/* @__PURE__ */jsx(FlaggedMarker,{marker:m,name:name},m.name):/* @__PURE__ */jsx(View,{style:{gap:S.markerGap,padding:S.markerPad,borderRadius:S.markerRadius},children:/* @__PURE__ */jsx(MarkerLine,{marker:m})},m.name)),
926
+ /* @__PURE__ */jsx(FromPage,{from:group.from},group.key)]})]}),
927
+ /* @__PURE__ */jsx(View,{style:{gap:S.moreGap,marginTop:S.moreTop},testID:"everfur-records-sheet-sample-more",children:HUB_SAMPLE_MORE.map(card=>{let rows=dog?card.rows:card.rows.filter(r=>!DOG_ONLY.test(r.title));return rows.length===0?null:/* @__PURE__ */jsxs(View,{style:{gap:S.moreInnerGap,padding:S.morePad,borderRadius:S.moreRadius,backgroundColor:tints[card.tint]},testID:`everfur-records-sheet-sample-${card.key}`,children:[
928
+ /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:S.moreHeadGap},children:[
929
+ /* @__PURE__ */jsx(HubIcon,{name:icons[card.key],size:S.moreIcon}),
930
+ /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",accessibilityRole:"header",style:{fontSize:17,lineHeight:22},children:card.title})]}),
931
+ /* @__PURE__ */jsx(HubText,{variant:"bodySm",children:card.lead}),
932
+ /* @__PURE__ */jsx(View,{style:{gap:S.rowsGap},children:rows.map(row=>/* @__PURE__ */jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:S.rowMinHeight,paddingVertical:S.rowPadY,paddingHorizontal:S.rowPadX,borderRadius:S.rowRadius,backgroundColor:look.white},children:[
933
+ /* @__PURE__ */jsx(HubText,{variant:"bodySm",style:{flexShrink:1},children:row.title}),row.pill!==void 0?/* @__PURE__ */jsx(HubPill,{label:row.pill,tone:row.tone??"plain"}):/* @__PURE__ */jsx(HubText,{variant:"labelMono",color:look.muted,children:row.text??""})]},row.title))})]},card.key)})})]})}function HubLegal(){/* @__PURE__ */
934
+ return jsx(View,{style:{marginTop:APP_HUB.screen.legalTop},testID:"everfur-records-hub-legal",children:/* @__PURE__ */jsx(HubText,{variant:"fine",style:{textAlign:"center"},accessibilityRole:"text",testID:"records-footnote",children:HUB_COPY.legal})})}var HIDDEN6={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"},STAGE_PET_HEIGHT=raphPx(".efh-stage","height")*raphPct(".efh-stage__pet","height");function SheetIcon({kind:kind,size:size=RAPH_RN_METRICS.icon,color:color}){let glyph;switch(kind){case"flask":glyph=/* @__PURE__ */jsx(FlaskGlyph,{size:size,color:color});break;case"thermo":glyph=/* @__PURE__ */jsx(ThermoGlyph,{size:size,color:color});break;case"heart":glyph=/* @__PURE__ */jsx(HeartGlyph,{size:size,color:color});break;case"wind":glyph=/* @__PURE__ */jsx(WindGlyph,{size:size,color:color});break;case"shield":glyph=/* @__PURE__ */jsx(ShieldGlyph,{size:size,color:color});break;case"folder":glyph=/* @__PURE__ */jsx(FolderGlyph,{size:size,color:color});break;case"clip":glyph=/* @__PURE__ */jsx(ClipboardGlyph,{size:size,color:color});break;case"clock":glyph=/* @__PURE__ */jsx(ClockFaceGlyph,{size:size,color:color});break;case"calendar":glyph=/* @__PURE__ */jsx(CalendarGlyph,{size:size,color:color});break;case"chevron":glyph=/* @__PURE__ */jsx(ChevronGlyph,{size:size,color:color,direction:"right"});break;case"upload":glyph=/* @__PURE__ */jsx(UploadArrowGlyph,{size:size,color:color});break;case"download":glyph=/* @__PURE__ */jsx(DownloadGlyph2,{size:size,color:color});break;default:glyph=null}/* @__PURE__ */
935
+ return jsx(View,{style:{width:size,height:size,alignItems:"center",justifyContent:"center"},...HIDDEN6,children:glyph})}var SheetKitContext=createContext(null);function useSheetKitValue(){let theme=useEverfurTheme();return useMemo(()=>{let look=recordsSheetLook(theme);return{theme:theme,look:look,s:makeSheetStyles(theme,look)}},[theme])}var SheetKitProvider=SheetKitContext.Provider;function useSheetKit(){let own=useSheetKitValue();return useContext(SheetKitContext)??own}function SheetPill({label:label,tone:tone,small:small=false,style:style,testID:testID}){let{s:s,look:look}=useSheetKit();if(label.trim().length===0)return null;let pad=small?7:10,edge=(width,color)=>({backgroundColor:look.card,borderWidth:width,borderColor:color,paddingHorizontal:pad-width}),tones={watch:{backgroundColor:look.watch},stable:{backgroundColor:look.goTint},later:edge(1.25,look.line),clear:edge(1.5,look.go),plain:edge(1.5,look.plainEdge),high:edge(1.25,look.alert)},ink=tone==="later"?look.muted:tone==="clear"?look.go:tone==="high"?look.alert:look.ink;/* @__PURE__ */
936
+ return jsx(View,{style:[s.pill,small?s.pillSmall:null,tones[tone],style],testID:testID,children:/* @__PURE__ */jsx(Text,{tier:"compact",style:[s.pillText,small?s.pillTextSmall:null,{color:ink}],children:label})})}function SheetCard({children:children,style:style,testID:testID}){let{s:s}=useSheetKit();/* @__PURE__ */
737
937
  return jsx(View,{style:[s.card,style],testID:testID,children:children})}function SheetButton({kind:kind,label:label,icon:icon,onPress:onPress,row:row=false,testID:testID}){let{s:s,look:look,theme:theme}=useSheetKit(),still=theme.motion.reducedMotion,ink=kind==="ink"?look.onFill:look.ink;/* @__PURE__ */
738
938
  return jsxs(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,testID:testID,style:({pressed:pressed})=>[s.button,row?s.buttonRow:null,kind==="ink"?{backgroundColor:look.fill}:{backgroundColor:look.card,borderWidth:1.5,borderColor:look.ink},pressed&&!still?{transform:[{scale:RECORDS_MOTION.pressScale}]}:null],children:[icon!==void 0?/* @__PURE__ */jsx(SheetIcon,{kind:icon,size:20,color:ink}):null,
739
- /* @__PURE__ */jsx(Text,{tier:"control",style:[s.buttonText,row?s.buttonTextRow:null,{color:ink}],children:label})]})}function SheetWay({kind:kind,icon:icon,title:title,detail:detail,onPress:onPress,testID:testID}){let{s:s,look:look,theme:theme}=useSheetKit(),still=theme.motion.reducedMotion,ink=kind==="ink"?look.onFill:look.ink;/* @__PURE__ */
740
- return jsxs(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:`${title}. ${detail}`,testID:testID,style:({pressed:pressed})=>[s.way,kind==="ink"?{backgroundColor:look.fill}:{backgroundColor:look.card,borderWidth:1.5,borderStyle:"dashed",borderColor:look.ink},pressed&&!still?{transform:[{scale:RECORDS_MOTION.pressScale}]}:null],children:[
741
- /* @__PURE__ */jsx(SheetIcon,{kind:icon,size:26,color:ink}),
742
- /* @__PURE__ */jsxs(View,{style:s.wayText,children:[
743
- /* @__PURE__ */jsx(Text,{style:[s.wayTitle,{color:ink}],children:title}),
744
- /* @__PURE__ */jsx(Text,{style:[s.wayDetail,{color:kind==="ink"?look.onFill:look.text}],children:detail})]}),
745
- /* @__PURE__ */jsx(SheetIcon,{kind:"chevron",size:20,color:kind==="ink"?look.accentOnFill:look.ink})]})}function SheetMarkerRow({name:name,value:value,unit:unit,range:range,at:at,pill:pill,testID:testID}){let{s:s,look:look}=useSheetKit();/* @__PURE__ */
939
+ /* @__PURE__ */jsx(Text,{tier:"control",style:[s.buttonText,row?s.buttonTextRow:null,{color:ink}],children:label})]})}function SheetMarkerRow({name:name,value:value,unit:unit,range:range,at:at,pill:pill,testID:testID}){let{s:s,look:look}=useSheetKit();/* @__PURE__ */
746
940
  return jsxs(View,{style:s.mk,testID:testID,children:[
747
941
  /* @__PURE__ */jsxs(View,{style:s.mkText,children:[
748
942
  /* @__PURE__ */jsxs(View,{style:s.mkNameRow,children:[
749
943
  /* @__PURE__ */jsx(Text,{style:s.mkName,children:name}),pill!==null?/* @__PURE__ */jsx(SheetPill,{label:pill,tone:"high"}):null]}),
750
- /* @__PURE__ */jsxs(Text,{style:s.mkLine,children:[
751
- /* @__PURE__ */jsx(Text,{style:s.mkValue,children:value}),unit?` ${unit}`:"",range!==null?` · ${range}`:""]})]}),at!==null?/* @__PURE__ */jsxs(View,{style:s.mkBar,...HIDDEN3,children:[
944
+ /* @__PURE__ */jsxs(View,{style:s.mkLine,children:[
945
+ /* @__PURE__ */jsx(Text,{style:s.mkValue,children:value}),unit?/* @__PURE__ */jsx(Text,{style:s.mkLineText,children:unit}):null,range!==null?/* @__PURE__ */jsx(Text,{style:s.mkLineText,children:`· ${range}`}):null]})]}),at!==null?/* @__PURE__ */jsxs(View,{style:s.mkBar,...HIDDEN6,children:[
752
946
  /* @__PURE__ */jsx(View,{style:[s.mkBarIn,{backgroundColor:look.go}]}),
753
947
  /* @__PURE__ */jsx(View,{style:[s.mkBarDot,{left:`${at}%`,backgroundColor:look.ink,borderColor:look.card}]})]}):null]})}function ChartLine({points:points,color:color}){let[box3,setBox]=useState(null),onLayout=e=>{let{width:width,height:height}=e.nativeEvent.layout;(box3===null||box3.w!==width||box3.h!==height)&&setBox({w:width,h:height})},segments=box3===null?[]:points.slice(1).map((p,i)=>{let a=points[i]??p,x1=a.x/100*box3.w,y1=a.y/100*box3.h,x2=p.x/100*box3.w,y2=p.y/100*box3.h,length=Math.hypot(x2-x1,y2-y1),angle=Math.atan2(y2-y1,x2-x1)*180/Math.PI;return{key:i,left:(x1+x2)/2-length/2,top:(y1+y2)/2-.75,length:length,angle:angle}});/* @__PURE__ */
754
- return jsx(View,{style:ABSOLUTE_FILL,onLayout:onLayout,...HIDDEN3,children:segments.map(seg=>/* @__PURE__ */jsx(View,{style:{position:"absolute",left:seg.left,top:seg.top,width:seg.length,height:1.5,backgroundColor:color,transform:[{rotate:`${seg.angle}deg`}]}},seg.key))})}function makeSheetStyles(theme,look){let body=face(theme,"regular"),bold=face(theme,"bold"),heading=headingFace(theme,"bold"),mono=face(theme,"mono"),monoBold=face(theme,"monoBold"),lh=(size,ratio)=>Math.round(size*ratio);return StyleSheet.create({sheet:{gap:RAPH_RN_METRICS.gap,paddingTop:RAPH_RN_METRICS.sheetPadTop,paddingHorizontal:RAPH_RN_METRICS.sheetPadX,paddingBottom:RAPH_RN_METRICS.sheetPadBottom,borderTopLeftRadius:RAPH_RN_METRICS.sheetRadius,borderTopRightRadius:RAPH_RN_METRICS.sheetRadius,backgroundColor:look.ground},card:{padding:RAPH_RN_METRICS.cardPad,backgroundColor:look.card,borderRadius:RAPH_RN_METRICS.cardRadius,shadowColor:"#000000",shadowOpacity:look.dark?0:.09,shadowRadius:3,shadowOffset:{width:0,height:1},elevation:look.dark?0:1,borderWidth:look.dark?1:0,borderColor:look.line},cardHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:12},cardTitle:{...heading,fontSize:RAPH_RN_METRICS.cardTitle,lineHeight:lh(RAPH_RN_METRICS.cardTitle,1.25),letterSpacing:-.36,color:look.ink},cardTitleGap:{marginBottom:12},sec:{marginTop:8,marginBottom:12},head:{gap:2,marginBottom:8},name:{...heading,fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.44,color:look.ink,flexShrink:1},meta:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),letterSpacing:.26,textTransform:"uppercase",color:look.muted},label:{...monoBold,marginTop:12,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look.muted},vitals:{flexDirection:"row",gap:8,marginTop:8},vital:{flex:1,minWidth:0},vitalTop:{flexDirection:"row",alignItems:"center",gap:6},vitalValue:{...bold,fontSize:17,lineHeight:lh(17,1.2),color:look.ink},vitalUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},vitalLabel:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},due:{gap:4,marginHorizontal:-12},dueRow:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius},dueText:{flex:1,minWidth:0,gap:2},dueTitle:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},dueWhen:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},pill:{minHeight:RAPH_RN_METRICS.pill,paddingHorizontal:10,borderRadius:999,alignItems:"center",justifyContent:"center",alignSelf:"flex-start"},pillSmall:{minHeight:22,paddingHorizontal:7},pillText:{...monoBold,fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,letterSpacing:.72,textTransform:"uppercase"},pillTextSmall:{fontSize:10.5,letterSpacing:.21},tiles:{flexDirection:"row",flexWrap:"wrap",gap:RAPH_RN_METRICS.tileGap},tile:{flexGrow:1,flexBasis:"45%",minWidth:0,gap:8,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},tileTop:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between"},tileTitle:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.25),letterSpacing:-.15,color:look.ink},tileFoot:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8,minHeight:28},tileNum:{...bold,fontSize:RAPH_RN_METRICS.tileNum,lineHeight:RAPH_RN_METRICS.tileNum+2,letterSpacing:-.4,color:look.ink},tileUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},emptyLine:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),color:look.muted},wt:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8},wtValue:{...bold,fontSize:RAPH_RN_METRICS.big,lineHeight:RAPH_RN_METRICS.big+4,letterSpacing:-.64,color:look.ink},wtSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look.muted},chart:{marginTop:20},plot:{position:"relative",height:RAPH_RN_METRICS.plot},point:{position:"absolute",width:12,height:12,marginLeft:-6,marginTop:-6,borderRadius:6,borderWidth:1.5,borderColor:look.card},pointLabel:{...face(theme,"medium"),position:"absolute",bottom:16,width:64,left:-26,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,color:look.dark?look.text:RAPH_CHARCOAL},xAxis:{position:"relative",height:18,marginTop:8},xTick:{...mono,position:"absolute",top:0,width:56,marginLeft:-28,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.3),color:look.muted},key:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:12},keyDot:{width:12,height:12,borderRadius:6,backgroundColor:look.ink},keyText:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},tlKey:{flexDirection:"row",alignItems:"center",gap:6,marginBottom:4},tlKeyDot:{width:10,height:10,borderRadius:5,borderWidth:2.5,borderColor:look.ink,backgroundColor:look.card},tlYear:{...monoBold,marginTop:20,marginBottom:12,marginLeft:40,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look.muted},tlItem:{position:"relative",flexDirection:"row",gap:16,paddingBottom:24},tlItemLast:{paddingBottom:0},tlRail:{position:"absolute",left:11,top:22,bottom:-2,width:2,borderRadius:1,backgroundColor:look.line},tlRailEnd:{bottom:12},tlDot:{width:16,height:16,marginTop:3,marginHorizontal:4,borderRadius:8,borderWidth:3,borderColor:look.ink,backgroundColor:look.card},tlBody:{flex:1,minWidth:0},tlBtn:{marginTop:-8,marginHorizontal:-8,paddingVertical:8,paddingLeft:8,paddingRight:36,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.alertTint},tlChevron:{position:"absolute",right:8,top:"50%",marginTop:-10},tlDate:{...mono,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.48,textTransform:"uppercase",color:look.muted},tlTitle:{...bold,marginTop:2,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},tlText:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},pull:{paddingTop:4,paddingBottom:24,paddingLeft:40},pullNone:{paddingTop:14,paddingBottom:0,paddingLeft:0},pullStep:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.ink},pullBar:{height:6,marginTop:10,overflow:"hidden",borderRadius:999,backgroundColor:look.line},pullFill:{height:"100%",backgroundColor:look.accent},failed:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.alertTint},failedText:{...bold,flex:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.alertDeep},add:{gap:12},addHead:{flexDirection:"row",alignItems:"center",gap:8},addLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},sources:{gap:6},source:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",columnGap:12,paddingVertical:10,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.rowGround},sourceLabel:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.text},sourceDetail:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},addActs:{gap:12,paddingTop:4},button:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,minHeight:RAPH_RN_METRICS.button,paddingHorizontal:20,borderRadius:999},buttonRow:{minHeight:RAPH_RN_METRICS.rowButton,paddingHorizontal:16},buttonText:{...bold,fontSize:16,lineHeight:20},buttonTextRow:{fontSize:RAPH_RN_METRICS.body},noneTitle:{...heading,fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.15),letterSpacing:-.44,color:look.ink},noneLead:{...body,marginTop:8,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},ways:{gap:12,marginTop:16},way:{flexDirection:"row",alignItems:"center",gap:12,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},wayText:{flex:1,minWidth:0,gap:2},wayTitle:{...bold,fontSize:16,lineHeight:lh(16,1.3)},wayDetail:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.45)},peek:{gap:12,marginTop:12},peekHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:12},peekLead:{...body,marginTop:-4,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},peekGroup:{...body,marginTop:8,marginBottom:6,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.45),color:look.muted},peekGroupTitle:{...bold,fontSize:16,color:look.ink},more:{gap:10},moreCard:{gap:10,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},moreHead:{flexDirection:"row",alignItems:"center",gap:8},moreTitle:{...bold,fontSize:16,lineHeight:lh(16,1.3),color:look.ink},moreLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},moreRows:{gap:6},moreRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:44,paddingVertical:8,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.card},moreRowLabel:{...body,flexShrink:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.text},moreWhen:{...mono,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.24,color:look.muted},note:{...body,marginTop:4,fontSize:12.5,textAlign:"center",color:look.muted},mks:{gap:2,marginHorizontal:-8},mk:{flexDirection:"row",alignItems:"center",gap:12,paddingVertical:10,paddingHorizontal:8},mkText:{flex:1,minWidth:0},mkNameRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:8},mkName:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},mkLine:{...body,marginTop:1,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},mkValue:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,color:look.text},mkBar:{position:"relative",width:96,height:6,borderRadius:999,backgroundColor:look.barTrack},mkBarIn:{position:"absolute",top:0,bottom:0,left:"20%",right:"20%",borderRadius:999},mkBarDot:{position:"absolute",top:-2,width:10,height:10,marginLeft:-5,borderRadius:5,borderWidth:2},topRisk:{gap:8,backgroundColor:look.topFill,borderRadius:22,borderWidth:0,shadowOpacity:0,elevation:0},topRiskKicker:{flexDirection:"row",alignItems:"center",gap:6},topRiskDot:{width:8,height:8,borderRadius:4,backgroundColor:look.alert},topRiskK:{...monoBold,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.72,textTransform:"uppercase",color:look.topKicker},topRiskText:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.35),color:look.topInk},disclaimer:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),textAlign:"center",color:look.muted},lab:{gap:RAPH_RN_METRICS.gap,paddingTop:8,paddingHorizontal:16,paddingBottom:32,backgroundColor:look.ground},labTitle:{...face(theme,"medium"),fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.33,color:look.ink},labMeta:{...mono,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.45),color:look.muted},latest:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",columnGap:12,rowGap:4},latestSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look.muted},change:{...body,marginTop:12,fontSize:RAPH_RN_METRICS.body,color:look.text},changeLead:{...bold,color:look.ink},ctx:{gap:12},ctxText:{...body,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.55),color:look.text},labBody:{flexDirection:"row",gap:8},rail:{width:8,height:RAPH_RN_METRICS.plot,overflow:"hidden",borderRadius:2},legend:{width:82,height:RAPH_RN_METRICS.plot,position:"relative"},range:{...monoBold,position:"absolute",left:0,right:0,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.2),letterSpacing:.24,textTransform:"uppercase",color:look.dark?look.text:RAPH_CHARCOAL},band:{position:"absolute",left:0,right:0,top:"25%",height:"50%",backgroundColor:look.goTint}})}var RAPH_CHARCOAL="#3D3D3D";function EverfurRecordsLabDetail({petRef:petRef,petName:petName,markerId:markerId,renderExtra:renderExtra,onAsk:onAsk,renderAskButton:renderAskButton,style:style}){let view=useRecordsMarkers(petRef).markers,model=view===null||view.withheld?null:buildSheetLabModel(view,markerId);if(model===null)return null;let marker=view?.markers.find(m=>m.markerId===markerId)??null;/* @__PURE__ */
948
+ return jsx(View,{style:ABSOLUTE_FILL,onLayout:onLayout,...HIDDEN6,children:segments.map(seg=>/* @__PURE__ */jsx(View,{style:{position:"absolute",left:seg.left,top:seg.top,width:seg.length,height:1.5,backgroundColor:color,transform:[{rotate:`${seg.angle}deg`}]}},seg.key))})}function makeSheetStyles(theme,look){let body=face(theme,"regular"),bold=face(theme,"bold"),heading=headingFace(theme,"bold"),mono=face(theme,"mono"),monoBold=face(theme,"monoBold"),lh=(size,ratio)=>lh100(size*ratio);return StyleSheet.create({scroll:{flexGrow:1},topSlot:{paddingHorizontal:RAPH_RN_METRICS.sheetPadX},sheet:{flexGrow:1,gap:RAPH_RN_METRICS.gap,paddingTop:RAPH_RN_METRICS.sheetPadTop,paddingHorizontal:RAPH_RN_METRICS.sheetPadX,paddingBottom:RAPH_RN_METRICS.sheetPadBottom,borderTopLeftRadius:RAPH_RN_METRICS.sheetRadius,borderTopRightRadius:RAPH_RN_METRICS.sheetRadius,backgroundColor:look.ground},sheetUnderSlot:{marginTop:RAPH_RN_METRICS.sheetGap},card:{padding:RAPH_RN_METRICS.cardPad,backgroundColor:look.card,borderRadius:RAPH_RN_METRICS.cardRadius,shadowColor:"#000000",shadowOpacity:look.dark?0:.09,shadowRadius:3,shadowOffset:{width:0,height:1},elevation:look.dark?0:1,borderWidth:look.dark?1:0,borderColor:look.line},cardHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:12},cardTitle:{...heading,fontSize:RAPH_RN_METRICS.cardTitle,lineHeight:lh(RAPH_RN_METRICS.cardTitle,1.25),letterSpacing:-.36,color:look.ink},cardTitleGap:{marginBottom:12},sec:{marginTop:8,marginBottom:12},head:{marginBottom:raphPx(".efh-head","marginBottom")},name:{...heading,fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.44,color:look.ink,flexShrink:1},meta:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),letterSpacing:.26,textTransform:"uppercase",color:look.muted},label:{...monoBold,marginTop:raphPx(".efh-head__from","marginTop"),fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look.muted},vitals:{flexDirection:"row",gap:8,marginTop:8},stage:{position:"relative",height:raphPx(".efh-stage","height"),marginTop:raphPx(".efh-stage","marginTop"),marginHorizontal:raphPx(".efh-stage","marginLeft"),overflow:"hidden"},stageGrass:{position:"absolute",left:0,right:0,bottom:0,height:`${raphPct(".efh-stage__grass","height")*100}%`,overflow:"hidden"},stagePet:{position:"absolute",left:`${raphPct(".efh-stage__pet","left")*100}%`,bottom:raphPx(".efh-stage__pet","bottom"),height:STAGE_PET_HEIGHT},stageVitals:{position:"absolute",top:raphPx(".efh-stage .efh-vitals","top"),left:raphPx(".efh-stage .efh-vitals","left"),gap:raphPx(".efh-stage .efh-vitals","gap")},vital:{flex:1,minWidth:0},vitalTop:{flexDirection:"row",alignItems:"center",gap:6},vitalValue:{...bold,fontSize:17,lineHeight:lh(17,1.2),color:look.ink},vitalUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},vitalLabel:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},due:{gap:4,marginHorizontal:-12},dueRow:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius},dueText:{flex:1,minWidth:0,gap:2},duePill:{alignSelf:"center"},dueTitle:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},dueWhen:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},pill:{minHeight:RAPH_RN_METRICS.pill,paddingHorizontal:10,borderRadius:999,alignItems:"center",justifyContent:"center",alignSelf:"flex-start"},pillSmall:{minHeight:22,paddingHorizontal:7},pillText:{...monoBold,fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,letterSpacing:.72,textTransform:"uppercase"},pillTextSmall:{fontSize:10.5,letterSpacing:.21},tiles:{flexDirection:"row",flexWrap:"wrap",gap:RAPH_RN_METRICS.tileGap},tile:{flexGrow:1,flexBasis:"45%",minWidth:0,gap:8,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},tileTop:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between"},tileTitle:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.25),letterSpacing:-.15,color:look.ink},tileFoot:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8,minHeight:28},tileNum:{...bold,fontSize:RAPH_RN_METRICS.tileNum,lineHeight:RAPH_RN_METRICS.tileNum+2,letterSpacing:-.4,color:look.ink},tileUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},emptyLine:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),color:look.muted},wt:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8},wtValue:{...bold,fontSize:RAPH_RN_METRICS.big,lineHeight:RAPH_RN_METRICS.big+4,letterSpacing:-.64,color:look.ink},wtSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look.muted},chart:{marginTop:20},plot:{position:"relative",height:RAPH_RN_METRICS.plot},point:{position:"absolute",width:12,height:12,marginLeft:-6,marginTop:-6,borderRadius:6,borderWidth:1.5,borderColor:look.card},pointLabel:{...face(theme,"medium"),position:"absolute",bottom:16,width:64,left:-26,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,color:look.dark?look.text:RAPH_CHARCOAL},xAxis:{position:"relative",height:18,marginTop:8},xTick:{...mono,position:"absolute",top:0,width:56,marginLeft:-28,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.3),color:look.muted},key:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:12},keyDot:{width:12,height:12,borderRadius:6,backgroundColor:look.ink},keyText:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},tlKey:{flexDirection:"row",alignItems:"center",gap:6,marginBottom:4},tlKeyDot:{width:10,height:10,borderRadius:5,borderWidth:2.5,borderColor:look.ink,backgroundColor:look.card},tlYear:{...monoBold,marginTop:20,marginBottom:12,marginLeft:40,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look.muted},tlItem:{position:"relative",flexDirection:"row",gap:16,paddingBottom:24},tlItemLast:{paddingBottom:0},tlRail:{position:"absolute",left:11,top:22,bottom:-2,width:2,borderRadius:1,backgroundColor:look.line},tlRailEnd:{bottom:12},tlDot:{width:16,height:16,marginTop:3,marginHorizontal:4,borderRadius:8,borderWidth:3,borderColor:look.ink,backgroundColor:look.card},tlBody:{flex:1,minWidth:0},tlBtn:{marginTop:-8,marginHorizontal:-8,paddingVertical:8,paddingLeft:8,paddingRight:36,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.alertTint},tlChevron:{position:"absolute",right:8,top:"50%",marginTop:-10},tlDate:{...mono,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.48,textTransform:"uppercase",color:look.muted},tlTitle:{...bold,marginTop:2,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},tlText:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},pull:{paddingTop:4,paddingBottom:24,paddingLeft:40},pullStep:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.ink},pullBar:{height:6,marginTop:10,overflow:"hidden",borderRadius:999,backgroundColor:look.line},pullFill:{height:"100%",backgroundColor:look.accent},failed:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.alertTint},failedText:{...bold,flex:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.alertDeep},add:{gap:12},addHead:{flexDirection:"row",alignItems:"center",gap:8},addLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},sources:{gap:6},source:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",columnGap:12,paddingVertical:10,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.rowGround},sourceLabel:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.text},sourceDetail:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},addActs:{gap:12,paddingTop:4},button:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,minHeight:RAPH_RN_METRICS.button,paddingHorizontal:20,borderRadius:999},buttonRow:{minHeight:RAPH_RN_METRICS.rowButton,paddingHorizontal:16},buttonText:{...bold,fontSize:16,lineHeight:20},buttonTextRow:{fontSize:RAPH_RN_METRICS.body},noneWithScene:{paddingTop:raphPx(".efh-none","paddingTop")},scene:{position:"relative",height:RAPH_RN_SCENE.height,marginHorizontal:raphPx(".efh-none__scene","marginLeft"),marginBottom:raphPx(".efh-none__scene","marginBottom"),overflow:"hidden",borderTopLeftRadius:RAPH_RN_METRICS.cardRadius,borderTopRightRadius:RAPH_RN_METRICS.cardRadius},sceneGrass:{position:"absolute",left:0,right:0,bottom:0,height:RAPH_RN_SCENE.grassHeight,overflow:"hidden"},scenePet:{position:"absolute",left:"50%",bottom:RAPH_RN_SCENE.petBottom,height:RAPH_RN_SCENE.petHeight},noneTitle:{...heading,fontSize:raphPx(".efh-none__t","fontSize"),lineHeight:raphPx(".efh-none__t","lineHeight"),letterSpacing:raphPx(".efh-none__t","letterSpacing"),color:look.ink},noneLead:{...body,marginTop:raphPx(".efh-none__lead","marginTop"),fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look.text},noneLine:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",columnGap:4,marginTop:raphPx(".efh-none__lead","marginTop")},noneLineText:{...body,fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look.text},noneLink:{...bold,fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look.ink,textDecorationLine:"underline"},repeatLine:{...bold,marginTop:raphPx(".efh-ways","gap"),fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look.ink},ways:{gap:raphPx(".efh-ways","gap"),marginTop:raphPx(".efh-ways","marginTop")},way:{flexDirection:"row",alignItems:"center",gap:raphPx(".efh-way","columnGap"),padding:raphPx(".efh-way","paddingTop"),borderRadius:raphPx(".efh-way","borderRadius")},wayText:{flex:1,minWidth:0,gap:raphPx(".efh-way__w","gap")},wayTitle:{...bold,fontSize:raphPx(".efh-way__t","fontSize"),lineHeight:raphPx(".efh-way__t","lineHeight")},wayDetail:{...body,fontSize:raphPx(".efh-way__x","fontSize"),lineHeight:raphPx(".efh-way__x","lineHeight")},tracker:{marginTop:16},step:{flexDirection:"row",gap:16,paddingBottom:20},stepLast:{paddingBottom:0},stepRail:{position:"absolute",left:TRACKER_DOT/2-1,top:TRACKER_DOT+2,bottom:2,width:2,borderRadius:1,backgroundColor:look.line},stepRailDone:{backgroundColor:look.ink},stepDot:{width:TRACKER_DOT,height:TRACKER_DOT,borderRadius:TRACKER_DOT/2,borderWidth:2,borderColor:look.line,backgroundColor:look.card,alignItems:"center",justifyContent:"center"},stepDotOn:{borderColor:look.ink},stepDotDone:{backgroundColor:look.fill,borderColor:look.fill},stepNow:{width:10,height:10,borderRadius:5,backgroundColor:look.accent},stepText:{flex:1,minWidth:0,paddingTop:3,gap:2},stepTitle:{...bold,fontSize:raphPx(".efh-mk__name","fontSize"),lineHeight:22,color:look.ink},stepWhen:{...body,fontSize:raphPx(".efh-mk__line","fontSize"),lineHeight:raphPx(".efh-mk__line","lineHeight"),color:look.muted},peek:{gap:12,marginTop:12},peekHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:12},peekLead:{...body,marginTop:-4,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},peekLabsTitle:{marginBottom:raphPx(".efh-peek__labs .efh-card__title","marginBottom")},peekGroup:{marginBottom:raphPx(".efh-peek__g","marginBottom")},peekGroupTitle:{...bold,fontSize:raphPx(".efh-peek__g b","fontSize"),lineHeight:lh100(raphPx(".efh-peek__g b","fontSize")*(raphPx(".efh-peek__g","lineHeight")/raphPx(".efh-peek__g","fontSize"))),color:look.ink},peekGroupLead:{...body,fontSize:raphPx(".efh-peek__g","fontSize"),lineHeight:raphPx(".efh-peek__g","lineHeight"),color:look.muted},more:{gap:10},moreCard:{gap:10,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},moreHead:{flexDirection:"row",alignItems:"center",gap:8},moreTitle:{...bold,fontSize:16,lineHeight:lh(16,1.3),color:look.ink},moreLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},moreRows:{gap:6},moreRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:44,paddingVertical:8,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.card},moreRowLabel:{...body,flexShrink:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.text},moreWhen:{...mono,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.24,color:look.muted},note:{...body,marginTop:raphPx(".efh-sheet .rec-note","marginTop"),fontSize:raphPx(".rec-note","fontSize"),textAlign:"center",color:look.muted},mks:{gap:2,marginHorizontal:-8},mk:{flexDirection:"row",alignItems:"center",gap:12,paddingVertical:10,paddingHorizontal:8},mkText:{flex:1,minWidth:0},mkNameRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:8},mkName:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},mkLine:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",rowGap:raphPx(".efh-mk__line","rowGap"),columnGap:raphPx(".efh-mk__line","columnGap"),marginTop:raphPx(".efh-mk__line","marginTop")},mkLineText:{...body,fontSize:raphPx(".efh-mk__line","fontSize"),lineHeight:raphPx(".efh-mk__line","lineHeight"),color:look.muted,fontVariant:["tabular-nums"]},mkValue:{...bold,fontSize:raphPx(".efh-mk__line b","fontSize"),lineHeight:lh100(raphPx(".efh-mk__line b","fontSize")*(raphPx(".efh-mk__line","lineHeight")/raphPx(".efh-mk__line","fontSize"))),color:look.text,fontVariant:["tabular-nums"]},mkBar:{position:"relative",width:96,height:6,borderRadius:999,backgroundColor:look.barTrack},mkBarIn:{position:"absolute",top:0,bottom:0,left:"20%",right:"20%",borderRadius:999},mkBarDot:{position:"absolute",top:-2,width:10,height:10,marginLeft:-5,borderRadius:5,borderWidth:2},topRisk:{gap:8,backgroundColor:look.topFill,borderRadius:22,borderWidth:0,shadowOpacity:0,elevation:0},topRiskKicker:{flexDirection:"row",alignItems:"center",gap:6},topRiskDot:{width:8,height:8,borderRadius:4,backgroundColor:look.alert},topRiskK:{...monoBold,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.72,textTransform:"uppercase",color:look.topKicker},topRiskText:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.35),color:look.topInk},disclaimer:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),textAlign:"center",color:look.muted},lab:{gap:RAPH_RN_METRICS.gap,paddingTop:8,paddingHorizontal:16,paddingBottom:32,backgroundColor:look.ground},labTitle:{...face(theme,"medium"),fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.33,color:look.ink},labMeta:{...mono,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.45),color:look.muted},latest:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",columnGap:12,rowGap:4},latestSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look.muted},change:{...body,marginTop:12,fontSize:RAPH_RN_METRICS.body,color:look.text},changeLead:{...bold,color:look.ink},ctx:{gap:12},ctxText:{...body,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.55),color:look.text},labBody:{flexDirection:"row",gap:8},rail:{width:8,height:RAPH_RN_METRICS.plot,overflow:"hidden",borderRadius:2},legend:{width:82,height:RAPH_RN_METRICS.plot,position:"relative"},range:{...monoBold,position:"absolute",left:0,right:0,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.2),letterSpacing:.24,textTransform:"uppercase",color:look.dark?look.text:RAPH_CHARCOAL},band:{position:"absolute",left:0,right:0,top:"25%",height:"50%",backgroundColor:look.goTint}})}var RAPH_CHARCOAL="#3D3D3D",TRACKER_DOT=28,lh100=value=>Math.round(value*100)/100;function EverfurRecordsLabDetail({petRef:petRef,petName:petName,markerId:markerId,renderExtra:renderExtra,onAsk:onAsk,renderAskButton:renderAskButton,style:style}){let view=useRecordsMarkers(petRef).markers,model=view===null||view.withheld?null:buildSheetLabModel(view,markerId);if(model===null)return null;let marker=view?.markers.find(m=>m.markerId===markerId)??null;/* @__PURE__ */
755
949
  return jsx(LabBody,{model:model,renderExtra:renderExtra,ask:onAsk!==void 0&&marker!==null?()=>{let built=buildMarkerAskPrompt(petName,{canonicalName:marker.name,markerId:marker.markerId,latestValueText:model.latest,statusText:model.pill,trajectoryText:null,meaningText:marker.meaning});onAsk(built.prompt,built.entityRef)}:void 0,renderAskButton:renderAskButton,style:style})}function LabBody({model:model,renderExtra:renderExtra,ask:ask,renderAskButton:renderAskButton,style:style}){let{s:s,look:look}=useSheetKit();/* @__PURE__ */
756
950
  return jsxs(ScrollView,{contentContainerStyle:[s.lab,style],testID:`everfur-records-lab-${model.markerId}`,children:[
757
951
  /* @__PURE__ */jsxs(View,{children:[
@@ -780,111 +974,31 @@ return jsxs(View,{style:s.chart,accessibilityElementsHidden:true,importantForAcc
780
974
  /* @__PURE__ */jsx(Text,{style:[s.range,{top:"44%"}],children:SHEET_COPY.inRange}),
781
975
  /* @__PURE__ */jsx(Text,{style:[s.range,{top:"82%"}],children:SHEET_COPY.below})]})]}):null,
782
976
  /* @__PURE__ */jsxs(View,{style:[s.plot,{flex:1}],children:[banded?/* @__PURE__ */jsx(View,{style:s.band}):null,model.chart.length>1?/* @__PURE__ */jsx(ChartLine,{points:model.chart,color:look.ink}):null,model.chart.map((p,i)=>/* @__PURE__ */jsx(View,{style:[s.point,{left:`${p.x}%`,top:`${p.y}%`,backgroundColor:p.out?look.alert:look.ink}],children:/* @__PURE__ */jsx(Text,{style:[s.pointLabel,p.out?{color:look.alert}:null],children:p.label})},i))]})]}),
783
- /* @__PURE__ */jsx(View,{style:[s.xAxis,banded?{marginLeft:106}:null],children:model.chart.map((p,i)=>/* @__PURE__ */jsx(Text,{style:[s.xTick,{left:`${p.x}%`}],children:p.tick},i))})]})}var LB_PER_KG2=2.20462,kgToLb=kg=>Math.round(kg*LB_PER_KG2*10)/10,kg1=kg=>Math.round(kg*10)/10;function capitalize(text4){return text4.length===0?text4:text4.charAt(0).toUpperCase()+text4.slice(1)}function pronounFromSex(sex){return sex==="female"?"her":sex==="male"?"his":null}function rnSheetWords(name,pronoun){let trimmed=name?.trim()??"",shown=trimmed.length>0?trimmed:NAMELESS_PET,words2=sheetPetWords(shown,pronoun);/* @__PURE__ */
784
- return Object.freeze({...words2,Poss:capitalize(words2.Poss)})}function rnSheetHeading(name){let trimmed=name?.trim()??"";return trimmed.length>0?trimmed:RECORD_SCREEN_COPY.document.namelessPet}var DOG_ONLY_ROW=/heartworm|4dx/i;function rnSamplePeek(species){let dog=canonicalPetSpecies(species??null)==="dog",more=SHEET_SAMPLE.more.map(card=>({card:card,rows:dog?card.rows:card.rows.filter(row=>!DOG_ONLY_ROW.test(row.label))})).filter(entry=>entry.rows.length>0);return{labsTitle:SHEET_SAMPLE.labsTitle,group:SHEET_SAMPLE.group,groupLead:SHEET_SAMPLE.groupLead,markers:SHEET_SAMPLE.markers,more:more}}var ONE_READING_LINE="One reading so far: we’ll plot a trend as more come in.";function readingsKg(timeline){return timeline===null||timeline.withheld?[]:timeline.weights.flatMap(w=>{let ms=dayMs(w.observedOn);return ms===null||w.weightKg===null?[]:[{ms:ms,kg:w.weightKg}]}).sort((a,b)=>a.ms-b.ms)}function rnWeight(shared,timeline,unit){if(shared===null)return null;let readings=readingsKg(timeline),last=readings[readings.length-1];if(last===void 0||readings.length!==shared.points.length)return{latest:shared.latest,sub:shared.sub,points:shared.points.map(p=>({x:p.x,y:p.y,label:String(p.lb),ms:p.ms})),ticks:shared.ticks,vetCount:shared.vetCount,single:shared.points.length===1};let label=kg=>unit==="kg"?num4(kg1(kg)):num4(kgToLb(kg)),latest=unit==="kg"?`${num4(kg1(last.kg))} kg`:`${num4(kgToLb(last.kg))} lb`,sub=unit==="kg"?`${num4(kgToLb(last.kg))} lb · ${shortDate(last.ms)}`:`${num4(kg1(last.kg))} kg · ${shortDate(last.ms)}`;return{latest:latest,sub:sub,points:shared.points.map((p,i)=>({x:p.x,y:p.y,label:label(readings[i]?.kg??last.kg),ms:p.ms})),ticks:shared.ticks,vetCount:shared.vetCount,single:shared.points.length===1}}function rnMeta(breed,weight,petWeightKg,unit){let w=weight?.latest??(petWeightKg==null?null:unit==="kg"?`${num4(kg1(petWeightKg))} kg`:`${num4(kgToLb(petWeightKg))} lb`),parts=[breed?.trim()||null,w].filter(p=>p!==null);return parts.length>0?parts.join(" · "):null}var RN_SHEET_APP_COPY=/* @__PURE__ */Object.freeze({noDueDate:"No due date on file",noVisits:pet=>`No visits in ${pet}’s records yet. They show up here when a record includes one.`,medications:entityTypeLabel("medication"),noCurrentMedications:"No current medications on file.",oneReading:ONE_READING_LINE,topRiskKicker:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`}),RECORDS_SHEET_RN_COPY=/* @__PURE__ */Object.freeze({undatedPill:""});function rnCurrentMedications(timeline,nowMs){if(timeline===null||timeline.withheld)return null;let current=m=>{let stop=dayMs(m.stoppedOn);return stop===null||stop>=nowMs};return timeline.medications.filter(m=>current(m)&&(m.drugName?.trim()??"").length>0).map((m,i)=>{let parts=[m.dose,m.route,m.frequency].filter(p=>typeof p=="string"&&p.trim().length>0);return{key:`${m.medicationId}-${i}`,title:(m.drugName??"").trim(),detail:parts.length>0?parts.join(" · "):null}})}function rnFailedRequest(requests,petRef){let mine=requests.filter(r=>r.petRef===petRef);if(mine.some(r=>!isTerminalStatus(r.status)))return null;let latest=[...mine].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(latest===void 0||latest.status!=="failed"&&latest.status!=="revoked")return null;let label=selectPrimaryLabel(latest).trim();return label.length>0?{id:latest.id,label:label}:null}function rnTopRiskText(focus){if(focus==null)return null;let risk=[focus.risk?.lead?.trim()??"",focus.risk?.body?.trim()??""].filter(p=>p.length>0).join(" ");if(risk.length>0)return risk;let title=focus.title.trim();return title.length>0?title:null}function planPageSex(pet){return pet?.sex??null}function recordSex(record){if(record==null||record.withheld)return null;let value=record.identity.find(r=>r.label.trim().toLowerCase()==="sex")?.value.trim().toLowerCase()??"";return value.length===0?null:/\bfemale\b/.test(value)||/^(f|fs)$/.test(value)?"female":/\bmale\b/.test(value)||/^(m|mn)$/.test(value)?"male":null}var readDepth4=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty4=value=>!value.available,readTimeline2=(client,petRef)=>client.getTimeline(petRef),timelineEmpty2=value=>value.isEmpty,NO_OPTIONS=/* @__PURE__ */Object.freeze({});function EverfurRecordsSheet(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),kit=useSheetKitValue();/* @__PURE__ */
785
- return jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsx(SheetKitProvider,{value:kit,children:/* @__PURE__ */jsx(SheetScreen,{...rest,style:style})})})}function SheetScreen({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,options:options=NO_OPTIONS,style:style}){let{s:s,look:look}=useSheetKit(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),markers=useRecordsMarkers(petRef),depth=useRecordsDepthRead(petRef,readDepth4,depthEmpty4),timeline=useRecordsDepthRead(petRef,readTimeline2,timelineEmpty2),{pets:pets}=useEverfurPets(),pet=pets.find(p=>p.petRef===petRef)??null,presentation=useEverfurPresentation(options.presentation??null);useConsentTextWarning2(consentVersion,consentText);let canGrant=useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),clinicDecision=useCapability("recordsClinic"),canRequest=clinicDecision.enabled||clinicDecision.isPending,[labOpen,setLabOpen]=useState(null),[clock]=useState(()=>options.nowMs??Date.now()),now=options.nowMs??clock,knownPronoun=options.pronoun??pronounFromSex(options.sex)??pronounFromSex(recordSex(records.record))??null,needPlanForSex=knownPronoun===null&&records.status!=="loading",planCapability=useCapability("healthPlan"),plan=useHealthPlanPage({petRef:petRef,enabled:planCapability.enabled&&(presentation.recordsTopRiskLine||needPlanForSex)}),planPet=plan.page?.pet??null,pronoun=knownPronoun??pronounFromSex(planPageSex(planPet)),name=petName?.trim()||pet?.name?.trim()||planPet?.name?.trim()||"",species=options.species??pet?.species??planPet?.species??null,unit=options.weightUnit??"lb",words2=rnSheetWords(name,pronoun),copy={...RECORDS_SHEET_RN_COPY,...options.copy??{}},model=useMemo(()=>buildRecordsSheetModel({words:words2,record:records.record,depth:depth.value,markers:markers.markers,timeline:timeline.value,requests:records.requests,breed:pet?.breed??planPet?.breed??null,petWeightKg:pet?.weightKg??planPet?.weightKg??null,nowMs:now}),[name,pronoun,records.record,records.requests,depth.value,markers.markers,timeline.value,pet,planPet,now]),weight=rnWeight(model.weight,timeline.value,unit),meta=rnMeta(pet?.breed??planPet?.breed??null,weight,pet?.weightKg??planPet?.weightKg??null,unit),failed=rnFailedRequest(records.requests,petRef),topRisk=presentation.recordsTopRiskLine?rnTopRiskText(plan.page?.page?.focus):null,meds=rnCurrentMedications(timeline.value,now),disclaimer=[markers.markers?.disclaimer,records.record?.disclaimer,timeline.value?.disclaimer].map(d=>d?.trim()??"").find(d=>d.length>0)??"";useEffect(()=>{if(labOpen===null)return;let sub=BackHandler.addEventListener("hardwareBackPress",()=>(setLabOpen(null),true));return()=>{sub.remove()}},[labOpen]);let openMarker=markerId=>{options.onOpenMarker!==void 0?options.onOpenMarker(markerId):setLabOpen(markerId)},go={request:()=>onNavigate?.({name:"clinicPicker"}),upload:()=>onNavigate?.({name:"upload"}),record:()=>onNavigate?.({name:"record"}),timeline:()=>onNavigate?.({name:"timeline"})},retryAll=()=>{records.refresh(),markers.refresh(),depth.refresh(),timeline.refresh()},canAct=onNavigate!==void 0;if(labOpen!==null)/* @__PURE__ */
977
+ /* @__PURE__ */jsx(View,{style:[s.xAxis,banded?{marginLeft:106}:null],children:model.chart.map((p,i)=>/* @__PURE__ */jsx(Text,{style:[s.xTick,{left:`${p.x}%`}],children:p.tick},i))})]})}function capitalize(text4){return text4.length===0?text4:text4.charAt(0).toUpperCase()+text4.slice(1)}function pronounFromSex(sex){return sex==="female"?"her":sex==="male"?"his":null}function rnSheetWords(name,pronoun){let trimmed=name?.trim()??"",shown=trimmed.length>0?trimmed:NAMELESS_PET,words2=sheetPetWords(shown,pronoun);/* @__PURE__ */
978
+ return Object.freeze({...words2,Poss:capitalize(words2.Poss)})}function rnSheetHeading(name){let trimmed=name?.trim()??"";return trimmed.length>0?trimmed:RECORD_SCREEN_COPY.document.namelessPet}var RN_SHEET_APP_COPY=/* @__PURE__ */Object.freeze({topRiskKicker:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`,today:"Today"});function rnOpenRequest(requests,petRef){return requests.filter(r=>r.petRef===petRef&&!isTerminalStatus(r.status)).sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0]??null}function isOwnerUpload(request){return request.source==="owner_provided"}function rnTrackerSteps(status){switch(status){case"received":case"parsing":case"in_review":case"published":return["done","done","now"];case"awaiting_clinic":return["done","now","next"];default:return["now","next","next"]}}var MONTH_SHORT2=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function rnTrackerWhen(iso,nowMs){let ms2=dayMs(iso);if(ms2===null)return null;let d=new Date(ms2),now=new Date(nowMs),sameDay=d.getFullYear()===now.getFullYear()&&d.getMonth()===now.getMonth()&&d.getDate()===now.getDate(),h=d.getHours(),time=`${h%12===0?12:h%12}:${String(d.getMinutes()).padStart(2,"0")} ${h<12?"AM":"PM"}`;return`${sameDay?RN_SHEET_APP_COPY.today:`${MONTH_SHORT2[d.getMonth()]??""} ${d.getDate()}`}, ${time}`}var RECORDS_SHEET_RN_COPY=/* @__PURE__ */Object.freeze({undatedPill:""});function rnFailedRequest(requests,petRef){let mine=requests.filter(r=>r.petRef===petRef);if(mine.some(r=>!isTerminalStatus(r.status)))return null;let latest=[...mine].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(latest===void 0||latest.status!=="failed"&&latest.status!=="revoked")return null;let label=selectPrimaryLabel(latest).trim();return label.length>0?{id:latest.id,label:label}:null}function rnTopRiskText(focus){if(focus==null)return null;let risk=[focus.risk?.lead?.trim()??"",focus.risk?.body?.trim()??""].filter(p=>p.length>0).join(" ");if(risk.length>0)return risk;let title=focus.title.trim();return title.length>0?title:null}function planPageSex(pet){return pet?.sex??null}function recordSex(record){if(record==null||record.withheld)return null;let value=record.identity.find(r=>r.label.trim().toLowerCase()==="sex")?.value.trim().toLowerCase()??"";return value.length===0?null:/\bfemale\b/.test(value)||/^(f|fs)$/.test(value)?"female":/\bmale\b/.test(value)||/^(m|mn)$/.test(value)?"male":null}var readDepth4=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty4=value=>!value.available,readTimeline2=(client,petRef)=>client.getTimeline(petRef),timelineEmpty2=value=>value.isEmpty,NO_OPTIONS=/* @__PURE__ */Object.freeze({});function EverfurRecordsSheet(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),kit=useSheetKitValue();/* @__PURE__ */
979
+ return jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsx(SheetKitProvider,{value:kit,children:/* @__PURE__ */jsx(HubKitProvider,{handFamily:rest.options?.stage?.handFontFamily??null,children:/* @__PURE__ */jsx(SheetScreen,{...rest,style:style})})})})}function SheetScreen({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,options:options=NO_OPTIONS,style:style}){let{s:s,look:look}=useSheetKit(),hub=useHub(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),markers=useRecordsMarkers(petRef),depth=useRecordsDepthRead(petRef,readDepth4,depthEmpty4),timeline=useRecordsDepthRead(petRef,readTimeline2,timelineEmpty2),{pets:pets}=useEverfurPets(),pet=pets.find(p=>p.petRef===petRef)??null,presentation=useEverfurPresentation(options.presentation??null);useConsentTextWarning2(consentVersion,consentText);let canGrant=useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),clinicDecision=useCapability("recordsClinic"),canRequest=clinicDecision.enabled||clinicDecision.isPending,[labOpen,setLabOpen]=useState(null),active=options.active??true,[foreground,setForeground]=useState(()=>AppState.currentState!=="background");useEffect(()=>{let subscription=AppState.addEventListener("change",state2=>setForeground(state2==="active"));return()=>subscription.remove()},[]);let now=useCoarseNow(options.nowMs,active&&foreground),knownPronoun=options.pronoun??pronounFromSex(options.sex)??pronounFromSex(recordSex(records.record))??null,needPlanForSex=knownPronoun===null&&records.status!=="loading",planCapability=useCapability("healthPlan"),plan=useHealthPlanPage({petRef:petRef,enabled:planCapability.enabled&&(presentation.recordsTopRiskLine||needPlanForSex)}),planPet=plan.page?.pet??null,pronoun=knownPronoun??pronounFromSex(planPageSex(planPet)),name=petName?.trim()||pet?.name?.trim()||planPet?.name?.trim()||"",species=options.species??pet?.species??planPet?.species??null,unit=options.weightUnit??"lb",words2=rnSheetWords(name,pronoun),breed=pet?.breed??planPet?.breed??null,model=useMemo(()=>buildRecordsSheetModel({words:words2,record:records.record,depth:depth.value,markers:markers.markers,timeline:timeline.value,requests:records.requests,breed:breed,petWeightKg:pet?.weightKg??planPet?.weightKg??null,nowMs:now}),[name,pronoun,records.record,records.requests,depth.value,markers.markers,timeline.value,pet,planPet,now]),weight=useMemo(()=>hubWeight(records.record,timeline.value,unit),[records.record,timeline.value,unit]),meta=hubMeta(breed,pet?.ageYears??null,weight),failed=rnFailedRequest(records.requests,petRef),topRisk=presentation.recordsTopRiskLine?rnTopRiskText(plan.page?.page?.focus):null,disclaimer=[markers.markers?.disclaimer,records.record?.disclaimer,timeline.value?.disclaimer].map(d=>d?.trim()??"").find(d=>d.length>0)??"";useEffect(()=>{if(labOpen===null||!active)return;let sub=BackHandler.addEventListener("hardwareBackPress",()=>(setLabOpen(null),true));return()=>{sub.remove()}},[labOpen,active]);let openMarker=markerId=>{options.onOpenMarker!==void 0?options.onOpenMarker(markerId):setLabOpen(markerId)},openRequest=rnOpenRequest(records.requests,petRef),canAct=onNavigate!==void 0,go={request:()=>{if(options.onRequestFromClinic!==void 0){let result=options.onRequestFromClinic({petRef:petRef});result!==void 0&&typeof result.then=="function"&&result.then(void 0,()=>{})}else onNavigate?.({name:"clinicPicker"})},upload:()=>onNavigate?.({name:"upload"}),record:()=>onNavigate?.({name:"record"}),timeline:()=>onNavigate?.({name:"timeline"})},retryAll=()=>{records.refresh(),markers.refresh(),depth.refresh(),timeline.refresh()};if(labOpen!==null)/* @__PURE__ */
786
980
  return jsxs(View,{style:[{flex:1,backgroundColor:look.ground},style],children:[
787
981
  /* @__PURE__ */jsx(ScreenHeader,{title:rnSheetHeading(name),onBack:()=>setLabOpen(null),testID:"everfur-records-lab-header"}),
788
982
  /* @__PURE__ */jsx(EverfurRecordsLabDetail,{petRef:petRef,markerId:labOpen,...name.length>0?{petName:name}:{},...onAsk?{onAsk:onAsk}:{}}),
789
- /* @__PURE__ */jsx(RecordsFootnote,{})]});let body,state="full";if(records.status==="loading"&&records.record===null)body=/* @__PURE__ */jsx(DashboardSkeleton,{testID:"everfur-records-sheet-loading"}),state="loading";else if(records.status==="error"){let view=selectErrorView(records,canGrant);isConsentGate(view)?(state="consent",body=/* @__PURE__ */jsxs(ScrollView,{contentContainerStyle:[s.sheet,options.style],children:[renderErrorFamily(records,onGrant,canGrant,consentText),canAct?/* @__PURE__ */jsx(AddCard,{words:words2,model:null,canRequest:canRequest,onRequest:go.request,onUpload:go.upload}):null]})):view.kind==="error"||view.kind==="pet_not_found"?(state="error",body=/* @__PURE__ */jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(view.error),message:view.error.displayMessage,onAction:view.error.retryable?retryAll:void 0,testID:"everfur-records-sheet-error"})):(state=view.kind,body=renderErrorFamily(records,onGrant,canGrant,consentText))}else{state=model.state;let failedLine=failed!==null?/* @__PURE__ */jsx(FailedLine,{label:failed.label,onPress:canAct?()=>onNavigate?.({name:"request",requestId:failed.id}):void 0}):null,foot=disclaimer.length>0&&!disclaimerRepeatsFootnote(disclaimer)?/* @__PURE__ */jsx(Text,{style:s.disclaimer,testID:"everfur-records-sheet-disclaimer",children:disclaimer}):null;body=model.state!=="full"?/* @__PURE__ */jsxs(ScrollView,{contentContainerStyle:[s.sheet,options.style],children:[failedLine,
790
- /* @__PURE__ */jsx(NoneCard,{words:words2,model:model,canAct:canAct,canRequest:canRequest,onRequest:go.request,onUpload:go.upload}),
791
- /* @__PURE__ */jsx(SamplePeek,{words:words2,species:species}),
792
- /* @__PURE__ */jsx(Text,{style:s.note,children:SHEET_COPY.sampleNote(words2)}),foot]}):/* @__PURE__ */jsxs(ScrollView,{contentContainerStyle:[s.sheet,options.style],children:[options.renderTopSlot!==void 0?/* @__PURE__ */jsx(HostRender,{render:()=>options.renderTopSlot?.({clearResultsFilter:presentation.recordsClearResultsFilter})??null,fallback:null,resetKey:petRef}):null,
793
- /* @__PURE__ */jsx(Head,{words:words2,name:name,meta:meta,model:model,renderStage:options.renderStage}),topRisk!==null?/* @__PURE__ */jsx(TopRisk,{words:words2,text:topRisk,onOpenPlan:options.onOpenPlan}):null,failedLine,
794
- /* @__PURE__ */jsx(Upcoming,{due:model.due,copy:copy,renderAction:options.renderUpcomingCareAction}),
795
- /* @__PURE__ */jsx(Tiles,{words:words2,model:model,onOpenMarker:openMarker,onOpenScreenings:options.onOpenScreenings,onOpenRecord:canAct?go.record:void 0,onOpenTimeline:canAct?go.timeline:void 0}),
796
- /* @__PURE__ */jsx(WeightCard,{weight:weight}),
797
- /* @__PURE__ */jsx(History,{words:words2,model:model,onOpenMarker:openMarker}),meds!==null?/* @__PURE__ */jsx(Medications,{meds:meds}):null,canAct?/* @__PURE__ */jsx(AddCard,{words:words2,model:model,canRequest:canRequest,onRequest:go.request,onUpload:go.upload}):null,foot]})}/* @__PURE__ */
798
- return jsxs(View,{style:[{flex:1,backgroundColor:look.ground},style],testID:"everfur-records-sheet",children:[onBack!==void 0?/* @__PURE__ */jsx(ScreenHeader,{title:DASHBOARD_COPY.titleNative(petName),onBack:onBack,testID:"everfur-records-sheet-header"}):null,
799
- /* @__PURE__ */jsx(View,{style:{flex:1},testID:`everfur-records-sheet-state-${state}`,children:body}),
800
- /* @__PURE__ */jsx(RecordsFootnote,{})]})}function Head({words:words2,name:name,meta:meta,model:model,renderStage:renderStage}){let{s:s,look:look}=useSheetKit(),vitals=model.vitals.length===0?null:/* @__PURE__ */jsx(View,{style:s.vitals,testID:"everfur-records-sheet-vitals",children:model.vitals.map(v=>/* @__PURE__ */jsxs(View,{style:s.vital,accessible:true,accessibilityLabel:`${v.label} ${v.value}${v.unit?` ${v.unit}`:""}`,children:[
801
- /* @__PURE__ */jsxs(View,{style:s.vitalTop,children:[
802
- /* @__PURE__ */jsx(SheetIcon,{kind:v.kind==="temp"?"thermo":v.kind==="heart"?"heart":"wind",size:18,color:v.kind==="heart"?look.alert:look.chevron}),
803
- /* @__PURE__ */jsx(Text,{style:s.vitalValue,children:v.value}),v.unit?/* @__PURE__ */jsx(Text,{style:s.vitalUnit,children:v.unit}):null]}),
804
- /* @__PURE__ */jsx(Text,{style:s.vitalLabel,children:v.label})]},v.kind))});/* @__PURE__ */
805
- return jsxs(View,{style:s.head,testID:"everfur-records-sheet-head",children:[
806
- /* @__PURE__ */jsx(Text,{style:s.name,accessibilityRole:"header",testID:"everfur-records-sheet-name",children:name.length>0?words2.name:rnSheetHeading(name)}),meta!==null?/* @__PURE__ */jsx(Text,{style:s.meta,testID:"everfur-records-sheet-meta",children:meta}):null,renderStage!==void 0?/* @__PURE__ */jsx(HostRender,{render:renderStage,fallback:null,resetKey:name}):null,vitals,model.vitalsFrom!==null?/* @__PURE__ */jsx(Text,{style:s.label,children:model.vitalsFrom}):null]})}function TopRisk({words:words2,text:text4,onOpenPlan:onOpenPlan}){let{s:s}=useSheetKit();/* @__PURE__ */
983
+ /* @__PURE__ */jsx(RecordsFootnote,{})]});let body,state="full",onHub=true,failedLine=failed!==null?/* @__PURE__ */jsx(FailedLine,{label:failed.label,onPress:canAct?()=>onNavigate?.({name:"request",requestId:failed.id}):void 0}):null,topSlot=options.renderTopSlot!==void 0?/* @__PURE__ */jsx(View,{style:[s.topSlot,{marginBottom:APP_HUB.screen.gap}],testID:"everfur-records-sheet-top-slot",children:/* @__PURE__ */jsx(HostRender,{render:()=>options.renderTopSlot?.({clearResultsFilter:presentation.recordsClearResultsFilter})??null,fallback:null,resetKey:petRef})}):null,foot=disclaimer.length>0&&!disclaimerRepeatsFootnote(disclaimer)?/* @__PURE__ */jsx(HubDisclaimer,{text:disclaimer}):null,column={paddingHorizontal:APP_HUB.screen.padX,gap:APP_HUB.screen.gap},hero=say=>/* @__PURE__ */jsx(HubHero,{name:name.length>0?words2.Name:rnSheetHeading(name),meta:meta,stage:options.stage,say:say,vitals:say?[]:model.vitals,vitalsName:words2.name,renderStage:options.renderStage});if(records.status==="loading"&&records.record===null)body=/* @__PURE__ */jsx(DashboardSkeleton,{testID:"everfur-records-sheet-loading"}),state="loading",onHub=false;else if(records.status==="error"){let view=selectErrorView(records,canGrant);isConsentGate(view)?(state="consent",body=/* @__PURE__ */jsx(ScrollView,{contentContainerStyle:{paddingBottom:APP_HUB.screen.padBottom},children:/* @__PURE__ */jsxs(View,{style:column,testID:"everfur-records-sheet-content",children:[renderErrorFamily(records,onGrant,canGrant,consentText),canAct?/* @__PURE__ */jsx(HubAddRecords,{words:words2,sources:[],canRequest:canRequest,onRequest:go.request,onUpload:go.upload}):null,
984
+ /* @__PURE__ */jsx(HubLegal,{})]})})):view.kind==="error"||view.kind==="pet_not_found"?(state="error",onHub=false,body=/* @__PURE__ */jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(view.error),message:view.error.displayMessage,onAction:view.error.retryable?retryAll:void 0,testID:"everfur-records-sheet-error"})):(state=view.kind,onHub=false,body=renderErrorFamily(records,onGrant,canGrant,consentText))}else if(model.state!=="full")state=openRequest===null?"none":isOwnerUpload(openRequest)?"processing":"onTheWay",body=/* @__PURE__ */jsx(ScrollView,{contentContainerStyle:{paddingBottom:APP_HUB.screen.padBottom},children:/* @__PURE__ */jsxs(View,{testID:"everfur-records-sheet-content",style:options.style,children:[topSlot,
985
+ /* @__PURE__ */jsxs(View,{style:column,children:[hero(true),failedLine,state==="onTheWay"&&openRequest!==null?/* @__PURE__ */jsx(HubOnTheWay,{words:words2,request:openRequest,steps:rnTrackerSteps(openRequest.status),sentWhen:rnTrackerWhen(openRequest.createdAt,now),canAct:canAct,canRequest:canRequest,onAnotherClinic:go.request,onUpload:go.upload}):state==="processing"&&openRequest!==null?/* @__PURE__ */jsx(HubInProgress,{words:words2,request:openRequest}):/* @__PURE__ */jsx(HubPrompt,{title:options.noVet===true?HUB_COPY.noVetTitle(words2):HUB_COPY.addRecords(words2.name),canAct:canAct,canRequest:canRequest,onRequest:go.request,onUpload:go.upload}),
986
+ /* @__PURE__ */jsx(HubSamplePeek,{name:words2.name,species:species}),foot,
987
+ /* @__PURE__ */jsx(HubLegal,{})]})]})});else{let rows=hubUpcoming(records.record?.forwardLooking??[],now),items=new Map((records.record?.forwardLooking??[]).map(item=>[item.careItemKey?.trim()||item.title,item])),tiles=hubTiles(records.record,markers.markers,depth.value,timeline.value),featured=model.featuredMarkerId,partialFailed=markers.status==="error"||timeline.status==="error",partialError=(markers.status==="error"?markers.error:null)??(timeline.status==="error"?timeline.error:null);body=/* @__PURE__ */jsx(ScrollView,{contentContainerStyle:{paddingBottom:APP_HUB.screen.padBottom},children:/* @__PURE__ */jsxs(View,{testID:"everfur-records-sheet-content",style:options.style,children:[topSlot,
988
+ /* @__PURE__ */jsxs(View,{style:column,children:[hero(false),topRisk!==null?/* @__PURE__ */jsx(TopRisk,{words:words2,text:topRisk,onOpenPlan:options.onOpenPlan}):null,failedLine,partialFailed?
989
+ /* @__PURE__ */jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(partialError),onAction:retryAll,testID:"everfur-records-sheet-partial-error"}):null,rows.length>0?/* @__PURE__ */jsx(HubUpcoming,{rows:rows,items:items,onViewAll:canAct?go.timeline:void 0,renderAction:options.renderUpcomingCareAction}):/* @__PURE__ */jsx(HubUpcomingEmpty,{name:words2.name}),
990
+ /* @__PURE__ */jsx(HubTilesSection,{tiles:tiles,labsUnknown:markers.status==="loading"||markers.status==="error",onOpenLabs:featured!==null?()=>openMarker(featured):void 0,onOpenScreenings:options.onOpenScreenings,onOpenVisits:canAct?go.record:void 0,onOpenTimeline:canAct?go.timeline:void 0}),
991
+ /* @__PURE__ */jsx(HubWeightCard,{weight:weight,name:words2.name}),canAct?/* @__PURE__ */jsx(HubAddRecords,{words:words2,sources:hubOnFile(records.record),canRequest:canRequest,onRequest:go.request,onUpload:go.upload}):null,foot,
992
+ /* @__PURE__ */jsx(HubLegal,{})]})]})})}/* @__PURE__ */
993
+ return jsxs(View,{style:[{flex:1,backgroundColor:onHub?hub.look.bg:look.ground},style],testID:"everfur-records-sheet",children:[onBack!==void 0?/* @__PURE__ */jsx(ScreenHeader,{title:DASHBOARD_COPY.titleNative(petName),onBack:onBack,testID:"everfur-records-sheet-header"}):null,
994
+ /* @__PURE__ */jsx(View,{style:{flex:1},testID:`everfur-records-sheet-state-${state}`,children:body}),onHub?null:/* @__PURE__ */jsx(RecordsFootnote,{})]})}function HubDisclaimer({text:text4}){let{type:type}=useHub();/* @__PURE__ */
995
+ return jsx(Text,{style:[type("fine"),{textAlign:"center",marginTop:APP_HUB.screen.legalTop}],testID:"everfur-records-sheet-disclaimer",children:text4})}function TopRisk({words:words2,text:text4,onOpenPlan:onOpenPlan}){let{s:s}=useSheetKit();/* @__PURE__ */
807
996
  return jsxs(SheetCard,{style:s.topRisk,testID:"everfur-records-sheet-top-risk",children:[
808
997
  /* @__PURE__ */jsxs(View,{style:s.topRiskKicker,children:[
809
998
  /* @__PURE__ */jsx(View,{style:s.topRiskDot}),
810
999
  /* @__PURE__ */jsx(Text,{style:s.topRiskK,children:RN_SHEET_APP_COPY.topRiskKicker(words2)})]}),
811
1000
  /* @__PURE__ */jsx(Text,{style:s.topRiskText,children:text4}),onOpenPlan!==void 0?/* @__PURE__ */jsx(SheetButton,{kind:"ink",row:true,label:RN_SHEET_APP_COPY.seePlan(words2),onPress:onOpenPlan,testID:"everfur-records-sheet-top-risk-plan"}):null]})}function FailedLine({label:label,onPress:onPress}){let{s:s,look:look}=useSheetKit(),inner=/* @__PURE__ */jsxs(Fragment,{children:[
812
- /* @__PURE__ */jsx(Text,{style:s.failedText,children:label}),onPress!==void 0?/* @__PURE__ */jsx(SheetIcon,{kind:"chevron",size:20,color:look.alertDeep}):null]});return onPress!==void 0?/* @__PURE__ */jsx(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,style:s.failed,testID:"everfur-records-sheet-failed",children:inner}):/* @__PURE__ */jsx(View,{style:s.failed,testID:"everfur-records-sheet-failed",children:inner})}function Upcoming({due:due,copy:copy,renderAction:renderAction}){let{s:s,look:look}=useSheetKit();return due.length===0?null:/* @__PURE__ */jsxs(SheetCard,{testID:"everfur-records-sheet-upcoming",children:[
813
- /* @__PURE__ */jsx(Text,{style:[s.cardTitle,s.cardTitleGap],accessibilityRole:"header",children:SHEET_COPY.upcomingCare}),
814
- /* @__PURE__ */jsx(View,{style:s.due,children:due.map((d,index)=>{let alert=d.tone==="alert",undated=d.tone==="none"&&(d.item.dueAt??null)===null,when=d.when??(undated?RN_SHEET_APP_COPY.noDueDate:null);/* @__PURE__ */
815
- return jsxs(View,{style:[s.dueRow,alert?{backgroundColor:look.alertTint}:null],testID:`everfur-records-sheet-due-${index}`,children:[
816
- /* @__PURE__ */jsx(SheetIcon,{kind:iconKindOf(d.icon),color:alert?look.alert:look.chevron}),
817
- /* @__PURE__ */jsxs(View,{style:s.dueText,children:[
818
- /* @__PURE__ */jsx(Text,{style:s.dueTitle,children:d.title}),when!==null?/* @__PURE__ */jsx(Text,{style:[s.dueWhen,alert?{color:look.alertDeep}:null],children:when}):null]}),alert&&renderAction!==void 0?/* @__PURE__ */jsx(HostRender,{render:()=>renderAction(d.item),fallback:null,resetKey:d.item}):d.pill!==null?/* @__PURE__ */jsx(SheetPill,{label:d.pill,tone:d.tone==="watch"?"watch":"later"}):undated?/* @__PURE__ */jsx(SheetPill,{label:copy.undatedPill,tone:"later"}):null]},`${d.title}-${index}`)})})]})}function tileGround(tint,look){return tint==="sage"?look.tintSage:tint==="emb"?look.tintPartner:tint==="blue"?look.tintBlue:look.tintYellow}function Tile({tint:tint,icon:icon,title:title,foot:foot,onOpen:onOpen,testID:testID}){let{s:s,look:look}=useSheetKit(),inner=/* @__PURE__ */jsxs(Fragment,{children:[
819
- /* @__PURE__ */jsxs(View,{style:s.tileTop,children:[
820
- /* @__PURE__ */jsx(SheetIcon,{kind:icon,color:look.ink}),onOpen!==void 0?/* @__PURE__ */jsx(SheetIcon,{kind:"chevron",size:20,color:look.chevron}):null]}),
821
- /* @__PURE__ */jsx(Text,{style:s.tileTitle,children:title}),
822
- /* @__PURE__ */jsx(View,{style:s.tileFoot,children:foot})]}),box3=[s.tile,{backgroundColor:tileGround(tint,look)}];return onOpen!==void 0?/* @__PURE__ */jsx(Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:title,style:box3,testID:testID,children:inner}):/* @__PURE__ */jsx(View,{style:box3,testID:testID,children:inner})}function Tiles({words:words2,model:model,onOpenMarker:onOpenMarker,onOpenScreenings:onOpenScreenings,onOpenRecord:onOpenRecord,onOpenTimeline:onOpenTimeline}){let{s:s}=useSheetKit(),featured=model.featuredMarkerId;/* @__PURE__ */
823
- return jsxs(View,{testID:"everfur-records-sheet-tiles",children:[
824
- /* @__PURE__ */jsx(Text,{style:[s.cardTitle,s.sec],accessibilityRole:"header",children:SHEET_COPY.recordsHistory}),
825
- /* @__PURE__ */jsxs(View,{style:s.tiles,children:[model.labsCount>0&&featured!==null?/* @__PURE__ */jsx(Tile,{tint:"sage",icon:"flask",title:SHEET_COPY.labs,onOpen:()=>onOpenMarker(featured),testID:"everfur-records-sheet-tile-labs",foot:/* @__PURE__ */jsxs(Fragment,{children:[
826
- /* @__PURE__ */jsx(Text,{style:s.tileNum,children:model.labsCount}),
827
- /* @__PURE__ */jsx(Text,{style:s.tileUnit,children:SHEET_COPY.results})]})}):null,onOpenScreenings!==void 0?/* @__PURE__ */jsx(Tile,{tint:"emb",icon:"shield",title:SHEET_COPY.screenings,onOpen:onOpenScreenings,foot:null,testID:"everfur-records-sheet-tile-screenings"}):null,
828
- /* @__PURE__ */jsx(Tile,{tint:"blue",icon:"folder",title:SHEET_COPY.visits,onOpen:onOpenRecord,testID:"everfur-records-sheet-tile-record",foot:model.latestVisit!==null?/* @__PURE__ */jsx(SheetPill,{label:model.latestVisit,tone:"plain",small:true}):/* @__PURE__ */jsx(Text,{style:s.emptyLine,testID:"everfur-records-sheet-no-visits",children:RN_SHEET_APP_COPY.noVisits(words2.name)})}),model.historyCount>0?/* @__PURE__ */jsx(Tile,{tint:"yellow",icon:"clock",title:SHEET_COPY.timeline,onOpen:onOpenTimeline,testID:"everfur-records-sheet-tile-timeline",foot:/* @__PURE__ */jsx(SheetPill,{label:SHEET_COPY.events(model.historyCount),tone:"plain",small:true})}):null]})]})}function WeightCard({weight:weight}){let{s:s,look:look}=useSheetKit();if(weight===null)return null;let labelAll=weight.points.length<=6;/* @__PURE__ */
829
- return jsxs(SheetCard,{testID:"everfur-records-sheet-weight",children:[
830
- /* @__PURE__ */jsx(View,{style:s.cardHead,children:/* @__PURE__ */jsx(Text,{style:s.cardTitle,accessibilityRole:"header",children:SHEET_COPY.weight})}),
831
- /* @__PURE__ */jsxs(View,{style:s.wt,children:[
832
- /* @__PURE__ */jsx(Text,{style:s.wtValue,testID:"everfur-records-sheet-weight-latest",children:weight.latest}),
833
- /* @__PURE__ */jsx(Text,{style:s.wtSub,children:weight.sub})]}),weight.single?
834
- /* @__PURE__ */jsx(Text,{style:[s.emptyLine,{marginTop:8}],testID:"everfur-records-sheet-weight-one",children:RN_SHEET_APP_COPY.oneReading}):/* @__PURE__ */jsxs(View,{style:s.chart,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[
835
- /* @__PURE__ */jsxs(View,{style:s.plot,children:[
836
- /* @__PURE__ */jsx(ChartLine,{points:weight.points,color:look.ink}),weight.points.map((p,i)=>{let last=i===weight.points.length-1;/* @__PURE__ */
837
- return jsx(View,{style:[s.point,{left:`${p.x}%`,top:`${p.y}%`,backgroundColor:look.ink}],children:labelAll||last?/* @__PURE__ */jsx(Text,{style:s.pointLabel,children:p.label}):null},`${p.ms}-${i}`)})]}),
838
- /* @__PURE__ */jsx(View,{style:s.xAxis,children:weight.ticks.map((t,i)=>/* @__PURE__ */jsx(Text,{style:[s.xTick,{left:`${t.x}%`}],children:t.label},`${t.label}-${i}`))}),
839
- /* @__PURE__ */jsxs(View,{style:s.key,children:[
840
- /* @__PURE__ */jsx(View,{style:s.keyDot}),
841
- /* @__PURE__ */jsx(Text,{style:s.keyText,children:SHEET_COPY.vetVisits(weight.vetCount)})]})]})]})}function Pull({step:step,pct:pct2,none:none}){let{s:s}=useSheetKit();/* @__PURE__ */
842
- return jsxs(View,{style:[s.pull,none===true?s.pullNone:null],accessibilityLiveRegion:"polite",testID:"everfur-records-sheet-pull",children:[
843
- /* @__PURE__ */jsx(Text,{style:s.pullStep,children:step}),
844
- /* @__PURE__ */jsx(View,{style:s.pullBar,children:/* @__PURE__ */jsx(View,{style:[s.pullFill,{width:`${pct2}%`}]})})]})}function HistoryRow({item:item,last:last,onOpenMarker:onOpenMarker}){let{s:s,look:look}=useSheetKit(),markerId=item.markerId,text4=/* @__PURE__ */jsxs(Fragment,{children:[
845
- /* @__PURE__ */jsx(Text,{style:s.tlDate,children:item.date}),
846
- /* @__PURE__ */jsx(Text,{style:s.tlTitle,children:item.title}),item.text!==null?/* @__PURE__ */jsx(Text,{style:s.tlText,children:item.text}):null]});/* @__PURE__ */
847
- return jsxs(View,{style:[s.tlItem,last?s.tlItemLast:null],children:[last?null:/* @__PURE__ */jsx(View,{style:s.tlRail}),
848
- /* @__PURE__ */jsx(View,{style:[s.tlDot,item.alert?{borderColor:look.alert}:null]}),
849
- /* @__PURE__ */jsx(View,{style:s.tlBody,children:markerId!==null?/* @__PURE__ */jsxs(Pressable,{onPress:()=>onOpenMarker(markerId),accessibilityRole:"button",accessibilityLabel:`${item.date}. ${item.title}`,style:s.tlBtn,testID:`everfur-records-sheet-history-marker-${markerId}`,children:[text4,
850
- /* @__PURE__ */jsx(View,{style:s.tlChevron,children:/* @__PURE__ */jsx(SheetIcon,{kind:"chevron",size:20,color:look.alert})})]}):text4})]})}function History({words:words2,model:model,onOpenMarker:onOpenMarker}){let{s:s}=useSheetKit();if(model.history.length===0&&model.pull===null)return null;let first=model.history[0];/* @__PURE__ */
851
- return jsxs(SheetCard,{testID:"everfur-records-sheet-history",children:[
852
- /* @__PURE__ */jsx(Text,{style:[s.cardTitle,s.cardTitleGap],accessibilityRole:"header",children:SHEET_COPY.history}),model.history.length>0?/* @__PURE__ */jsxs(View,{style:s.tlKey,children:[
853
- /* @__PURE__ */jsx(View,{style:s.tlKeyDot}),
854
- /* @__PURE__ */jsx(Text,{style:s.keyText,children:SHEET_COPY.theirClinic(words2)})]}):null,first!==void 0?/* @__PURE__ */jsx(Text,{style:s.tlYear,children:first.year}):null,model.pull!==null?/* @__PURE__ */jsx(Pull,{step:model.pull.step,pct:model.pull.pct}):null,model.history.map((year,y)=>/* @__PURE__ */jsxs(View,{children:[y>0?/* @__PURE__ */jsx(Text,{style:s.tlYear,children:year.year}):null,year.items.map((item,i)=>/* @__PURE__ */jsx(HistoryRow,{item:item,onOpenMarker:onOpenMarker,last:i===year.items.length-1},item.key))]},year.year))]})}function Medications({meds:meds}){let{s:s}=useSheetKit();/* @__PURE__ */
855
- return jsxs(SheetCard,{testID:"everfur-records-sheet-meds",children:[
856
- /* @__PURE__ */jsx(Text,{style:[s.cardTitle,s.cardTitleGap],accessibilityRole:"header",children:RN_SHEET_APP_COPY.medications}),meds.length===0?/* @__PURE__ */jsx(Text,{style:s.emptyLine,children:RN_SHEET_APP_COPY.noCurrentMedications}):/* @__PURE__ */jsx(View,{style:s.sources,children:meds.map(m=>/* @__PURE__ */jsxs(View,{style:s.source,children:[
857
- /* @__PURE__ */jsx(Text,{style:s.sourceLabel,children:m.title}),m.detail!==null?/* @__PURE__ */jsx(Text,{style:s.sourceDetail,children:m.detail}):null]},m.key))})]})}function AddCard({words:words2,model:model,canRequest:canRequest,onRequest:onRequest,onUpload:onUpload}){let{s:s,look:look}=useSheetKit(),sources=model?.sources??[];/* @__PURE__ */
858
- return jsxs(SheetCard,{style:s.add,testID:"everfur-records-sheet-add",children:[
859
- /* @__PURE__ */jsxs(View,{style:s.addHead,children:[
860
- /* @__PURE__ */jsx(SheetIcon,{kind:"clip",color:look.ink}),
861
- /* @__PURE__ */jsx(Text,{style:[s.cardTitle,{flexShrink:1}],accessibilityRole:"header",children:SHEET_COPY.addRecords(words2)})]}),
862
- /* @__PURE__ */jsx(Text,{style:s.addLead,children:SHEET_COPY.moreThanOneClinic}),sources.length>0?/* @__PURE__ */jsx(View,{style:s.sources,accessibilityLabel:SHEET_COPY.onFileNow,children:sources.map(src=>/* @__PURE__ */jsxs(View,{style:s.source,children:[
863
- /* @__PURE__ */jsx(Text,{style:s.sourceLabel,children:src.label}),
864
- /* @__PURE__ */jsx(Text,{style:s.sourceDetail,children:src.detail})]},src.label))}):null,
865
- /* @__PURE__ */jsxs(View,{style:s.addActs,children:[canRequest?/* @__PURE__ */jsx(SheetButton,{kind:"ink",icon:"download",label:SHEET_COPY.requestFromClinic,onPress:onRequest,testID:"everfur-records-sheet-request"}):null,
866
- /* @__PURE__ */jsx(SheetButton,{kind:"outline",icon:"upload",label:SHEET_COPY.uploadDocument,onPress:onUpload,testID:"everfur-records-sheet-upload"})]})]})}function NoneCard({words:words2,model:model,canAct:canAct,canRequest:canRequest,onRequest:onRequest,onUpload:onUpload}){let{s:s}=useSheetKit(),onTheWay=model.state==="onTheWay";/* @__PURE__ */
867
- return jsxs(SheetCard,{testID:"everfur-records-sheet-none",children:[
868
- /* @__PURE__ */jsx(Text,{style:s.noneTitle,accessibilityRole:"header",children:onTheWay?SHEET_COPY.onTheWay(words2):SHEET_COPY.firstRecord(words2)}),
869
- /* @__PURE__ */jsx(Text,{style:s.noneLead,children:onTheWay?SHEET_COPY.clinicsTake:SHEET_COPY.firstLead(words2)}),model.pull!==null?/* @__PURE__ */jsx(Pull,{step:model.pull.step,pct:model.pull.pct,none:true}):null,canAct?/* @__PURE__ */jsxs(View,{style:s.ways,testID:"everfur-records-sheet-none-ways",children:[canRequest?/* @__PURE__ */jsx(SheetWay,{kind:"ink",icon:"download",onPress:onRequest,testID:"everfur-records-sheet-none-request",title:onTheWay?SHEET_COPY.anotherClinic:SHEET_COPY.requestFromTheirClinic(words2),detail:onTheWay?SHEET_COPY.anotherClinicDetail:SHEET_COPY.requestDetail}):null,
870
- /* @__PURE__ */jsx(SheetWay,{kind:"drop",icon:"upload",onPress:onUpload,testID:"everfur-records-sheet-none-upload",title:SHEET_COPY.uploadDocument,detail:SHEET_COPY.uploadDetail})]}):null]})}function SamplePeek({words:words2,species:species}){let{s:s,look:look}=useSheetKit(),peek=rnSamplePeek(species);/* @__PURE__ */
871
- return jsxs(View,{style:s.peek,testID:"everfur-records-sheet-sample",children:[
872
- /* @__PURE__ */jsxs(View,{style:s.peekHead,children:[
873
- /* @__PURE__ */jsx(Text,{style:s.cardTitle,accessibilityRole:"header",children:SHEET_COPY.recordsHistory}),
874
- /* @__PURE__ */jsx(SheetPill,{label:SHEET_COPY.sample,tone:"plain"})]}),
875
- /* @__PURE__ */jsx(Text,{style:s.peekLead,children:SHEET_COPY.peekLead(words2)}),
876
- /* @__PURE__ */jsxs(SheetCard,{children:[
877
- /* @__PURE__ */jsx(Text,{style:[s.cardTitle,s.cardTitleGap],children:peek.labsTitle}),
878
- /* @__PURE__ */jsxs(Text,{style:s.peekGroup,children:[
879
- /* @__PURE__ */jsx(Text,{style:s.peekGroupTitle,children:peek.group}),` ${peek.groupLead}`]}),
880
- /* @__PURE__ */jsx(View,{style:s.mks,children:peek.markers.map(m=>/* @__PURE__ */jsx(SheetMarkerRow,{name:m.name,value:m.value,unit:m.unit,range:m.range,at:m.at,pill:m.high?SHEET_COPY.high:null},m.name))})]}),
881
- /* @__PURE__ */jsx(View,{style:s.more,testID:"everfur-records-sheet-sample-more",children:peek.more.map(({card:card,rows:rows})=>/* @__PURE__ */jsxs(View,{style:[s.moreCard,{backgroundColor:tileGround(card.tint,look)}],testID:`everfur-records-sheet-sample-${card.tint}`,children:[
882
- /* @__PURE__ */jsxs(View,{style:s.moreHead,children:[
883
- /* @__PURE__ */jsx(SheetIcon,{kind:iconKindOf(card.icon),color:look.ink}),
884
- /* @__PURE__ */jsx(Text,{style:s.moreTitle,children:card.title})]}),
885
- /* @__PURE__ */jsx(Text,{style:s.moreLead,children:card.lead(words2)}),
886
- /* @__PURE__ */jsx(View,{style:s.moreRows,children:rows.map(row=>/* @__PURE__ */jsxs(View,{style:s.moreRow,children:[
887
- /* @__PURE__ */jsx(Text,{style:s.moreRowLabel,children:row.label}),"pill"in row&&typeof row.pill=="string"?/* @__PURE__ */jsx(SheetPill,{label:row.pill,tone:row.tone==="clear"?"clear":"watch"}):/* @__PURE__ */jsx(Text,{style:s.moreWhen,children:row.when})]},row.label))})]},card.title))})]})}function EverfurRecordsFlow(props){let{petRef:petRef,petName:petName,controller:controller,clinicController:clinicController,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,consentVersion:consentVersion,consentText:consentText,ownerName:ownerName,onCaptureSignature:onCaptureSignature,initialScreen:initialScreen,onExit:onExit,style:style,renderPending:renderPending,onOpenUrl:onOpenUrl,onCopy:onCopy,onAsk:onAsk,location:location,sheet:sheet=true}=guardHostProps(props,["onExit"]),[nav,dispatch]=useReducer(recordsNavReducer,initialScreen,initialRecordsNav),screen=currentRecordsScreen(nav),depth=nav.stack.length;useEffect(()=>{let onBackPress=()=>depth<=1?false:(dispatch({type:"pop"}),true),subscription=BackHandler.addEventListener("hardwareBackPress",onBackPress);return()=>{subscription.remove()}},[depth]);let onNavigate=useCallback(to=>dispatch({type:"navigate",screen:to}),[]),onBack=useMemo(()=>popRecordsNav(nav).handled?()=>dispatch({type:"pop"}):onExit,[nav,onExit]),seams={onNavigate:onNavigate,...onBack?{onBack:onBack}:{},...petName!==void 0?{petName:petName}:{},...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{},...onAsk?{onAsk:onAsk}:{},...location?{location:location}:{}},records={...controller?{controller:controller}:{},...consentVersion!==void 0?{consentVersion:consentVersion}:{},...consentText!==void 0?{consentText:consentText}:{}},uploads={...onPickDocument?{onPickDocument:onPickDocument}:{},...onPickPhotos?{onPickPhotos:onPickPhotos}:{},...uploadTransport?{uploadTransport:uploadTransport}:{}},pending=renderPending?{renderPending:renderPending}:{};switch(screen.name){case"dashboard":return sheet!==false?/* @__PURE__ */jsx(EverfurRecordsSheet,{petRef:petRef,...seams,...records,...pending,...typeof sheet=="object"?{options:sheet}:{},style:style}):/* @__PURE__ */jsx(EverfurRecordsDashboard,{petRef:petRef,...seams,...records,...pending,style:style});case"request":/* @__PURE__ */
1001
+ /* @__PURE__ */jsx(Text,{style:s.failedText,children:label}),onPress!==void 0?/* @__PURE__ */jsx(SheetIcon,{kind:"chevron",size:20,color:look.alertDeep}):null]});return onPress!==void 0?/* @__PURE__ */jsx(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label,style:s.failed,testID:"everfur-records-sheet-failed",children:inner}):/* @__PURE__ */jsx(View,{style:s.failed,testID:"everfur-records-sheet-failed",children:inner})}function EverfurRecordsFlow(props){let{petRef:petRef,petName:petName,controller:controller,clinicController:clinicController,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,consentVersion:consentVersion,consentText:consentText,ownerName:ownerName,onCaptureSignature:onCaptureSignature,initialScreen:initialScreen,onExit:onExit,style:style,renderPending:renderPending,onOpenUrl:onOpenUrl,onCopy:onCopy,onAsk:onAsk,location:location,sheet:sheet=true}=guardHostProps(props,["onExit"]),[nav,dispatch]=useReducer(recordsNavReducer,initialScreen,initialRecordsNav),screen=currentRecordsScreen(nav),depth=nav.stack.length;useEffect(()=>{let onBackPress=()=>depth<=1?false:(dispatch({type:"pop"}),true),subscription=BackHandler.addEventListener("hardwareBackPress",onBackPress);return()=>{subscription.remove()}},[depth]);let onNavigate=useCallback(to=>dispatch({type:"navigate",screen:to}),[]),onBack=useMemo(()=>popRecordsNav(nav).handled?()=>dispatch({type:"pop"}):onExit,[nav,onExit]),seams={onNavigate:onNavigate,...onBack?{onBack:onBack}:{},...petName!==void 0?{petName:petName}:{},...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{},...onAsk?{onAsk:onAsk}:{},...location?{location:location}:{}},records={...controller?{controller:controller}:{},...consentVersion!==void 0?{consentVersion:consentVersion}:{},...consentText!==void 0?{consentText:consentText}:{}},uploads={...onPickDocument?{onPickDocument:onPickDocument}:{},...onPickPhotos?{onPickPhotos:onPickPhotos}:{},...uploadTransport?{uploadTransport:uploadTransport}:{}},pending=renderPending?{renderPending:renderPending}:{};switch(screen.name){case"dashboard":return sheet!==false?/* @__PURE__ */jsx(EverfurRecordsSheet,{petRef:petRef,...seams,...records,...pending,...typeof sheet=="object"?{options:sheet}:{},style:style}):/* @__PURE__ */jsx(EverfurRecordsDashboard,{petRef:petRef,...seams,...records,...pending,style:style});case"request":/* @__PURE__ */
888
1002
  return jsx(EverfurRecordsRequest,{petRef:petRef,requestId:screen.requestId,...seams,...records,...uploads,...pending,style:style});case"timeline":/* @__PURE__ */
889
1003
  return jsx(EverfurRecordsTimeline,{petRef:petRef,...seams,style:style});case"record":/* @__PURE__ */
890
1004
  return jsx(EverfurRecordDetail,{petRef:petRef,...seams,...records,...pending,style:style});case"document":/* @__PURE__ */