@everfur/sdk 0.14.0 → 0.15.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 (166) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/dist/{Chat.d-aycmX1CA.d.cts → Chat.d-CtfANk3A.d.cts} +3 -3
  3. package/dist/{Chat.d-puminpyi.d.ts → Chat.d-a7Ksz7NZ.d.ts} +3 -3
  4. package/dist/{DepthViews.d-BdvFZgPs.d.cts → DepthViews.d-BqMnWSMu.d.cts} +1 -1
  5. package/dist/{DepthViews.d-Dy0Zl-s-.d.ts → DepthViews.d-CuBElgEc.d.ts} +1 -1
  6. package/dist/{DepthViews.d-DIvxzLDf.d.ts → DepthViews.d-DbJejGm3.d.ts} +1 -1
  7. package/dist/{DepthViews.d-wLNkzk9f.d.cts → DepthViews.d-dXWL6ToG.d.cts} +1 -1
  8. package/dist/{RecordsPage.d-9Ank15PT.d.ts → RecordsPage.d-DKrZ9rHX.d.ts} +1 -1
  9. package/dist/{RecordsPage.d-DMKU0IKc.d.cts → RecordsPage.d-DRPdUAo4.d.cts} +1 -1
  10. package/dist/animations/index.cjs +1 -1
  11. package/dist/animations/index.d.cts +5 -3
  12. package/dist/animations/index.d.ts +5 -3
  13. package/dist/animations/index.js +1 -1
  14. package/dist/{attachments.d-rp3xs-Q3.d.ts → attachments.d-BGn2_knv.d.ts} +5 -5
  15. package/dist/{attachments.d--sIsfk6e.d.ts → attachments.d-CoQhXrP9.d.ts} +2 -2
  16. package/dist/{attachments.d-DNUCiyy5.d.cts → attachments.d-CpaOfi2g.d.cts} +5 -5
  17. package/dist/{attachments.d-ZEpTUeWN.d.cts → attachments.d-CqHMGoER.d.cts} +2 -2
  18. package/dist/{bookingCopy.d-DUrmVcLs.d.cts → bookingCopy.d-Bnq2zk0F.d.cts} +2 -2
  19. package/dist/{bookingCopy.d-D0uIIFAJ.d.ts → bookingCopy.d-BwCOCZUj.d.ts} +2 -2
  20. package/dist/{branding.d-CTXTUg_8.d.cts → branding.d-Bbc6p1XY.d.cts} +1 -1
  21. package/dist/{branding.d-DxJSoFce.d.ts → branding.d-y6c0UwhE.d.ts} +1 -1
  22. package/dist/{casesRepository.d-DCnix2pT.d.cts → casesRepository.d-CsUJ2Oyb.d.cts} +1 -1
  23. package/dist/{casesRepository.d-DbirgbyH.d.ts → casesRepository.d-DG83Ggbq.d.ts} +1 -1
  24. package/dist/chat/index.cjs +3 -3
  25. package/dist/chat/index.d.cts +9 -9
  26. package/dist/chat/index.d.ts +9 -9
  27. package/dist/chat/index.js +3 -3
  28. package/dist/client/index.cjs +3 -3
  29. package/dist/client/index.d.cts +10 -10
  30. package/dist/client/index.d.ts +10 -10
  31. package/dist/client/index.js +3 -3
  32. package/dist/{clinicBatch.d-Ccmrngcu.d.cts → clinicBatch.d-BLpbpS51.d.cts} +2 -2
  33. package/dist/{clinicBatch.d-D9Ci7IpP.d.ts → clinicBatch.d-Byjx4y_W.d.ts} +2 -2
  34. package/dist/{config.d-DJ4mvf_w.d.cts → config.d-C0WgjutL.d.cts} +1 -1
  35. package/dist/{config.d-MX7IKP2f.d.ts → config.d-zd2eTb2L.d.ts} +1 -1
  36. package/dist/consent/index.d.cts +5 -5
  37. package/dist/consent/index.d.ts +5 -5
  38. package/dist/{context.d-BdnBe8Oe.d.ts → context.d-BBjmV0rz.d.ts} +7 -7
  39. package/dist/{context.d-C6MJsMpN.d.cts → context.d-Du_UPxa1.d.cts} +7 -7
  40. package/dist/{copy.d-BIfQOoDB.d.ts → copy.d-D_VVj01o.d.ts} +2 -2
  41. package/dist/{copy.d-C_u7shha.d.cts → copy.d-Da_PP2K3.d.cts} +2 -2
  42. package/dist/core/index.cjs +2 -2
  43. package/dist/core/index.d.cts +16 -16
  44. package/dist/core/index.d.ts +16 -16
  45. package/dist/core/index.js +2 -2
  46. package/dist/{depth.d-COFxYWLU.d.ts → depth.d-BEedifOR.d.ts} +2 -2
  47. package/dist/{depth.d-D2e5WZuE.d.cts → depth.d-RTV61QNf.d.cts} +2 -2
  48. package/dist/{entitlementRepository.d-DLuxnGi5.d.ts → entitlementRepository.d-BwThmh3V.d.ts} +3 -3
  49. package/dist/{entitlementRepository.d-BP15dFbe.d.cts → entitlementRepository.d-C-stdRyA.d.cts} +3 -3
  50. package/dist/{focus.d-C0Tr0oVJ.d.ts → focus.d-CtotIyEt.d.ts} +20 -4
  51. package/dist/{focus.d-jQWp0hdK.d.cts → focus.d-Dsm39DjO.d.cts} +20 -4
  52. package/dist/health-plan/index.cjs +46 -41
  53. package/dist/health-plan/index.d.cts +8 -8
  54. package/dist/health-plan/index.d.ts +8 -8
  55. package/dist/health-plan/index.js +47 -42
  56. package/dist/{idempotency.d-DXb1BN2A.d.ts → idempotency.d-Bfm7oIxS.d.cts} +8 -1
  57. package/dist/{idempotency.d-HF6fyRt2.d.cts → idempotency.d-Cv-B7SfC.d.ts} +8 -1
  58. package/dist/{identity.d-BePPZ7Uv.d.ts → identity.d-BksOEa6m.d.ts} +1 -1
  59. package/dist/{identity.d-CJfnWOdH.d.cts → identity.d-CioQhZrq.d.cts} +1 -1
  60. package/dist/index.cjs +6 -6
  61. package/dist/index.d.cts +16 -16
  62. package/dist/index.d.ts +16 -16
  63. package/dist/index.js +6 -6
  64. package/dist/{introEvents.d-BkGDT_kG.d.cts → introEvents.d-fAZitxMA.d.cts} +1 -1
  65. package/dist/{introEvents.d-DHlMvmC7.d.ts → introEvents.d-tOi4o3F4.d.ts} +1 -1
  66. package/dist/notifications/index.d.cts +4 -4
  67. package/dist/notifications/index.d.ts +4 -4
  68. package/dist/{optInView.d-s-w4aGN3.d.ts → optInView.d-B8zTORO2.d.ts} +2 -2
  69. package/dist/{optInView.d-0iI5JoAf.d.cts → optInView.d-BkNSv4Gk.d.cts} +2 -2
  70. package/dist/{parse.d-COt1qVA6.d.ts → parse.d-B5JHS6Pr.d.ts} +1 -1
  71. package/dist/{parse.d-EmsgOUMQ.d.cts → parse.d-BgjO82mY.d.cts} +1 -1
  72. package/dist/{pets.d-nNAVnw7f.d.cts → pets.d-B_LoizOv.d.cts} +1 -1
  73. package/dist/{pets.d-BFT_b53y.d.ts → pets.d-OWxskXCP.d.ts} +1 -1
  74. package/dist/{petsRepository.d-B2TpRE7r.d.cts → petsRepository.d-B5DWzU7C.d.cts} +1 -1
  75. package/dist/{petsRepository.d-RGwSZcYl.d.ts → petsRepository.d-Ba3xhJcj.d.ts} +1 -1
  76. package/dist/{planSignals.d-BDbp2e-k.d.cts → planSignals.d-Cl6n5QpS.d.cts} +2 -2
  77. package/dist/{planSignals.d-DSnxKoWe.d.ts → planSignals.d-DtxZoWGM.d.ts} +2 -2
  78. package/dist/{ports.d-D2n4HRUy.d.ts → ports.d-BDtwHxmW.d.ts} +4 -4
  79. package/dist/{ports.d-DBA_gsq5.d.cts → ports.d-gZNTn8Qf.d.cts} +4 -4
  80. package/dist/records/depth/index.d.cts +9 -9
  81. package/dist/records/depth/index.d.ts +9 -9
  82. package/dist/records/index.cjs +62 -52
  83. package/dist/records/index.d.cts +21 -15
  84. package/dist/records/index.d.ts +21 -15
  85. package/dist/records/index.js +63 -53
  86. package/dist/{requestFunnel.d-RZex94XX.d.cts → requestFunnel.d-CR4akGCY.d.cts} +2 -2
  87. package/dist/{requestFunnel.d-D9edIEjZ.d.ts → requestFunnel.d-DFf9C__p.d.ts} +2 -2
  88. package/dist/{runtimeTypes.d-BYq38b17.d.ts → runtimeTypes.d-BqBOrZxa.d.ts} +5 -5
  89. package/dist/{runtimeTypes.d-LkwZaF7z.d.cts → runtimeTypes.d-CHdH-y2c.d.cts} +5 -5
  90. package/dist/{screenProps.d-CQ0qZJkr.d.cts → screenProps.d-B1dIANI0.d.cts} +1 -1
  91. package/dist/{screenProps.d-BVzRzowC.d.ts → screenProps.d-CVqFJw-J.d.ts} +1 -1
  92. package/dist/server/events/index.cjs +1 -1
  93. package/dist/server/events/index.d.cts +2 -2
  94. package/dist/server/events/index.d.ts +2 -2
  95. package/dist/server/events/index.js +1 -1
  96. package/dist/server/index.cjs +1 -1
  97. package/dist/server/index.d.cts +3 -3
  98. package/dist/server/index.d.ts +3 -3
  99. package/dist/server/index.js +1 -1
  100. package/dist/shop/index.cjs +5 -4
  101. package/dist/shop/index.d.cts +15 -3
  102. package/dist/shop/index.d.ts +15 -3
  103. package/dist/shop/index.js +5 -4
  104. package/dist/tabs/index.cjs +3 -3
  105. package/dist/tabs/index.d.cts +9 -8
  106. package/dist/tabs/index.d.ts +9 -8
  107. package/dist/tabs/index.js +3 -3
  108. package/dist/televet/booking/index.d.cts +6 -6
  109. package/dist/televet/booking/index.d.ts +6 -6
  110. package/dist/testing/index.cjs +1 -1
  111. package/dist/testing/index.d.cts +1 -1
  112. package/dist/testing/index.d.ts +1 -1
  113. package/dist/testing/index.js +1 -1
  114. package/dist/testing/rn/index.d.cts +9 -9
  115. package/dist/testing/rn/index.d.ts +9 -9
  116. package/dist/testing/web/index.d.cts +9 -9
  117. package/dist/testing/web/index.d.ts +9 -9
  118. package/dist/texting/index.d.cts +5 -5
  119. package/dist/texting/index.d.ts +5 -5
  120. package/dist/{threadOptions.d-9r4Csa7k.d.cts → threadOptions.d-CnSfFVMr.d.cts} +2 -2
  121. package/dist/{threadOptions.d-B6GA09aM.d.ts → threadOptions.d-DZ0AoQGk.d.ts} +2 -2
  122. package/dist/{timelineRows.d-BvM2A7_G.d.cts → timelineRows.d-CF1KvLcQ.d.cts} +1 -1
  123. package/dist/{timelineRows.d-Bes8ip2v.d.ts → timelineRows.d-CtL0y7y1.d.ts} +1 -1
  124. package/dist/{tokens.d-DarDaV39.d.cts → tokens.d-BUVqme2D.d.cts} +1 -1
  125. package/dist/{tokens.d-DarDaV39.d.ts → tokens.d-BUVqme2D.d.ts} +1 -1
  126. package/dist/{typeStyle.d-Co5KF0up.d.ts → typeStyle.d-B3Kdtjie.d.ts} +2 -2
  127. package/dist/{typeStyle.d-xIZj02Ru.d.cts → typeStyle.d-DmlwyJq-.d.cts} +2 -2
  128. package/dist/{usePresentation.d-BGz32Vlm.d.ts → usePresentation.d-BsR08Wxt.d.ts} +1 -1
  129. package/dist/{usePresentation.d-DYTF_ZGf.d.cts → usePresentation.d-CZS0qlLI.d.cts} +1 -1
  130. package/dist/{useRecordsDepth.d-BQRL0Hez.d.ts → useRecordsDepth.d-DTAxFf5s.d.ts} +1 -1
  131. package/dist/{useRecordsDepth.d--LLA_4ga.d.cts → useRecordsDepth.d-k-zYIHTe.d.cts} +1 -1
  132. package/dist/{view.d-DqbCADFa.d.ts → view.d-BE7VOlsB.d.ts} +3 -3
  133. package/dist/{view.d-0yBjLTV3.d.cts → view.d-CAWQjcY_.d.cts} +3 -3
  134. package/dist/web/consent/index.d.cts +5 -5
  135. package/dist/web/consent/index.d.ts +5 -5
  136. package/dist/web/health-plan/index.cjs +35 -30
  137. package/dist/web/health-plan/index.d.cts +10 -10
  138. package/dist/web/health-plan/index.d.ts +10 -10
  139. package/dist/web/health-plan/index.js +35 -30
  140. package/dist/web/index.cjs +9 -9
  141. package/dist/web/index.d.cts +30 -29
  142. package/dist/web/index.d.ts +30 -29
  143. package/dist/web/index.js +9 -9
  144. package/dist/web/intro/index.d.cts +6 -6
  145. package/dist/web/intro/index.d.ts +6 -6
  146. package/dist/web/notifications/index.d.cts +3 -3
  147. package/dist/web/notifications/index.d.ts +3 -3
  148. package/dist/web/records/depth/index.d.cts +9 -9
  149. package/dist/web/records/depth/index.d.ts +9 -9
  150. package/dist/web/records/index.cjs +2 -2
  151. package/dist/web/records/index.d.cts +11 -11
  152. package/dist/web/records/index.d.ts +11 -11
  153. package/dist/web/records/index.js +2 -2
  154. package/dist/web/records-sheet/index.cjs +87 -62
  155. package/dist/web/records-sheet/index.d.cts +9 -2
  156. package/dist/web/records-sheet/index.d.ts +9 -2
  157. package/dist/web/records-sheet/index.js +87 -62
  158. package/dist/web/shop/index.cjs +7 -6
  159. package/dist/web/shop/index.d.cts +3 -3
  160. package/dist/web/shop/index.d.ts +3 -3
  161. package/dist/web/shop/index.js +7 -6
  162. package/dist/web/televet/booking/index.d.cts +7 -7
  163. package/dist/web/televet/booking/index.d.ts +7 -7
  164. package/dist/web/texting/index.d.cts +5 -5
  165. package/dist/web/texting/index.d.ts +5 -5
  166. package/package.json +2 -1
@@ -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,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([
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,Animated,AccessibilityInfo,Share,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}),
@@ -102,7 +102,7 @@ return Object.freeze({docId:d.doc_id,title:d.title??null,documentClass:d.documen
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
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(
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}var SDK_VERSION="0.15.0";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
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
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__ */
@@ -725,13 +725,13 @@ return jsxs(ScrollView,{contentContainerStyle:local.content,keyboardShouldPersis
725
725
  /* @__PURE__ */jsx(Text,{style:local.confirmTitle,accessibilityRole:"header",children:RECORDS_RECOVERY_COPY.cancelQuestion}),
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
- /* @__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?.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
- 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__ */
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","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),TONES=/* @__PURE__ */new Set(["y","c","g","r"]),TRACK_STATES=/* @__PURE__ */new Set(["done","now","next"]),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?.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),tone=s?.tone;return t===null?null:clean({title:t,body:str4(s?.body),source:str4(s?.source,200),tone:typeof tone=="string"&&TONES.has(tone)?tone:null,icon:iconOf(s?.icon),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,hidden:o.none===true&&o.hidden===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),productId=idOf(v?.productId),added=str4(v?.added,80)??(productId!==null?action:null);return key===null||t===null||action===null||added===null?null:clean({key:key,productId:productId,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 waitOf(value){let o=obj(value),kicker=str4(o?.kicker,120),title=str4(o?.title,120);return o===null||kicker===null||title===null?null:clean({kicker:kicker,title:title,icon:iconOf(o.icon),track:listOf(o.track,r=>{let v=obj(r),t=str4(v?.title,120),state=v?.state;return t===null?null:clean({title:t,detail:str4(v?.detail,120),state:typeof state=="string"&&TRACK_STATES.has(state)?state:null,tag:str4(v?.tag,40)})},6),heading:str4(o.heading,200),rows:listOf(o.rows,r=>{let v=obj(r),icon=iconOf(v?.icon),label=str4(v?.label,120);if(icon===null||label===null)return null;if(v?.fromVet===true)return clean({icon:icon,label:label,text:"",fromVet:true});let text4=str4(v?.text,300);return text4===null?null:clean({icon:icon,label:label,text:text4})},6),note:str4(o.note,300),action:str4(o.action,80)})}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),subtitleNoRecords:str4(o.subtitleNoRecords,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),wait:waitOf(o.wait),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
+ 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=HEALTH_PLAN_STALE_MS,SHARED_READS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function sharedReads(){let host=globalThis,stored=host[SHARED_READS_SYMBOL];if(stored instanceof WeakMap)return stored;let made=/* @__PURE__ */new WeakMap;return host[SHARED_READS_SYMBOL]=made,made}function readShared(reader,runtime,userRef,petRef,fresh){let all=sharedReads(),reads=all.get(runtime);reads===void 0&&(reads=/* @__PURE__ */new Map,all.set(runtime,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,runtime,userRef,pet,fresh),[hostRepository,repository,own,runtime,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
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__ */
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 sheetAge(ageYears){if(typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<=0)return null;let totalMonths=Math.floor(ageYears*12+1e-9),years=Math.floor(totalMonths/12),months=totalMonths%12;return years<=0?`${months}M`:months>0?`${years}Y ${months}M`:`${years}Y`}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,sheetAge(inputs.petAgeYears),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}}function mapTier(wire){let tier={url:wire.url,kind:wire.kind,expiresAt:wire.expires_at};return typeof wire.loop_duration_ms=="number"&&(tier.loopDurationMs=wire.loop_duration_ms),typeof wire.cache_key=="string"&&wire.cache_key.length>0&&(tier.cacheKey=wire.cache_key),/* @__PURE__ */Object.freeze(tier)}function mapPetStateResponse(wire){let tiers={};wire.tiers.animation&&(tiers.animation=mapTier(wire.tiers.animation)),wire.tiers.image&&(tiers.image=mapTier(wire.tiers.image));let overlays={};wire.overlays.weather_alert&&(overlays.weatherAlert=mapTier(wire.overlays.weather_alert));let response={category:wire.category,tiers:/* @__PURE__ */Object.freeze(tiers),overlays:/* @__PURE__ */Object.freeze(overlays),idle:"bundled",ttlSeconds:wire.ttl_seconds,degraded:wire.degraded};return typeof wire.cache_epoch=="number"&&(response.cacheEpoch=wire.cache_epoch),/* @__PURE__ */Object.freeze(response)}var mediaKindWireSchema=/* @__PURE__ */z.enum(["webp","video"]),categoryWireSchema=/* @__PURE__ */z.enum(["health","attention","moment","activity","mood","idle"]),petStateTierWireSchema=/* @__PURE__ */z.object({url:/* @__PURE__ */z.string(),kind:/* @__PURE__ */mediaKindWireSchema.default("webp"),loop_duration_ms:/* @__PURE__ */z.number().nullish(),expires_at:/* @__PURE__ */z.string(),cache_key:/* @__PURE__ */z.string().nullish()}),petStateResponseWireSchema=/* @__PURE__ */z.object({category:categoryWireSchema,tiers:/* @__PURE__ */z.object({animation:/* @__PURE__ */petStateTierWireSchema.optional(),image:/* @__PURE__ */petStateTierWireSchema.optional()}).default({}),overlays:/* @__PURE__ */z.object({weather_alert:/* @__PURE__ */petStateTierWireSchema.optional()}).default({}),idle:/* @__PURE__ */z.literal("bundled").default("bundled"),ttl_seconds:/* @__PURE__ */z.number(),degraded:/* @__PURE__ */z.boolean().default(false),cache_epoch:/* @__PURE__ */z.number().default(0)});function parsePetStateWire(raw){let parsed=petStateResponseWireSchema.safeParse(raw);return parsed.success?parsed.data:null}function createPetStateRepository(auth){return createPetStateRepositoryOver(createRequestFunnel({auth:auth}))}function createPetStateRepositoryOver(funnel){return{async getState(petRef,opts){if(hasLoneSurrogate(petRef))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let path=`/widget/v1/pets/${encodeURIComponent(petRef)}/state`,res=await funnel.send("animations.getState",opts?.signal?{method:"GET",path:path,signal:opts.signal}:{method:"GET",path:path},opts?.maxAttempts!==void 0?{maxAttempts:opts.maxAttempts}:void 0);if(res.ok){let wire=parsePetStateWire(res.value);return wire===null?err(makeEverfurError("internalError",{retryable:true})):ok(mapPetStateResponse(wire))}return res.error.httpStatus===404?ok(null):err(res.error)}}}var LOADING=/* @__PURE__ */Object.freeze({status:"loading"}),NONE=/* @__PURE__ */Object.freeze({status:"none"}),RETRY_MS=3e4,RECORDS_PET_ART_RETRIES_MS=/* @__PURE__ */Object.freeze([2e3,6e3]),NO_FAILURES=/* @__PURE__ */Object.freeze({animation:false,image:false});function recordsPetArtOf(read,failed,reducedMotion){if(read.kind==="pending")return LOADING;if(read.kind==="failed"||read.value===null)return NONE;let{animation:animation,image:image}=read.value.tiers;return animation!==void 0&&animation.kind==="webp"&&!reducedMotion&&!failed.animation?{status:"art",url:animation.url,key:animation.cacheKey??animation.url,animated:true}:image!==void 0&&image.kind==="webp"&&!failed.image?{status:"art",url:image.url,key:image.cacheKey??image.url,animated:false}:NONE}function useRecordsPetArt(petRef,opts){let context=useContext(EverfurContext),runtime=context?.runtime??null,userRef=context?.userRef??null,scope=runtime!==null&&userRef!==null&&petRef!==null?`${userRef}|${petRef}`:null,[read,setRead]=useState({scope:scope,read:{kind:"pending"}}),[failed,setFailed]=useState({scope:scope,failed:NO_FAILURES}),[due,setDue]=useState({scope:scope,at:0}),current=read.scope===scope?read.read:{kind:"pending"},done=current.kind==="answer"&&current.value===null,attempts=useRef({scope:scope,n:0});useEffect(()=>{if(scope===null||runtime===null||userRef===null||petRef===null||!opts.isFocused||done)return;let at=due.scope===scope?due.at:0,live=true,controller=typeof AbortController=="function"?new AbortController:null,run=()=>{createPetStateRepository(runtime.registry.services.authFor(userRef)).getState(petRef,controller?{signal:controller.signal,maxAttempts:1}:{maxAttempts:1}).then(result=>{if(!live)return;if(result.ok){attempts.current={scope:scope,n:0};let value=result.value;setRead(prev=>value!==null&&value.degraded&&prev.scope===scope&&prev.read.kind==="answer"&&prev.read.value!==null?prev:{scope:scope,read:{kind:"answer",value:value}}),value!==null&&(value.degraded||setFailed({scope:scope,failed:NO_FAILURES}),setDue({scope:scope,at:Date.now()+Math.max(30,value.ttlSeconds)*1e3}));return}if(result.error.httpStatus===403){setRead({scope:scope,read:{kind:"answer",value:null}});return}let n2=attempts.current.scope===scope?attempts.current.n:0,quick=RECORDS_PET_ART_RETRIES_MS[n2];attempts.current={scope:scope,n:n2+1},setRead(prev=>prev.scope===scope&&prev.read.kind==="answer"?prev:quick!==void 0?{scope:scope,read:{kind:"pending"}}:{scope:scope,read:{kind:"failed"}}),setDue({scope:scope,at:Date.now()+(quick??RETRY_MS)})})},wait=Math.max(0,at-Date.now()),timer=wait===0?null:setTimeout(run,wait);return timer===null&&run(),()=>{live=false,timer!==null&&clearTimeout(timer),controller?.abort()}},[scope,runtime,userRef,petRef,opts.isFocused,done,due]);let failedNow=failed.scope===scope?failed.failed:NO_FAILURES,art=useMemo(()=>scope===null?NONE:recordsPetArtOf(current,failedNow,opts.reducedMotion),[scope,current,failedNow,opts.reducedMotion]),onError=useCallback(()=>{art.status==="art"&&setFailed(prev=>{let base2=prev.scope===scope?prev.failed:NO_FAILURES;return{scope:scope,failed:art.animated?{...base2,animation:true}:{...base2,image:true}}})},[art,scope]);return useMemo(()=>({art:art,onError:onError}),[art,onError])}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
735
  return jsxs(View,{style:frame(size),...HIDDEN3,children:[
736
736
  /* @__PURE__ */jsx(View,{style:bar2(12.35*u,3.09*u,12.35*u,15.44*u,w,color)}),
737
737
  /* @__PURE__ */jsx(View,{style:bar2(7.2*u,10.29*u,12.35*u,15.44*u,w,color)}),
@@ -801,61 +801,70 @@ return jsx(View,{testID:testID,style:[{alignSelf:"flex-start",maxWidth:"100%",mi
801
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
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
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__ */
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(z12=>({zone:z12.zone,lines:z12.lines,baselines:baselines(z12.lines.length,z12.top,z12.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()}`}var VERSION=typeof __EVERFUR_SDK_VERSION__=="string"&&__EVERFUR_SDK_VERSION__.length>0?__EVERFUR_SDK_VERSION__:SDK_VERSION,ORIGIN=typeof __EVERFUR_CDN_ORIGIN__=="string"&&__EVERFUR_CDN_ORIGIN__.length>0?__EVERFUR_CDN_ORIGIN__:"https://sdk.everfur.com",RECORDS_GRASS_URL=`${ORIGIN}/${VERSION}/assets/grass.webp`;var RECORDS_GRASS_SOURCE=/* @__PURE__ */Object.freeze({uri:RECORDS_GRASS_URL}),easeOut=null,EASE_OUT=t=>(easeOut??=Easing.bezier(.23,1,.32,1))(t);function useHeroSettle(grassHeight,reduced){let start=reduced?1:0,petFade=useRef(new Animated.Value(start)).current,petRise=useRef(new Animated.Value(start)).current,grassGrow=useRef(new Animated.Value(start)).current,grassFade=useRef(new Animated.Value(start)).current,played=useRef(reduced);useEffect(()=>{if(reduced){for(let v of[petFade,petRise,grassGrow,grassFade])v.setValue(1);return}if(played.current)return;played.current=true;let timing=(v,duration,delay=0)=>Animated.timing(v,{toValue:1,duration:duration,delay:delay,easing:EASE_OUT,useNativeDriver:true}),run=Animated.parallel([timing(petFade,400,60),timing(petRise,700,60),timing(grassGrow,820),timing(grassFade,360)]);return run.start(),()=>run.stop()},[reduced,petFade,petRise,grassGrow,grassFade]);let refs=useRef(null);if(refs.current===null||refs.current.pet.opacity!==petFade){let scale=grassGrow.interpolate({inputRange:[0,1],outputRange:[.35,1]}),drop=grassGrow.interpolate({inputRange:[0,1],outputRange:[grassHeight*.65/2,0]});refs.current={pet:{opacity:petFade,transform:[{translateY:petRise.interpolate({inputRange:[0,1],outputRange:[16,0]})}]},grass:{opacity:grassFade,transform:[{translateY:drop},{scaleY:scale}]}}}return refs.current}function RiseIn({index:index,reduced:reduced,children:children}){let p=useRef(new Animated.Value(reduced?1:0)).current;return useEffect(()=>{if(reduced){p.setValue(1);return}let run=Animated.timing(p,{toValue:1,duration:400,delay:index*60,easing:EASE_OUT,useNativeDriver:true});return run.start(),()=>run.stop()},[reduced,index,p]),/* @__PURE__ */jsx(Animated.View,{style:{opacity:p,transform:[{translateY:p.interpolate({inputRange:[0,1],outputRange:[8,0]})}]},children:children})}function HubPetArt({art:art,onError:onError,reduced:reduced}){return art.status!=="art"?null:/* @__PURE__ */jsx(PetImage,{url:art.url,onError:onError,reduced:reduced},art.key)}function PetImage({url:url,onError:onError,reduced:reduced}){let opacity=useRef(new Animated.Value(0)).current,onLoad=()=>{if(reduced){opacity.setValue(1);return}Animated.timing(opacity,{toValue:1,duration:200,easing:EASE_OUT,useNativeDriver:true}).start()};/* @__PURE__ */
805
+ return jsx(View,{style:{width:"100%",height:"100%"},testID:"everfur-records-sheet-pet-art",children:/* @__PURE__ */jsx(Animated.Image,{source:{uri:url},onLoad:onLoad,onError:onError,resizeMode:"contain",style:{width:"100%",height:"100%",opacity:opacity}})})}var HUB_MOTION=/* @__PURE__ */Object.freeze({reveal:480,revealFade:320,revealStagger:60,revealMaxSteps:8,revealRiseBlock:14,rollDigits:900,rollDigitStagger:55,chartDraw:850,slideTravel:48,slideMs:320}),easeOut2=null,HUB_EASE_OUT=t=>(easeOut2??=Easing.bezier(.23,1,.32,1))(t);function hubRevealDelay(index){return Math.min(Math.max(0,index),HUB_MOTION.revealMaxSteps-1)*HUB_MOTION.revealStagger}function HubReveal({index:index,reduced:reduced,style:style,testID:testID,children:children}){let rise=useRef(new Animated.Value(reduced?1:0)).current,fade=useRef(new Animated.Value(reduced?1:0)).current,played=useRef(reduced);useEffect(()=>{if(reduced){rise.setValue(1),fade.setValue(1);return}if(played.current)return;let delay=hubRevealDelay(index),run=Animated.parallel([Animated.timing(rise,{toValue:1,duration:HUB_MOTION.reveal,delay:delay,easing:HUB_EASE_OUT,useNativeDriver:true}),Animated.timing(fade,{toValue:1,duration:HUB_MOTION.revealFade,delay:delay,easing:HUB_EASE_OUT,useNativeDriver:true})]);return run.start(({finished:finished})=>{finished&&(played.current=true)}),()=>run.stop()},[reduced,index,rise,fade]);let moving={opacity:fade,transform:[{translateY:rise.interpolate({inputRange:[0,1],outputRange:[HUB_MOTION.revealRiseBlock,0]})}]};/* @__PURE__ */
806
+ return jsx(Animated.View,{style:[style,moving],testID:testID,children:children})}function useHubDraw(ready,reduced){let p=useRef(new Animated.Value(reduced?1:0)).current,played=useRef(reduced);return useEffect(()=>{if(reduced){p.setValue(1);return}if(!ready||played.current)return;let run=Animated.timing(p,{toValue:1,duration:HUB_MOTION.chartDraw,easing:HUB_EASE_OUT,useNativeDriver:true});return run.start(({finished:finished})=>{finished&&(played.current=true)}),()=>run.stop()},[ready,reduced,p]),p}function hubSegmentSpans(points){let lengths=points.slice(1).map((b,i)=>Math.hypot(b.x-points[i].x,b.y-points[i].y)),total=lengths.reduce((a,b)=>a+b,0),at=0;return lengths.map(len=>{let from=total>0?at/total:0;return at+=len,[from,total>0?at/total:1]})}function hubSegmentDraw(p,span,length){let[from,to]=span,end=to>from?to:from+1e-4,scaleX=p.interpolate({inputRange:[from,end],outputRange:[1e-4,1],extrapolate:"clamp"});return{translateX:p.interpolate({inputRange:[from,end],outputRange:[-length/2,0],extrapolate:"clamp"}),scaleX:scaleX}}function hubDotAt(spans,i){return i<=0?0:spans[i-1]?.[1]??1}function hubDotShown(p,at){return p.interpolate({inputRange:[at-.0011,at-.001],outputRange:[0,1],extrapolate:"clamp"})}function useHubSlideStep(index,reduced){let prev=useRef(index),x=useRef(new Animated.Value(0)).current,o=useRef(new Animated.Value(1)).current;return useEffect(()=>{let dir=Math.sign(index-prev.current);if(prev.current=index,dir===0||reduced)return;x.setValue(dir*HUB_MOTION.slideTravel),o.setValue(0);let run=Animated.parallel([Animated.timing(x,{toValue:0,duration:HUB_MOTION.slideMs,easing:HUB_EASE_OUT,useNativeDriver:true}),Animated.timing(o,{toValue:1,duration:HUB_MOTION.slideMs,easing:HUB_EASE_OUT,useNativeDriver:true})]);return run.start(),()=>run.stop()},[index,reduced,x,o]),useRef({opacity:o,transform:[{translateX:x}]}).current}function hubRollPlan(text4){return Array.from(text4,char=>({char:char,digit:/\d/.test(char)?Number(char):null}))}function hubRollEase(x){let t=Math.min(1,Math.max(0,x));return 1-Math.pow(1-t,3)}function HubRollingDigits({text:text4,reduced:reduced,renderText:renderText,testID:testID}){let[rolling,setRolling]=useState(()=>!reduced&&/\d/.test(text4)),first=useRef(text4);return useEffect(()=>{first.current!==text4&&setRolling(false)},[text4]),useEffect(()=>{reduced&&setRolling(false)},[reduced]),rolling?/* @__PURE__ */jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:text4,children:[
807
+ /* @__PURE__ */jsx(View,{style:{opacity:0},importantForAccessibility:"no-hide-descendants",accessibilityElementsHidden:true,children:renderText(text4,testID!==void 0?{testID:testID}:{})}),
808
+ /* @__PURE__ */jsx(RollOverlay,{text:text4,renderText:renderText,onDone:()=>setRolling(false)})]}):renderText(text4,testID!==void 0?{testID:testID}:{})}function RollOverlay({text:text4,renderText:renderText,onDone:onDone}){let plan=hubRollPlan(text4),digits=plan.filter(c=>c.digit!==null).length,total=HUB_MOTION.rollDigits+Math.max(0,digits-1)*HUB_MOTION.rollDigitStagger,t=useRef(new Animated.Value(0)).current,done=useRef(onDone);done.current=onDone,useEffect(()=>{let run=Animated.timing(t,{toValue:total,duration:total,easing:Easing.linear,useNativeDriver:true});return run.start(({finished:finished})=>{finished&&done.current()}),()=>run.stop()},[t,total]);let order=-1;/* @__PURE__ */
809
+ return jsx(View,{style:{position:"absolute",left:0,top:0,right:0,bottom:0,flexDirection:"row",alignItems:"flex-end"},pointerEvents:"none",importantForAccessibility:"no-hide-descendants",accessibilityElementsHidden:true,children:plan.map((cell,i)=>cell.digit===null?/* @__PURE__ */jsx(View,{children:renderText(cell.char)},i):(order+=1,/* @__PURE__ */jsx(RollCell,{cell:cell,t:t,delay:order*HUB_MOTION.rollDigitStagger,renderText:renderText},i)))})}var DIGITS=[0,1,2,3,4,5,6,7,8,9],ROLL_STEPS=24;function RollCell({cell:cell,t:t,delay:delay,renderText:renderText}){let[lh,setLh]=useState(0),onLayout=e=>{let h=e.nativeEvent.layout.height;h>0&&h!==lh&&setLh(h)},to=cell.digit??0,inputRange=[],outputRange=[];for(let s=0;s<=ROLL_STEPS;s+=1){let x=s/ROLL_STEPS;inputRange.push(delay+x*HUB_MOTION.rollDigits),outputRange.push(-to*lh*hubRollEase(x))}let translateY=t.interpolate({inputRange:inputRange,outputRange:outputRange,extrapolate:"clamp"});/* @__PURE__ */
810
+ return jsxs(View,{style:{overflow:"hidden"},onLayout:onLayout,children:[
811
+ /* @__PURE__ */jsx(View,{style:{opacity:0},children:renderText(cell.char)}),lh>0?/* @__PURE__ */jsx(Animated.View,{style:{position:"absolute",left:0,right:0,top:0,transform:[{translateY:translateY}]},children:DIGITS.map(d=>/* @__PURE__ */jsx(View,{style:{height:lh},children:renderText(String(d))},d))}):null]})}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
812
  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
813
  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:[
814
+ /* @__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,art:art,handFontFamily:handFontFamily,say:say,vitals:vitals,vitalsName:vitalsName,renderStage:renderStage}){let{look:look,face:face2}=useHub(),reduced=useEverfurTheme().motion.reducedMotion,staged=stage!==void 0||renderStage===void 0,settle=useHeroSettle(GRASS_H,reduced),grass=stage?.grassSource??RECORDS_GRASS_SOURCE,[grassFailed,setGrassFailed]=useState(null),grassKey=sourceKey(grass),list=vitals.length>0?/* @__PURE__ */jsx(View,{style:staged?{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,rank)=>{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__ */
815
+ return jsx(RiseIn,{index:rank,reduced:reduced,children:/* @__PURE__ */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
816
  /* @__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__ */
817
+ /* @__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!==void 0?stage.handFontFamily??null:handFontFamily;/* @__PURE__ */
811
818
  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__ */
819
+ /* @__PURE__ */jsx(View,{style:[{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:APP_HUB.screen.padX},say?null:{minHeight:APP_HUB.peek.roundButton}],testID:"everfur-records-sheet-head",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,staged?/* @__PURE__ */jsxs(View,{style:{height:APP_HUB.hero.stageHeight,marginTop:APP_HUB.hero.stageTop,overflow:"hidden"},testID:"everfur-records-sheet-stage",children:[
820
+ /* @__PURE__ */jsx(Animated.View,{style:[{position:"absolute",left:0,right:0,bottom:0,height:GRASS_H,overflow:"hidden"},settle.grass],...HIDDEN5,children:grassFailed===grassKey?null:/* @__PURE__ */jsx(Image,{source:grass,onError:()=>setGrassFailed(grassKey),style:{position:"absolute",top:0,left:0,right:0,height:"100%"},resizeMode:"cover",testID:"everfur-records-sheet-grass"})}),
821
+ /* @__PURE__ */jsx(Animated.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"},settle.pet],...HIDDEN5,children:stage!==void 0?/* @__PURE__ */jsx(Image,{source:stage.petSource,style:{width:"100%",height:"100%"},resizeMode:"contain"}):/* @__PURE__ */jsx(HubPetArt,{art:art.art,onError:art.onError,reduced:reduced})}),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,
822
+ /* @__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,note:note}){let reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
823
+ return jsx(HubReveal,{index:1,reduced:reduced,children:/* @__PURE__ */jsxs(HubCard,{title:title,testID:"everfur-records-records-prompt",children:[
824
+ /* @__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&&canRequest&&note?/* @__PURE__ */jsx(View,{style:{marginTop:12},children:note}):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,reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
818
825
  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:[
826
+ return jsx(RiseIn,{index:index,reduced:reduced,children:/* @__PURE__ */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
827
  /* @__PURE__ */jsxs(View,{style:{flex:1,flexDirection:"row",alignItems:"center",gap:U.rowGap},accessible:true,accessibilityLabel:`${row.label}, ${row.when}`,children:[
821
828
  /* @__PURE__ */jsx(HubIcon,{name:row.icon,size:U.icon,color:overdue?look.alert:look.icoGrey}),
822
829
  /* @__PURE__ */jsxs(View,{style:{flex:1,minWidth:0},children:[
823
830
  /* @__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:[
831
+ /* @__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__ */
832
+ 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({index:index,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
833
  /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},children:[
827
834
  /* @__PURE__ */jsx(HubIcon,{name:icon,size:G.icon}),onOpen!==void 0?/* @__PURE__ */jsx(HubIcon,{name:"chevron",size:G.chevron,color:look.icoSage}):null]}),
828
835
  /* @__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__ */
836
+ /* @__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},reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
837
+ return jsx(HubReveal,{index:index,reduced:reduced,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
838
  return jsxs(View,{style:{marginTop:G.top},testID:"everfur-records-hub-records",children:[
832
839
  /* @__PURE__ */jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{marginBottom:G.titleBottom},children:HUB_COPY.recordsHistory}),
833
840
  /* @__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:[
841
+ /* @__PURE__ */jsx(Tile,{index:0,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
842
  /* @__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__ */
843
+ /* @__PURE__ */jsx(Tile,{index:1,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}),
844
+ /* @__PURE__ */jsx(Tile,{index:2,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}),
845
+ /* @__PURE__ */jsx(Tile,{index:3,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__ */
846
+ 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),reduced=useEverfurTheme().motion.reducedMotion,draw=useHubDraw(width>0,reduced),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,spans=hubSegmentSpans(c.dots);/* @__PURE__ */
840
847
  return jsxs(View,{onLayout:onLayout,style:{height:G.height},children:[
841
848
  /* @__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
849
  /* @__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
850
  /* @__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__ */
851
+ /* @__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,grow=hubSegmentDraw(draw,spans[i],len+w);/* @__PURE__ */
852
+ return jsx(Animated.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`},{translateX:grow.translateX},{scaleX:grow.scaleX}]}},`l-${i}`)}),c.dots.map((d,i)=>/* @__PURE__ */jsx(Animated.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,opacity:hubDotShown(draw,hubDotAt(spans,i))}},`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(z12=>z12.lines.map((line2,i)=>/* @__PURE__ */jsx(ChartText,{x:G.legendX,y:z12.baselines[i],anchor:"start",size:G.legendSize,style:[face2("monoBold"),{color:look.charcoal,letterSpacing:G.legendTracking}],children:line2},`k-${z12.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
853
  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:[
854
+ /* @__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,reduced=useEverfurTheme().motion.reducedMotion;if(weight===null)/* @__PURE__ */
855
+ return jsx(HubReveal,{index:3,reduced:reduced,children:/* @__PURE__ */jsx(HubCard,{title:HUB_COPY.weight,testID:"everfur-records-hub-weight",children:/* @__PURE__ */jsx(HubText,{variant:"bodySm",children:HUB_COPY.noWeights(name)})})});let num5={fontSize:W.numSize,lineHeight:W.numLineHeight,letterSpacing:W.numTracking};/* @__PURE__ */
856
+ return jsx(HubReveal,{index:3,reduced:reduced,children:/* @__PURE__ */jsxs(HubCard,{title:HUB_COPY.weight,testID:"everfur-records-hub-weight",children:[
848
857
  /* @__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:[
858
+ /* @__PURE__ */jsx(HubRollingDigits,{text:weight.primary,reduced:reduced,testID:"everfur-records-sheet-weight-latest",renderText:(text4,extra)=>/* @__PURE__ */jsx(HubText,{variant:"bodySmBold",style:[num5,extra?.style],...extra?.testID!==void 0?{testID:extra.testID}:{},children:text4})}),weight.secondary!==null?/* @__PURE__ */jsx(HubText,{variant:"bodySm",color:look.muted,children:weight.secondary}):null]})}),weight.points.length>=2?/* @__PURE__ */jsxs(View,{children:[
859
+ /* @__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,note:note}){let{look:look}=useHub(),A=APP_HUB.add,reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
860
+ return jsx(HubReveal,{index:4,reduced:reduced,children:/* @__PURE__ */jsx(HubCard,{style:{backgroundColor:look.tintPinkSoft},testID:"everfur-records-hub-add-records",children:/* @__PURE__ */jsxs(View,{style:{gap:A.gap},children:[
852
861
  /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:A.headGap},children:[
853
862
  /* @__PURE__ */jsx(HubIcon,{name:"clip",size:A.icon,color:look.alert}),
854
863
  /* @__PURE__ */jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{flex:1},children:HUB_COPY.addRecords(words2.name)})]}),
855
864
  /* @__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
865
  /* @__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__ */
866
+ /* @__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,canRequest?note:null,
867
+ /* @__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
868
  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
869
  /* @__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
870
  /* @__PURE__ */jsxs(View,{style:{flex:1,minWidth:0,paddingTop:3,gap:2},children:[
@@ -865,18 +874,18 @@ return jsxs(Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityL
865
874
  /* @__PURE__ */jsxs(View,{style:{flex:1,minWidth:0,gap:2},children:[
866
875
  /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",color:fg,style:{fontSize:17,lineHeight:22},children:title}),
867
876
  /* @__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:[
877
+ /* @__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),reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
878
+ return jsx(HubReveal,{index:1,reduced:reduced,children:/* @__PURE__ */jsxs(HubCard,{testID:"everfur-records-hub-on-the-way",children:[
870
879
  /* @__PURE__ */jsx(HubText,{variant:"screenTitle",accessibilityRole:"header",style:{fontSize:O.titleSize,lineHeight:O.titleLineHeight,letterSpacing:O.titleTracking},children:HUB_COPY.onTheWay(words2.Name)}),
871
880
  /* @__PURE__ */jsx(HubText,{variant:"body",style:{marginTop:8},children:HUB_COPY.clinicsTake}),
872
881
  /* @__PURE__ */jsxs(View,{style:{marginTop:16},accessibilityRole:"list",testID:"everfur-records-sheet-tracker",children:[
873
882
  /* @__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
883
  /* @__PURE__ */jsx(Step,{state:waiting,title:HUB_COPY.waitingFor(whose),when:waitingLine,testID:"everfur-records-sheet-step-waiting"}),
875
884
  /* @__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:[
885
+ /* @__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
886
  /* @__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:[
887
+ /* @__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(),reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
888
+ return jsx(HubReveal,{index:1,reduced:reduced,children:/* @__PURE__ */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
889
  /* @__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
890
  /* @__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
891
  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:[
@@ -884,7 +893,7 @@ return jsxs(View,{style:{flexDirection:"row",alignItems:"flex-start",gap:APP_HUB
884
893
  /* @__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
894
  /* @__PURE__ */jsxs(View,{style:{flex:1,paddingBottom:APP_HUB_TIMELINE.bodyBottom,gap:APP_HUB_TIMELINE.bodyGap},children:[
886
895
  /* @__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__ */
896
+ /* @__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
897
  return jsxs(Fragment,{children:[
889
898
  /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:S.markerTopGap},children:[
890
899
  /* @__PURE__ */jsxs(View,{style:{flex:1,minWidth:0},children:[
@@ -908,30 +917,30 @@ return jsxs(View,{style:{marginTop:8},testID:"everfur-records-sheet-sample-from"
908
917
  /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:8},children:[
909
918
  /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",children:from.who}),
910
919
  /* @__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__ */
920
+ /* @__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"},reduced=useEverfurTheme().motion.reducedMotion,slide=useHubSlideStep(index,reduced);/* @__PURE__ */
912
921
  return jsxs(View,{style:{marginTop:S.top},testID:"everfur-records-sample-peek",children:[
913
922
  /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:S.headGap},children:[
914
923
  /* @__PURE__ */jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",children:HUB_COPY.recordsHistory}),
915
924
  /* @__PURE__ */jsx(HubPill,{label:HUB_COPY.sample,tone:"plain"})]}),
916
925
  /* @__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:[
926
+ /* @__PURE__ */jsx(HubReveal,{index:0,reduced:reduced,style:{marginTop:S.labsTop},children:/* @__PURE__ */jsxs(HubCard,{testID:"everfur-records-sheet-sample-labs",children:[
918
927
  /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:6},children:[
919
928
  /* @__PURE__ */jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{flex:1},children:HUB_COPY.labs}),
920
929
  /* @__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
930
  /* @__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
931
  /* @__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:[
932
+ /* @__PURE__ */jsxs(Animated.View,{style:[{marginTop:S.slideTop,gap:S.slideGap},slide],accessibilityLabel:HUB_COPY.slideOf(group.chip,index+1,HUB_SAMPLE_GROUPS.length),testID:"everfur-records-sheet-sample-slide",children:[
924
933
  /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",style:{fontSize:17,lineHeight:22},children:group.chip}),
925
934
  /* @__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:[
935
+ /* @__PURE__ */jsx(FromPage,{from:group.from},group.key)]})]})}),
936
+ /* @__PURE__ */jsx(View,{style:{gap:S.moreGap,marginTop:S.moreTop},testID:"everfur-records-sheet-sample-more",children:HUB_SAMPLE_MORE.map((card,ci)=>{let rows=dog?card.rows:card.rows.filter(r=>!DOG_ONLY.test(r.title));return rows.length===0?null:/* @__PURE__ */jsx(HubReveal,{index:ci+1,reduced:reduced,children:/* @__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
937
  /* @__PURE__ */jsxs(View,{style:{flexDirection:"row",alignItems:"center",gap:S.moreHeadGap},children:[
929
938
  /* @__PURE__ */jsx(HubIcon,{name:icons[card.key],size:S.moreIcon}),
930
939
  /* @__PURE__ */jsx(HubText,{variant:"bodySmBold",accessibilityRole:"header",style:{fontSize:17,lineHeight:22},children:card.title})]}),
931
940
  /* @__PURE__ */jsx(HubText,{variant:"bodySm",children:card.lead}),
932
941
  /* @__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__ */
942
+ /* @__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(){let reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
943
+ return jsx(HubReveal,{index:5,reduced:reduced,children:/* @__PURE__ */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})})})}function sourceKey(source){return source!==null&&typeof source=="object"&&typeof source.uri=="string"?source.uri:source}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
944
  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
945
  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__ */
937
946
  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__ */
@@ -975,23 +984,24 @@ return jsxs(View,{style:s.chart,accessibilityElementsHidden:true,importantForAcc
975
984
  /* @__PURE__ */jsx(Text,{style:[s.range,{top:"82%"}],children:SHEET_COPY.below})]})]}):null,
976
985
  /* @__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))]})]}),
977
986
  /* @__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__ */
987
+ 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 rnOpenClinicRequest(requests,petRef){return rnOpenRequest(requests.filter(r=>!isOwnerUpload(r)),petRef)}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 handFamilyOf(options){return options?.stage!==void 0?options.stage.handFontFamily??null:options?.handFontFamily!==void 0?options.handFontFamily:Platform.OS==="android"||Platform.OS==="web"?"cursive":null}function EverfurRecordsSheet(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),kit=useSheetKitValue();/* @__PURE__ */
988
+ 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:handFamilyOf(rest.options),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),reducedMotion=useEverfurTheme().motion.reducedMotion,petArt=useRecordsPetArt(options.stage===void 0&&options.renderStage===void 0?petRef:null,{reducedMotion:reducedMotion,isFocused: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()},note=useRequestedNote(),requested=rnOpenClinicRequest(records.requests,petRef)?.clinicName?.trim()||null,requestOnce=requested!==null?note.show:go.request,requestedNote=requested!==null&&note.on?/* @__PURE__ */jsx(RequestedNote,{clinic:requested},note.shown):null;if(labOpen!==null)/* @__PURE__ */
980
989
  return jsxs(View,{style:[{flex:1,backgroundColor:look.ground},style],children:[
981
990
  /* @__PURE__ */jsx(ScreenHeader,{title:rnSheetHeading(name),onBack:()=>setLabOpen(null),testID:"everfur-records-lab-header"}),
982
991
  /* @__PURE__ */jsx(EverfurRecordsLabDetail,{petRef:petRef,markerId:labOpen,...name.length>0?{petName:name}:{},...onAsk?{onAsk:onAsk}:{}}),
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,
992
+ /* @__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,art:petArt,handFontFamily:handFamilyOf(options),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:requestOnce,onUpload:go.upload,note:requestedNote}):null,
984
993
  /* @__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}),
994
+ /* @__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:requestOnce,onUpload:go.upload,note:requestedNote}),
986
995
  /* @__PURE__ */jsx(HubSamplePeek,{name:words2.name,species:species}),foot,
987
996
  /* @__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
997
  /* @__PURE__ */jsxs(View,{style:column,children:[hero(false),topRisk!==null?/* @__PURE__ */jsx(TopRisk,{words:words2,text:topRisk,onOpenPlan:options.onOpenPlan}):null,failedLine,partialFailed?
989
998
  /* @__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
999
  /* @__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,
1000
+ /* @__PURE__ */jsx(HubWeightCard,{weight:weight,name:words2.name}),canAct?/* @__PURE__ */jsx(HubAddRecords,{words:words2,sources:hubOnFile(records.record),canRequest:canRequest,onRequest:requestOnce,onUpload:go.upload,note:requestedNote}):null,foot,
992
1001
  /* @__PURE__ */jsx(HubLegal,{})]})]})})}/* @__PURE__ */
993
1002
  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__ */
1003
+ /* @__PURE__ */jsx(View,{style:{flex:1},testID:`everfur-records-sheet-state-${state}`,children:body}),onHub?null:/* @__PURE__ */jsx(RecordsFootnote,{})]})}var NOTE_MS=2600;function useRequestedNote(){let[on,setOn]=useState(false),[shown,setShown]=useState(0),timer=useRef(null);useEffect(()=>()=>{timer.current!==null&&clearTimeout(timer.current)},[]);let show=useCallback(()=>{timer.current!==null&&clearTimeout(timer.current),setOn(true),setShown(n2=>n2+1),timer.current=setTimeout(()=>{timer.current=null,setOn(false)},NOTE_MS)},[]);return{on:on,shown:shown,show:show}}function RequestedNote({clinic:clinic}){let{look:look}=useHub();/* @__PURE__ */
1004
+ return jsx(View,{accessibilityLiveRegion:"polite",style:{paddingVertical:APP_HUB.upcoming.rowPadY,paddingHorizontal:APP_HUB.card.pad,borderRadius:APP_HUB.card.radius,backgroundColor:look.fill},testID:"everfur-records-sheet-requested-note",children:/* @__PURE__ */jsx(HubText,{variant:"bodySm",color:look.onFill,children:SHEET_COPY.requestedFrom(clinic)})})}function HubDisclaimer({text:text4}){let{type:type}=useHub();/* @__PURE__ */
995
1005
  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__ */
996
1006
  return jsxs(SheetCard,{style:s.topRisk,testID:"everfur-records-sheet-top-risk",children:[
997
1007
  /* @__PURE__ */jsxs(View,{style:s.topRiskKicker,children:[