@everfur/sdk 0.3.0 → 0.4.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 (165) hide show
  1. package/CHANGELOG.md +69 -4
  2. package/README.md +6 -1
  3. package/dist/{Chat-DwAC2vhB.d.ts → Chat-BZZ-Py5l.d.ts} +3 -3
  4. package/dist/{Chat-DPUD6dnc.d.cts → Chat-Dq4fffIO.d.cts} +3 -3
  5. package/dist/{DepthViews-DNEM96Se.d.ts → DepthViews-BG3E25MD.d.ts} +1 -1
  6. package/dist/{DepthViews-DP0R-DhB.d.cts → DepthViews-B_hIypI6.d.cts} +1 -1
  7. package/dist/{DepthViews-DbFhR4Du.d.cts → DepthViews-CL75jyRA.d.cts} +1 -1
  8. package/dist/{DepthViews-D_3hl4xk.d.ts → DepthViews-CkYri51q.d.ts} +1 -1
  9. package/dist/animations/index.cjs +1 -1
  10. package/dist/animations/index.d.cts +3 -3
  11. package/dist/animations/index.d.ts +3 -3
  12. package/dist/animations/index.js +1 -1
  13. package/dist/{attachments-CQgFrEQ7.d.cts → attachments-BorG422I.d.cts} +2 -2
  14. package/dist/{attachments-5NeobOCd.d.ts → attachments-BrUWQYNK.d.ts} +5 -4
  15. package/dist/{attachments-D8T5re7e.d.cts → attachments-D_SECjr1.d.cts} +5 -4
  16. package/dist/{attachments-Bw3iMQgu.d.ts → attachments-DpldrvIW.d.ts} +2 -2
  17. package/dist/bookingCopy-CqtDYvCR.d.ts +732 -0
  18. package/dist/bookingCopy-SREvkG19.d.cts +732 -0
  19. package/dist/{entitlementRepository-DSbzuyAW.d.ts → branding-CsRdeNwK.d.cts} +1 -133
  20. package/dist/{entitlementRepository-DKdXFgTo.d.cts → branding-CsRdeNwK.d.ts} +1 -133
  21. package/dist/callCopy-DoQKG3-L.d.cts +40 -0
  22. package/dist/callCopy-DoQKG3-L.d.ts +40 -0
  23. package/dist/casesRepository-DwtZVsbj.d.cts +51 -0
  24. package/dist/casesRepository-v6QczS9N.d.ts +51 -0
  25. package/dist/chat/index.cjs +1 -1
  26. package/dist/chat/index.d.cts +9 -8
  27. package/dist/chat/index.d.ts +9 -8
  28. package/dist/chat/index.js +1 -1
  29. package/dist/client/index.cjs +5 -5
  30. package/dist/client/index.d.cts +10 -8
  31. package/dist/client/index.d.ts +10 -8
  32. package/dist/client/index.js +5 -5
  33. package/dist/{config-CzTZGlfF.d.cts → config--Wu1Umhd.d.cts} +2 -2
  34. package/dist/{config-DW60uRb9.d.ts → config-C7eb_IMD.d.ts} +2 -2
  35. package/dist/consent/index.cjs +1 -1
  36. package/dist/consent/index.d.cts +5 -5
  37. package/dist/consent/index.d.ts +5 -5
  38. package/dist/consent/index.js +1 -1
  39. package/dist/{context-XvTzq1tE.d.cts → context-CL3lyuy1.d.cts} +6 -6
  40. package/dist/{context-DXhqHlPU.d.ts → context-CahAEha8.d.ts} +6 -6
  41. package/dist/{copy-Mjoo91aS.d.ts → copy-DdVFDL01.d.ts} +2 -2
  42. package/dist/{copy-bKDNigLb.d.cts → copy-UeUJVk8X.d.cts} +2 -2
  43. package/dist/core/index.cjs +7 -7
  44. package/dist/core/index.d.cts +118 -29
  45. package/dist/core/index.d.ts +118 -29
  46. package/dist/core/index.js +7 -7
  47. package/dist/{depth-CErXCU8J.d.cts → depth-D5HwcvKC.d.cts} +34 -3
  48. package/dist/{depth-DjDcJ6kH.d.ts → depth-DvPwPuT_.d.ts} +34 -3
  49. package/dist/entitlementRepository-B7egEdW6.d.ts +43 -0
  50. package/dist/entitlementRepository-BpJ7tiwl.d.cts +43 -0
  51. package/dist/{identity-DI4eVx9S.d.cts → identity-C2-08BZW.d.cts} +2 -2
  52. package/dist/{identity-BMx2SUOM.d.ts → identity-CEi9GRFZ.d.ts} +2 -2
  53. package/dist/index.cjs +6 -6
  54. package/dist/index.d.cts +17 -16
  55. package/dist/index.d.ts +17 -16
  56. package/dist/index.js +6 -6
  57. package/dist/notifications/index.cjs +2 -2
  58. package/dist/notifications/index.d.cts +2 -2
  59. package/dist/notifications/index.d.ts +2 -2
  60. package/dist/notifications/index.js +2 -2
  61. package/dist/optionalModule-DbJmsq5f.d.cts +21 -0
  62. package/dist/optionalModule-DbJmsq5f.d.ts +21 -0
  63. package/dist/{pets-CtQdRpWo.d.ts → pets-DJv2sj2H.d.ts} +1 -1
  64. package/dist/{pets-aB8q0JyX.d.cts → pets-JVCXgRgR.d.cts} +1 -1
  65. package/dist/{casesRepository-DHwtGRYY.d.cts → petsRepository-B_gKbAzJ.d.cts} +2 -48
  66. package/dist/{casesRepository-ClLv6qMl.d.ts → petsRepository-Bk6GDwLs.d.ts} +2 -48
  67. package/dist/photo/index.cjs +1 -1
  68. package/dist/photo/index.js +1 -1
  69. package/dist/{ports-DEBzEhbp.d.cts → ports-BY2ph0_y.d.cts} +5 -15
  70. package/dist/{ports-DMolTRzU.d.ts → ports-D7YW8qz9.d.ts} +5 -15
  71. package/dist/records/depth/index.cjs +2 -2
  72. package/dist/records/depth/index.d.cts +7 -7
  73. package/dist/records/depth/index.d.ts +7 -7
  74. package/dist/records/depth/index.js +2 -2
  75. package/dist/records/index.cjs +3 -3
  76. package/dist/records/index.d.cts +9 -9
  77. package/dist/records/index.d.ts +9 -9
  78. package/dist/records/index.js +3 -3
  79. package/dist/{requestFunnel-L-BQfi0z.d.cts → requestFunnel-BjDpqqvm.d.cts} +25 -2
  80. package/dist/{requestFunnel-CjW7uDuA.d.ts → requestFunnel-DFMGcluw.d.ts} +25 -2
  81. package/dist/{runtime-B8s-_hv8.d.cts → runtimeTypes-gZEJu-da.d.cts} +9 -99
  82. package/dist/{runtime-BR9ysG0J.d.ts → runtimeTypes-w5KqBMcs.d.ts} +9 -99
  83. package/dist/server/events/index.cjs +1 -1
  84. package/dist/server/events/index.d.cts +2 -2
  85. package/dist/server/events/index.d.ts +2 -2
  86. package/dist/server/events/index.js +1 -1
  87. package/dist/server/index.cjs +1 -1
  88. package/dist/server/index.d.cts +3 -3
  89. package/dist/server/index.d.ts +3 -3
  90. package/dist/server/index.js +1 -1
  91. package/dist/televet/booking/index.cjs +1 -0
  92. package/dist/televet/booking/index.d.cts +294 -0
  93. package/dist/televet/booking/index.d.ts +294 -0
  94. package/dist/televet/booking/index.js +1 -0
  95. package/dist/televet/call/index.cjs +1 -0
  96. package/dist/televet/call/index.d.cts +141 -0
  97. package/dist/televet/call/index.d.ts +141 -0
  98. package/dist/televet/call/index.js +1 -0
  99. package/dist/televet/index.cjs +1 -1
  100. package/dist/televet/index.d.cts +87 -5
  101. package/dist/televet/index.d.ts +87 -5
  102. package/dist/televet/index.js +1 -1
  103. package/dist/testing/index.cjs +3 -3
  104. package/dist/testing/index.d.cts +2 -2
  105. package/dist/testing/index.d.ts +2 -2
  106. package/dist/testing/index.js +3 -3
  107. package/dist/testing/rn/index.cjs +1 -1
  108. package/dist/testing/rn/index.d.cts +9 -8
  109. package/dist/testing/rn/index.d.ts +9 -8
  110. package/dist/testing/rn/index.js +1 -1
  111. package/dist/testing/web/index.cjs +1 -1
  112. package/dist/testing/web/index.d.cts +9 -8
  113. package/dist/testing/web/index.d.ts +9 -8
  114. package/dist/testing/web/index.js +1 -1
  115. package/dist/{timelineRows-DZed6dAM.d.ts → timelineRows-C15jxFFH.d.ts} +1 -1
  116. package/dist/{timelineRows-CaohZzXS.d.cts → timelineRows-odO8g9r2.d.cts} +1 -1
  117. package/dist/typeStyle-CKqVYD6L.d.cts +111 -0
  118. package/dist/typeStyle-DmoyacDG.d.ts +111 -0
  119. package/dist/{useRecordsDepth-BHBzJ76R.d.cts → useRecordsDepth-C6rjEaLn.d.cts} +1 -1
  120. package/dist/{useRecordsDepth-BU-OhzH6.d.ts → useRecordsDepth-crhBllQK.d.ts} +1 -1
  121. package/dist/video/index.cjs +1 -1
  122. package/dist/video/index.js +1 -1
  123. package/dist/{view-DtSPYpKa.d.ts → view-Bxwxp4xD.d.ts} +2 -2
  124. package/dist/{view-C3qPIXGX.d.cts → view-DyitEO0m.d.cts} +2 -2
  125. package/dist/web/consent/index.cjs +1 -1
  126. package/dist/web/consent/index.d.cts +5 -5
  127. package/dist/web/consent/index.d.ts +5 -5
  128. package/dist/web/consent/index.js +1 -1
  129. package/dist/web/index.cjs +7 -7
  130. package/dist/web/index.d.cts +18 -17
  131. package/dist/web/index.d.ts +18 -17
  132. package/dist/web/index.js +7 -7
  133. package/dist/web/notifications/index.cjs +2 -2
  134. package/dist/web/notifications/index.d.cts +3 -3
  135. package/dist/web/notifications/index.d.ts +3 -3
  136. package/dist/web/notifications/index.js +2 -2
  137. package/dist/web/records/depth/index.cjs +2 -2
  138. package/dist/web/records/depth/index.d.cts +7 -7
  139. package/dist/web/records/depth/index.d.ts +7 -7
  140. package/dist/web/records/depth/index.js +2 -2
  141. package/dist/web/records/index.cjs +3 -3
  142. package/dist/web/records/index.d.cts +102 -11
  143. package/dist/web/records/index.d.ts +102 -11
  144. package/dist/web/records/index.js +3 -3
  145. package/dist/web/televet/booking/index.cjs +1 -0
  146. package/dist/web/televet/booking/index.d.cts +349 -0
  147. package/dist/web/televet/booking/index.d.ts +349 -0
  148. package/dist/web/televet/booking/index.js +1 -0
  149. package/dist/web/televet/call/index.cjs +1 -0
  150. package/dist/web/televet/call/index.d.cts +142 -0
  151. package/dist/web/televet/call/index.d.ts +142 -0
  152. package/dist/web/televet/call/index.js +1 -0
  153. package/dist/web/televet/index.cjs +1 -1
  154. package/dist/web/televet/index.d.cts +90 -4
  155. package/dist/web/televet/index.d.ts +90 -4
  156. package/dist/web/televet/index.js +1 -1
  157. package/package.json +72 -4
  158. package/televet/booking/package.json +8 -0
  159. package/televet/call/package.json +8 -0
  160. package/web/televet/booking/native-blocked.cjs +12 -0
  161. package/web/televet/booking/package.json +8 -0
  162. package/web/televet/call/native-blocked.cjs +12 -0
  163. package/web/televet/call/package.json +8 -0
  164. package/dist/typeStyle-0TydiZ1w.d.cts +0 -19
  165. package/dist/typeStyle-CWMsoe6b.d.ts +0 -19
@@ -1,4 +1,4 @@
1
- import {createContext,forwardRef,useRef,useMemo,useState,useCallback,useEffect,useReducer,createElement,useContext,useSyncExternalStore,Component}from'react';import {z}from'zod';import {TextInput,View,Pressable,ScrollView,ActivityIndicator,StyleSheet,PanResponder,KeyboardAvoidingView,Image,Linking,BackHandler,Text,Modal,AccessibilityInfo}from'react-native';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var qd=Object.defineProperty;var i=(e,t)=>qd(e,"name",{value:t,configurable:true});var Lo=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(Lo.map(e=>e.wireCode));var Fd=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),Fa=Object.freeze(Lo.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:Fd[e.wireCode]}))),zd=new Map(Fa.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Nd=Object.freeze(["http_envelope",...[...new Set(Fa.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Ln(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let o of [t??"http_envelope",...Nd]){let n=zd.get(o+r);if(n)return n}}i(Ln,"contractErrorFor");function Md(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Md,"contractDocUrl");function za(e){return null}i(za,"publishedDocUrl");var Bd=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function Na(e){return Bd[e]}i(Na,"categoryFor");function Ma(e){let t=Ln(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),o=r.replace(/[^A-Z0-9]/g,"");if(o==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(o){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Ma,"fromWire");var Hd=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Vo(e){return Hd.has(e)}i(Vo,"isAutoRetryable");var Ud=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Ba(e){return Vo(e)||Ud.has(e)}i(Ba,"isRetryableCode");var jd=500,qo=8e3,Ha=4;function Ua(e,t=Math.random){let r=Math.max(0,e),o=Math.min(jd*2**r,qo);return Math.floor(t()*o)}i(Ua,"backoffDelayMs");var $d=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function Fo(e){return $d[e]}i(Fo,"userFacingError");function ja(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(ja,"defineHidden");var Wd=/^[a-z][a-z0-9_]{0,63}$/;function q(e,t){let r=Ln(t?.wireCode,t?.wireEnvelope),o={code:e,category:Na(e),retryable:t?.retryable??Ba(e),displayMessage:Fo(e)};if(t?.httpStatus!==void 0&&(o.httpStatus=t.httpStatus),t?.requestId&&(o.requestId=t.requestId),typeof t?.reasonCode=="string"&&Wd.test(t.reasonCode)&&(o.reasonCode=t.reasonCode),r);return t?.wireMessage&&ja(o,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ja(o,"raw",t.raw),Object.freeze(o)}i(q,"makeEverfurError");function _e(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(_e,"ok");function B(e){return Object.freeze({ok:false,error:e})}i(B,"err");var Vn=class Vn extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Vn.prototype);}};i(Vn,"EverfurConfigError");var en=Vn;var Ka=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),$a=Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function Gd(e){let t=Object.prototype.hasOwnProperty.call($a,e)?$a[e]:void 0;if(t!==void 0)return t;let r=e;return Ka.has(r)?r:"parsing"}i(Gd,"normalizeStatus");function Qa(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Qa,"normalizeOrigin");var Yd=z.object({request_id:z.string().min(1),pet_ref:z.string().min(1),status:z.string(),simple_status:z.string().nullish(),simple_status_detail:z.string().nullish(),status_label:z.string().optional(),dispatch_status:z.string().nullish(),can_retry_send:z.boolean().optional(),can_revoke:z.boolean().optional(),can_convert_to_upload:z.boolean().optional(),can_update_clinic_email:z.boolean().optional(),reminder_count:z.number().int().nonnegative().optional(),last_reminder_at:z.string().nullish(),waiting_expectation:z.string().nullish(),document_count:z.number().optional(),held_item_count:z.number().optional(),received_at:z.string().nullish(),parsing_started_at:z.string().nullish(),review_started_at:z.string().nullish(),created_at:z.string().optional(),updated_at:z.string().optional(),source:z.string().nullish().catch(null),action_needed_label:z.string().nullish().catch(null),failure_reason:z.string().nullish().catch(null),failure_code:z.string().nullish().catch(null),recovery_stage:z.string().nullish().catch(null),show_clinic_phone:z.boolean().optional().catch(void 0),clinic_name:z.string().nullish().catch(null),clinic_email:z.string().nullish().catch(null),clinic_phone:z.string().nullish().catch(null),converted_to_upload_at:z.string().nullish().catch(null),request_group_id:z.string().nullish().catch(null)}).passthrough();function cr(e){let t=Yd.safeParse(e);if(!t.success)return null;let r=t.data,o=Qd(r.simple_status),n=o==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":o==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":o??Gd(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:n,simpleStatus:o,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:Ga(r.document_count,0),heldItemCount:Ga(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(cr,"mapRequestView");var Kd=z.object({request_group_id:z.string().min(1),pet_ref:z.string().min(1),total:z.number().int().nonnegative(),responded:z.number().int().nonnegative(),pending:z.number().int().nonnegative(),members:z.array(z.unknown())});function Xa(e){let t=Kd.safeParse(e);if(!t.success)return null;let r=t.data,o=zo(r.members);return o.some(n=>n.petRef!==r.pet_ref)?null:Object.freeze({requestGroupId:r.request_group_id,petRef:r.pet_ref,total:r.total,responded:r.responded,pending:r.pending,members:o})}i(Xa,"mapRequestGroup");function Qd(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Ka.has(e)?e:null}i(Qd,"normalizeSimpleStatus");function zo(e){let t=Array.isArray(e)?e:[],r=[];for(let o of t){let n=cr(o);n!==null&&r.push(n);}return Object.freeze(r)}i(zo,"mapRequestList");var Xd=z.object({source_doc_id:z.string().min(1),request_id:z.string().min(1)});function Ja(e){let t=Xd.safeParse(e);return t.success?Object.freeze({documentId:t.data.source_doc_id,requestId:t.data.request_id,status:"received"}):null}i(Ja,"mapUploadedDocument");var Jd=z.object({label:z.string(),value:z.string()}),No=z.object({key:z.string(),category:z.string().optional(),label:z.string().optional(),value:z.string().nullish(),unit:z.string().nullish(),observed_at:z.string().nullish(),status:z.string().nullish(),origin:z.string().nullish(),canonical_key:z.string().nullish()}),Zd=z.object({at:z.string(),value:z.number().nullish(),display:z.string().nullish(),origin:z.string().nullish()}),eu=z.object({key:z.string(),label:z.string().optional(),points:z.array(Zd).optional()}),tu=z.object({title:z.string(),detail:z.string().nullish(),due_at:z.string().nullish()}),Mo=z.object({doc_id:z.string(),title:z.string().nullish(),page_count:z.number().nullish(),received_at:z.string().nullish()});function Bo(e){return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:Qa(e.origin),canonicalKey:e.canonical_key??null})}i(Bo,"mapEntityRow");function Ho(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(Ho,"mapDocumentRow");var ru=z.object({identity:z.array(Jd).optional(),entities:z.array(No).optional(),entity_series:z.array(eu).optional(),forward_looking:z.array(tu).optional(),documents:z.array(Mo).optional()});function Za(e,t){let r=ou(t)?t:{},o=Ya(r.schema_version,"epdf/1.0"),n=Ya(r.disclaimer,""),l=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Wa(l,o,n);let s=ru.safeParse(r);if(!s.success)return Wa(l,o,n);let c=s.data,a=(c.identity??[]).map(R=>Object.freeze({label:R.label,value:R.value})),d=(c.entities??[]).map(Bo),u=(c.entity_series??[]).map(R=>Object.freeze({key:R.key,label:R.label??R.key,points:Object.freeze((R.points??[]).map(v=>Object.freeze({at:v.at,value:v.value??null,display:v.display??null,origin:Qa(v.origin)})))})),p=(c.forward_looking??[]).map(R=>Object.freeze({title:R.title,detail:R.detail??null,dueAt:R.due_at??null})),f={};for(let R of c.documents??[])f[R.doc_id]=Ho(R);let h=r.is_empty===true||a.length===0&&d.length===0&&u.length===0&&p.length===0&&Object.keys(f).length===0;return Object.freeze({petRef:l,schemaVersion:o,isEmpty:h,withheld:false,generatedAt:iu(r.generated_at),identity:Object.freeze(a),entities:Object.freeze(d),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(p),documents:Object.freeze(f),disclaimer:n})}i(Za,"mapRecordView");function Wa(e,t,r){return Object.freeze({petRef:e,schemaVersion:t,isEmpty:false,withheld:true,generatedAt:null,identity:Object.freeze([]),entities:Object.freeze([]),entitySeries:Object.freeze([]),forwardLooking:Object.freeze([]),documents:Object.freeze({}),disclaimer:r})}i(Wa,"withheldView");var nu=z.object({pet_ref:z.string().optional(),granted:z.boolean().optional(),version:z.string().nullish(),granted_at:z.string().nullish()});function qn(e,t){let r=nu.safeParse(t),o=r.success?r.data:{};return Object.freeze({petRef:typeof o.pet_ref=="string"&&o.pet_ref.length>0?o.pet_ref:e,granted:o.granted===true,version:o.version??null,grantedAt:o.granted_at??null})}i(qn,"mapConsent");function ou(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ou,"isObject");function Ga(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Ga,"numberOr");function Ya(e,t){return typeof e=="string"&&e.length>0?e:t}i(Ya,"strOr");function iu(e){return typeof e=="string"&&e.length>0?e:null}i(iu,"strOrNull");var es=Object.freeze(["published","failed","revoked"]);function zr(e){return es.includes(e)}i(zr,"isTerminalStatus");function dr(e){if(e===null)return null;let t=e.recordsReason;return t==="consent_required"||t==="session_required"||t==="entitlement"||t==="pet_not_found"?t:null}i(dr,"recordsDenialReasonOf");var au="records_consent_required";function su(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,o=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof o=="string"&&o.length>0?o:null}i(su,"recordsWireCodeOf");function tr(e){return e===null||e.httpStatus!==409?false:su(e)===au}i(tr,"isRecordsConsentRequired");var lu=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Fn(e){return e!==lu}i(Fn,"isUploadTransportAvailable");var ts=Object.freeze({record(){}}),ur=25*1024*1024,rs=64,tn=128,mt=128,rn="application/pdf",ns=9e4;function is(e){return new Uo(e)}i(is,"createRecordsController");var jo=class jo{constructor(t){this.recordCache=new Map;this.consentEpoch=new Map;this.reportedGaps=new Set;this.repository=t.repository,this.uploads=t.uploads,this.telemetry=t.telemetry??ts,this.newIdempotencyKey=t.newIdempotencyKey??mu(),this.timers=t.timers??uu,this.uploadDeadlineMs=t.uploadDeadlineMs??ns;}async createUploadRequest(t){let r=await this.repository.createRequest({pet_ref:t.petRef,idempotency_key:t.idempotencyKey});if(!r.ok)return this.onRequestError(r.error);let o=cr(r.value);return o===null?B(zn()):(this.observeRequest(o),_e(o))}async getRequest(t){let r=await this.repository.getRequest(t);if(!r.ok)return this.onRequestError(r.error);let o=cr(r.value);return o===null?B(zn()):(this.observeRequest(o),_e(o))}async listRequests(){let t=await this.repository.listRequests();if(!t.ok)return this.onRequestError(t.error);let r=zo(t.value);for(let o of r)this.observeRequest(o);return _e(r)}async uploadDocument(t){let{requestId:r,file:o}=t,n=cu(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),B(os(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(r,{content_type:rn,file_size:o.sizeBytes});if(!l.ok)return this.onRequestError(l.error);let s=await this.postToS3(l.value,o,t);if(!s.ok)return this.telemetry.record("records.upload.failed",{reason:s.reason}),B(os(s.reason));let c=await this.repository.completeUpload(r,{upload_id:l.value.upload_id});if(!c.ok)return c.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:du(c.error)??"corrupt"}),this.onRequestError(c.error);let a=Ja(c.value);return a===null?B(zn()):_e(a)}async postToS3(t,r,o){let n=new AbortController,l=pu(n.signal,o.signal),s=this.timers.setTimeout(()=>n.abort(),this.uploadDeadlineMs);try{let c={signal:l};return o.onProgress&&(c.onProgress=o.onProgress),await this.uploads.postMultipart(t,r,c),{ok:!0}}catch{return {ok:false,reason:n.signal.aborted&&o.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(s);}}async getRecord(t){let r=this.consentEpoch.get(t)??0,o=await this.repository.getRecord(t);if(r!==(this.consentEpoch.get(t)??0))return B(Object.freeze({...q("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let l=dr(o.error);return l==="consent_required"?(this.recordCache.delete(t),this.telemetry.record("records.consent.denied",{pet_ref:t})):l==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t}),B(o.error)}let n=Za(t,o.value);return n.petRef!==t?B(zn()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:t}),this.recordCache.delete(t),_e(n)):(this.recordCache.set(t,n),_e(n))}peekCachedRecord(t){return this.recordCache.get(t)??null}async getConsent(t){let r=await this.repository.getConsent(t);return r.ok?_e(qn(t,r.value)):B(r.error)}async grantConsent(t){let r=await this.repository.putConsent(t.petRef,{consent_version:t.consentVersion,idempotency_key:t.idempotencyKey});return r.ok?_e(qn(t.petRef,r.value)):(dr(r.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t.petRef}),B(r.error))}async revokeConsent(t){let r=await this.repository.deleteConsent(t);return r.ok?(this.consentEpoch.set(t,(this.consentEpoch.get(t)??0)+1),this.recordCache.delete(t),_e(qn(t,r.value))):B(r.error)}reportCapabilityDenied(t){this.telemetry.record("records.capability.denied",t?{pet_ref:t}:{});}observeRequest(t){t.reviewStartedAt!==null&&!this.reportedGaps.has(t.id)&&(this.reportedGaps.add(t.id),this.telemetry.record("records.parse.gap",{request_id:t.id}));}onRequestError(t){return dr(t)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),B(t)}};i(jo,"RecordsControllerImpl");var Uo=jo;function cu(e){if(e.mimeType!==rn)return "unsupported_format";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>ur?"oversize":null}i(cu,"validateFile");function du(e){let t=e.wireMessage;return t==="unsupported_format"||t==="oversize"||t==="corrupt"?t:null}i(du,"reasonFromWire");function os(e){return q("mediaUploadFailed",{retryable:false,wireMessage:e})}i(os,"uploadFailed");function zn(){return q("internalError",{retryable:true})}i(zn,"internal");var uu={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function pu(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let o=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),r.signal}i(pu,"mergeSignals");function mu(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(mu,"defaultIdempotencyFactory");function pr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(pr,"assertNever");function as(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(as,"errorFrame");function gu(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(gu,"authHeaders");function nn(e,t){return {...e,headers:{...bu(e.headers),...gu(t)}}}i(nn,"withAuthHeaders");function bu(e){if(!e)return {};let t={};for(let[r,o]of Object.entries(e)){let n=r.toLowerCase();n==="authorization"||n==="x-everfur-partner-key"||(t[r]=o);}return t}i(bu,"stripAuthHeaders");async function ss(e,t){if(t.mode==="anonymous")return t.transport.request(nn(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return B($o())}let o=await t.transport.request(nn(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(o.ok||o.error.httpStatus!==401)return o;let n;try{n=await t.identity.currentToken({forceRefresh:!0});}catch{return B($o())}let l=await t.transport.request(nn(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?B($o(l.error.httpStatus)):l}i(ss,"authedSend");function $o(e){return q("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i($o,"authRejectedError");function ls(e){return q("internalError",{retryable:true,wireMessage:hu(e)})}i(ls,"networkError");function hu(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(hu,"describeCause");var Ru=3e4,vu=qo*2,xu="idempotency-key",wu=new Set(["POST","PUT","PATCH","DELETE"]),Cu=Object.freeze({onEvent(){}}),Eu=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function mr(e){let t=e.observer??Cu,r=e.timers??Eu,o=e.rng??Math.random,n=e.sleep??((f,h)=>qu(f,r,h)),l=e.maxAttempts??Ha,s=e.unaryTimeoutMs??Ru,c=e.newIdempotencyKey??rr(),a=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,h,R){let v=R?.maxAttempts,y=Math.max(1,v??l),b=R?.idempotent??wu.has(h.method)?c():null,w=Su(h,b),x=0;for(;;){let E=i($=>Object.freeze({call:f,method:h.method,path:h.path,attempt:x,...b?{idempotencyKey:b}:{},...$}),"stamp");a(E({phase:"attempt"}));let D=Lu(s,r),k=Vu(D.signal,h.signal),S;try{S=await ss({...w,signal:k.signal},e.auth);}catch($){S=B(ls($));}finally{k.dispose(),D.cancel();}if(S.ok)return a(E({phase:"settled",ok:true,reason:"ok"})),S;let I=S.error,Y=Tu(I,x,{maxAttempts:y,rng:o,now:r.now(),aborted:h.signal?.aborted===true,...v!==void 0?{perCallMaxAttempts:v}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),z={ok:false,code:I.code,reason:Y.reason,...I.httpStatus!==void 0?{httpStatus:I.httpStatus}:{},...I.requestId!==void 0?{requestId:I.requestId}:{}};if(!Y.retry)return a(E({phase:"settled",...z})),B(I);if(a(E({phase:"retry",...z,delayMs:Y.delayMs})),await n(Y.delayMs,h.signal),h.signal?.aborted===true)return a(E({phase:"settled",...z,reason:"aborted"})),B(I);x+=1;}}i(d,"send");async function u(f){return nn(f,await Ou(e.auth))}i(u,"authorize");async function*p(f,h,R){a(Object.freeze({call:f,phase:"stream.open",method:h.method,path:h.path,attempt:0}));try{yield*e.auth.transport.stream(h,R);}catch{yield as({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:u,stream:p})}i(mr,"createRequestFunnel");function Su(e,t){let r={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==xu&&(r[o]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Su,"assembleHeaders");function rr(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(rr,"defaultIdempotencyKeyFactory");var ku=10;function Tu(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let o=_u(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!Vo(e.code))return {retry:false,reason:"terminal-code"};let n=o==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let s=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(ku,Math.floor(d)))},"policyCeiling"),c=r.perCallMaxAttempts??s()??r.maxAttempts;if(t+1>=c)return {retry:false,reason:"attempts-exhausted"};let a=Pu(e,r.now);return a!==null?a>vu?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:a}:{retry:true,reason:n,delayMs:Ua(t,r.rng)}}i(Tu,"decideRetry");function _u(e){let t=e.code==="unknown"?Ma(Au(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(_u,"throttleKind");function Pu(e,t){let r=Iu(e.raw);if(r===null)return null;let o=r-t;return o>0?o:0}i(Pu,"retryOverrideMs");function Iu(e){for(let t of ds(e)){let r=t.resets_at,o=Du(r);if(o!==null)return o}return null}i(Iu,"findResetsAt");function ds(e){if(!cs(e))return [];let t=[e];for(let r of ["error","detail"]){let o=e[r];cs(o)&&t.push(o);}return t}i(ds,"candidateScopes");function Du(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(Du,"parseInstantMs");function Au(e){for(let t of ds(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Au,"rawWireCode");function cs(e){return typeof e=="object"&&e!==null}i(cs,"isRecord");async function Ou(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(Ou,"resolveDeviceAuth");function Lu(e,t){let r=new AbortController,o=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(o),"cancel")}}i(Lu,"boundedSignal");function Vu(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let o=new AbortController;if(e.aborted||t.aborted)return o.abort(),{signal:o.signal,dispose:r};let n=i(()=>o.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),{signal:o.signal,dispose:i(()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",n);},"dispose")}}i(Vu,"mergeSignals");function qu(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(o=>{let n=t.setTimeout(()=>{r?.removeEventListener("abort",l),o();},e),l=i(()=>{t.clearTimeout(n),o();},"onAbort");r?.addEventListener("abort",l,{once:true});})}i(qu,"delayAbortable");function yr(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let o=e.charCodeAt(t+1);if(!(o>=56320&&o<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(yr,"hasLoneSurrogate");var nr="/widget/v1/records";function ps(e){let{auth:t}=e,r=t.mode,o=e.funnel??mr({auth:t,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(a,d,u)=>{let p=await o.send(a,d);return p.ok?p:B(Nu(p.error,r,u))},"send"),l=i((a,d)=>typeof d!="string"||d.length===0?q("validationFailed",{retryable:false,wireMessage:`${a} is required and must be a non-empty string`}):yr(d)?q("validationFailed",{retryable:false,wireMessage:`${a} contains an unpaired surrogate and cannot be encoded`}):null,"segmentError"),s=i((a,d,u)=>{let p=l(a,d);if(p!==null)return p;let h=[...d].length;return h>u?q("validationFailed",{retryable:false,wireMessage:`${a} is ${h} characters; the server accepts at most ${u}`}):null},"boundsError"),c=i((...a)=>a.find(d=>d!==null)??null,"firstError");return {createRequest:i(a=>{let d=c(s("idempotency_key",a.idempotency_key,tn),s("pet_ref",a.pet_ref,mt));return d?Promise.resolve(B(d)):n("records.createRequest",Wo(`${nr}/requests`,a),"request")},"createRequest"),initiateUpload:i((a,d)=>{let u=l("request_id",a);return u?Promise.resolve(B(u)):n("records.initiateUpload",Wo(`${nr}/requests/${encodeURIComponent(a)}/uploads/initiate`,d),"request")},"initiateUpload"),completeUpload:i((a,d)=>{let u=l("request_id",a);return u?Promise.resolve(B(u)):n("records.completeUpload",Wo(`${nr}/requests/${encodeURIComponent(a)}/uploads/complete`,d),"request")},"completeUpload"),getRequest:i(a=>{let d=l("request_id",a);return d?Promise.resolve(B(d)):n("records.getRequest",Nn(`${nr}/requests/${encodeURIComponent(a)}`),"request")},"getRequest"),listRequests:i(async()=>{let a=await n("records.listRequests",Nn(`${nr}/requests`),"request");if(!a.ok)return a;let d=a.value;return {ok:true,value:Array.isArray(d)?d:d.items??[]}},"listRequests"),getRecord:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.getRecord",Nn(`${nr}/pets/${encodeURIComponent(a)}/record`),"content")},"getRecord"),getConsent:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.getConsent",Nn(`${nr}/pets/${encodeURIComponent(a)}/consent`),"consent")},"getConsent"),putConsent:i((a,d)=>{let u=c(s("consent_version",d.consent_version,rs),s("idempotency_key",d.idempotency_key,tn),s("pet_ref",a,mt));return u?Promise.resolve(B(u)):n("records.putConsent",Mu(`${nr}/pets/${encodeURIComponent(a)}/consent`,d),"consent")},"putConsent"),deleteConsent:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.deleteConsent",Bu(`${nr}/pets/${encodeURIComponent(a)}/consent`),"consent")},"deleteConsent")}}i(ps,"createHttpRecordsRepository");function us(e,t){let r={...e,recordsReason:t};for(let o of ["wireMessage","raw"]){let n=Object.getOwnPropertyDescriptor(e,o);n!==void 0&&Object.defineProperty(r,o,n);}return Object.freeze(r)}i(us,"withReason");var Fu="pet_not_registered";function zu(e){return e.httpStatus!==404?null:e.reasonCode===Fu?"pet_not_found":"entitlement"}i(zu,"recordsErrorReasonFor");function Nu(e,t,r){let o=zu(e);return o!==null?us(e,o):e.code!=="accessDenied"?e:us(e,t==="anonymous"?"session_required":r==="content"?"consent_required":"entitlement")}i(Nu,"tagReason");function Nn(e){return {method:"GET",path:e}}i(Nn,"get");function Wo(e,t){return {method:"POST",path:e,body:t}}i(Wo,"post");function Mu(e,t){return {method:"PUT",path:e,body:t}}i(Mu,"put");function Bu(e){return {method:"DELETE",path:e}}i(Bu,"del");var ms=Symbol.for("@everfur/sdk#EverfurContext@v1"),ys=globalThis,fs=ys[ms]??(ys[ms]=createContext(null));fs.displayName??="EverfurContext";function ke(){let e=useContext(fs);if(e===null)throw new en("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ke,"useEverfurContext");var Go=new Map,Yo=new Set;function gs(e){Go.set(e,(Go.get(e)??0)+1);for(let t of [...Yo])t();}i(gs,"notifyRecordsConsentWithdrawn");function Wu(e){return Go.get(e)??0}i(Wu,"recordsConsentEpochOf");function Gu(e){return Yo.add(e),()=>{Yo.delete(e);}}i(Gu,"subscribe");function Mn(e){let t=useCallback(()=>Wu(e),[e]);return useSyncExternalStore(Gu,t,t)}i(Mn,"useRecordsConsentEpoch");var Qo={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},hs=4e3,Ku=30;function yt(e){let{petRef:t}=e,r=useRef(e.uploadTransport);r.current=e.uploadTransport;let o=e.uploadTransport!==void 0,{runtime:n,userRef:l,scopeEpoch:s}=ke(),c=useMemo(()=>({}),[n,l,t,s,e.controller]),a=useRef(c),[d,u]=useState({scope:c,controller:e.controller??null}),p=e.controller??(d.scope===c?d.controller:null),[f,h]=useState({scope:c,value:Qo}),R=f.scope===c?f.value:Qo,v=useCallback(C=>{h(T=>T.scope===c?{scope:c,value:C(T.value)}:T);},[c]),y=useRef(0);useEffect(()=>(a.current=c,h({scope:c,value:Qo}),()=>{a.current=null,y.current+=1;}),[c]),useEffect(()=>{if(e.controller)return;let{services:C}=n.registry,T={record:i((M,K)=>C.telemetry.track(M,K),"record")},A=n.registry.acquire("records",`${l??""}|${t}${o?"|own-upload":""}`,()=>is({repository:ps({auth:C.authFor(l),...C.errorPolicy?{errorPolicy:C.errorPolicy}:{}}),uploads:o?{postMultipart:i((M,K,ye)=>(r.current??C.uploadTransport).postMultipart(M,K,ye),"postMultipart")}:C.uploadTransport,telemetry:T}),()=>{});return u({scope:c,controller:A}),()=>{n.registry.release(A);}},[n,l,t,e.controller,s,c,o]);let g=useCallback(C=>{v(T=>({...T,...C}));},[v]),b=useCallback(async()=>{if(!p||a.current!==c)return;let C=y.current+=1;D.current=0,I(),g({loading:true,error:null,denialReason:null,withheld:false});let[T,A]=await Promise.all([p.getConsent(t),p.listRequests()]);if(C!==y.current)return;let M=T.ok?T.value:null,K=A.ok?A.value.filter(Ve=>Ve.petRef===t):[],ye=A.ok?null:A.error;if(M&&M.granted){let Ve=await p.getRecord(t);if(C!==y.current)return;if(Ve.ok){g({consent:M,requests:K,record:Ve.value,withheld:Ve.value.withheld,error:Ve.value.withheld?ep():ye,denialReason:null,loading:false});return}g({consent:M,requests:K,record:null,error:Ve.error,denialReason:dr(Ve.error),withheld:false,loading:false});return}g({consent:M,requests:K,record:null,error:T.ok?ye:T.error,denialReason:M?"consent_required":Zu(T),withheld:false,loading:false});},[p,t,g,c]);useEffect(()=>(b(),()=>{y.current+=1;}),[b]);let w=useMemo(()=>Ju(R.requests),[R.requests]),x=w?.id??null,E=w?.status??null,D=useRef(0),k=useRef(null),[S,I]=useReducer(C=>C+1,0);useEffect(()=>{if(!p||x===null||E===null||zr(E)||E==="in_review")return;k.current!==String(x)&&(k.current=String(x),D.current=0);let C=false,T=i(async()=>{if(C||D.current>=Ku)return;D.current+=1;let M=await p.getRequest(x);if(!C){if(M.ok&&M.value.petRef===t){if(v(K=>({...K,requests:Hn(K.requests,M.value)})),zr(M.value.status)){M.value.status==="published"&&b();return}if(M.value.status==="in_review")return}A=setTimeout(()=>{T();},hs);}},"tick"),A=setTimeout(()=>{T();},hs);return ()=>{C=true,clearTimeout(A);}},[p,x,E,b,S,t,v]);let Y=useCallback(async C=>{if(!p||a.current!==c)return Un();let T=await p.createUploadRequest({petRef:t,idempotencyKey:C});return a.current===c&&T.ok&&T.value.petRef===t&&v(A=>({...A,requests:Hn(A.requests,T.value)})),T},[p,t,c,v]),z=useCallback((C,T)=>{v(A=>({...A,uploadQueue:A.uploadQueue.map(M=>M.key===C?T(M):M)}));},[v]),$=useCallback(async(C,T)=>{let A=Date.now().toString(36),M=T.map((ye,Ve)=>{let ie=Qu(ye);return {key:`${A}-${Ve}`,name:ye.name??null,status:ie===null?"queued":"skipped",progress:0,skipReason:ie,error:null}}),K=[...M];if(!p||a.current!==c)return Object.freeze(K);v(ye=>({...ye,uploadQueue:M,isUploading:true,uploadProgress:0}));for(let[ye,Ve]of T.entries()){let ie=M[ye];if(ie.status==="skipped")continue;if(a.current!==c)break;z(ie.key,Xe=>({...Xe,status:"uploading",progress:0})),g({uploadProgress:0});let we=await p.uploadDocument({requestId:C,file:Ve,onProgress:i(Xe=>{if(a.current!==c)return;let Vt=Math.min(1,Math.max(0,Xe));z(ie.key,qt=>({...qt,progress:Math.max(qt.progress,Vt)})),g({uploadProgress:Vt});},"onProgress")});if(a.current!==c)break;let vt=we.ok?{...ie,status:"done",progress:1}:{...ie,status:"failed",error:we.error};if(K[ye]=vt,z(ie.key,()=>vt),we.ok){let Xe=await p.getRequest(C);a.current===c&&Xe.ok&&Xe.value.petRef===t&&v(Vt=>({...Vt,requests:Hn(Vt.requests,Xe.value)}));}}return a.current===c&&g({isUploading:false,uploadProgress:null}),Object.freeze(K)},[p,g,z,t,c,v]),G=useCallback(async(C,T)=>{if(!p||a.current!==c)return Un();let A=`${Date.now().toString(36)}-0`;v(K=>({...K,isUploading:true,uploadProgress:0,uploadQueue:[{key:A,name:T.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let M=await p.uploadDocument({requestId:C,file:T,onProgress:i(K=>{a.current===c&&(g({uploadProgress:K}),z(A,ye=>({...ye,progress:Math.max(ye.progress,Math.min(1,K))})));},"onProgress")});if(a.current!==c)return M;if(g({isUploading:false,uploadProgress:null}),z(A,K=>M.ok?{...K,status:"done",progress:1}:{...K,status:"failed",error:M.error}),M.ok){let K=await p.getRequest(C);a.current===c&&K.ok&&K.value.petRef===t&&v(ye=>({...ye,requests:Hn(ye.requests,K.value)}));}return M},[p,g,z,t,c,v]),Z=useCallback(async(C,T)=>{if(!p||a.current!==c)return Un();let A=await p.grantConsent({petRef:t,consentVersion:C,idempotencyKey:T});return A.ok&&a.current===c&&b(),A},[p,t,b,c]),oe=useCallback(async()=>{if(!p||a.current!==c)return Un();let C=await p.revokeConsent(t);return C.ok&&gs(t),C.ok&&a.current===c&&(y.current+=1,g({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:C.value})),C},[p,t,g,c]),Ee=useCallback(()=>{b();},[b]),H=Xu(R,p!==null);return useMemo(()=>({status:H,record:R.record,requests:R.requests,activeRequest:w,consent:R.consent,error:R.error,denialReason:R.denialReason,withheld:R.withheld,isUploading:R.isUploading,uploadProgress:R.uploadProgress,uploadQueue:R.uploadQueue,createRequest:Y,uploadDocument:G,uploadDocuments:$,grantConsent:Z,revokeConsent:oe,refresh:Ee}),[H,R,w,Y,G,$,Z,oe,Ee])}i(yt,"useEverfurRecords");function Qu(e){if(e.mimeType!==rn)return "unsupported";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>ur?"too_large":null}i(Qu,"skipReasonFor");function Xu(e,t){return e.loading||!t?"loading":e.withheld||e.denialReason!==null||e.error!==null?"error":e.record!==null&&!e.record.isEmpty||e.requests.length>0?"populated":"empty"}i(Xu,"selectStatus");function Ju(e){if(e.length===0)return null;let t=e[0];for(let r of e)r.updatedAt>t.updatedAt&&(t=r);return t}i(Ju,"newestRequest");function Hn(e,t){let r=e.filter(o=>o.id!==t.id);return [t,...r]}i(Hn,"replaceRequest");function Zu(e){return e.ok?"consent_required":dr(e.error)??"consent_required"}i(Zu,"consentDenial");function ep(){return q("internalError",{retryable:false})}i(ep,"withheldSentinel");function Un(){return {ok:false,error:q("internalError",{retryable:true})}}i(Un,"notReady");function Xo(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(Xo,"reportHostFailure");function tp(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(tp,"isThenable");function jn(e,...t){if(typeof e=="function")try{let r=e(...t);return tp(r)&&Promise.resolve(r).then(void 0,Xo),r}catch(r){Xo(r);return}}i(jn,"callHost");var Rs=new WeakMap;function an(e){if(typeof e!="function")return;let t=Rs.get(e);if(t!==void 0)return t;let r=i((...o)=>{jn(e,...o);},"guarded");return Rs.set(e,r),r}i(an,"guardHost");function Fe(e,t){let r=null;for(let o of t){let n=e[o];typeof n=="function"&&(r??={...e},r[o]=an(n));}return r??e}i(Fe,"guardHostProps");function kr(e,...t){let r;try{r=e(...t);}catch(o){return Xo(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(r).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(kr,"callHostAsync");var vs=Object.freeze({name:"dashboard"});function $n(e=vs){return Object.freeze({stack:Object.freeze([e])})}i($n,"initialRecordsNav");function Wn(e){return e.stack[e.stack.length-1]??vs}i(Wn,"currentRecordsScreen");function Jo(e,t){return Object.freeze({stack:Object.freeze([...e.stack,t])})}i(Jo,"pushRecordsNav");function Zo(e,t){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),t])})}i(Zo,"replaceRecordsNav");function ei(e){return $n(e)}i(ei,"resetRecordsNav");function Gn(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(Gn,"popRecordsNav");function xs(e,t){return t.name==="dashboard"?ei(t):Wn(e).name==="upload"&&t.name==="request"?Zo(e,t):Jo(e,t)}i(xs,"transitionRecordsNav");function ti(e,t){switch(t.type){case "push":return Jo(e,t.screen);case "pop":return Gn(e).state;case "replace":return Zo(e,t.screen);case "reset":return ei(t.screen);case "navigate":return xs(e,t.screen);default:return e}}i(ti,"recordsNavReducer");function oi(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))oi(e[t]);}return e}i(oi,"deepFreeze");var rp=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Cs={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Es={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},ws={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},np={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},op={regular:"400",medium:"500",bold:"700"},ip={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},ap=0,Yn="System",Kn="monospace",sp=["content","heading","control","compact","badge"];function lp(e){let t={};for(let r of sp)t[r]=e;return t}i(lp,"authoredTierSizes");function Ss(){return {family:Yn,mono:Kn,fontUrl:null,families:{regular:Yn,medium:Yn,bold:Yn,mono:Kn,monoMedium:Kn,monoBold:Kn},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:ws,tierSizes:lp(ws),lineHeight:np,weight:op,letterSpacing:ip,scale:1,maxScale:ap,scaleCaps:rp}}i(Ss,"baseType");var ks={},ri=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function ni(e){return `cubic-bezier(${e.join(", ")})`}i(ni,"cssCubicBezier");var Ts={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:ni(ri.standard),emphasized:ni(ri.emphasized),exit:ni(ri.exit)},reducedMotion:false},cp={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#B91C1C",errorRed:"#FF1B00",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},_s=oi({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:cp,space:Cs,radius:Es,type:Ss(),motion:Ts,slots:ks}),dp={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A938C",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"};oi({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:dp,space:Cs,radius:Es,type:Ss(),motion:Ts,slots:ks});var Ps=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Is=globalThis,ii=Is[Ps]??(Is[Ps]=createContext(_s));ii.displayName??="EverfurThemeContext";function L(){return useContext(ii)}i(L,"useEverfurTheme");function gp(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(gp,"tierMultiplier");function m({tier:e="content",...t}){let{type:r}=L(),o=gp(r,e);return createElement(Text,o===void 0?t:{maxFontSizeMultiplier:o,...t})}i(m,"Text");var qe=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var bp=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function _(e,t){let r=e.type,o=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:o}:{fontFamily:o,fontWeight:r.weight[bp[t]]}}i(_,"face");var U=Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you\u2019re authorizing",send:"Send request",sending:"Sending\u2026",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can\u2019t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used"});var xe=Object.freeze({title:U.title,placeholder:U.placeholder,searchA11y:U.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload\u2026",uploadOwnA11y:"Upload records you already have",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:U.recentlyUsed,noMatch:i(e=>`No clinics match \u201C${e}\u201D. You can still request records using the option above.`,"noMatch"),loadingMore:"Loading more\u2026",loadMoreFailed:"Couldn\u2019t load more. Tap to retry.",loadMoreRetryA11y:"Retry loading more clinics",selectA11y:i(e=>`Request records from ${e}`,"selectA11y"),fallback:Object.freeze({title:"Can\u2019t find your clinic?",subtitle:"Add it by email and we\u2019ll request your records.",expandA11y:"Can't find your clinic? Add it by email to request records.",collapseA11y:"Hide the request-by-email form",nameLabel:"Clinic name",namePlaceholder:"Your clinic\u2019s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue",submitA11y:"Request records by email"})});function As(e){switch(e){case "verified":return {label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case "unverified":return {label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return {label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}i(As,"clinicEmailStatusBadge");function Os(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(Os,"formatClinicDistanceLabel");function Ls(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(Ls,"formatClinicDistanceForA11y");var Vs=300,ai=2;var ce=Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"});function qs(e){return !zr(e.status)}i(qs,"isRecordsInProgress");function Qn(e,t){if(t===null)return null;let r=e.filter(l=>l.petRef===t);if(r.length===0)return null;let o=r.find(l=>l.status==="published");return o!==void 0?o:r.filter(qs).sort((l,s)=>s.updatedAt.localeCompare(l.updatedAt))[0]??null}i(Qn,"pickPetRecordsRequest");function si(e){if(e.hasMarkers)return "published";let t=Qn(e.requests,e.petRef);return t===null?"none":t.status==="published"||qs(t)?"in_progress":"none"}i(si,"deriveRecordsDashboardState");function hp(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(hp,"selectDashboardLoading");function li(e){return hp(e)?"loading":e.hasFullRecord?"record":e.markersError||e.recordError&&!e.hasMarkers?"error":e.dashboardState==="in_progress"&&e.drivingRequest!==null?"in_progress":e.dashboardState==="none"?"none":"labs_only"}i(li,"selectDashboardView");function wt(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(wt,"recordsEmptyVariantForError");var ge=Object.freeze({loading:"Loading record request",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there\u2019s no reply by day 14.",waitingBanner:i(e=>`It\u2019s been ${e} ${e===1?"day":"days"}. Some clinics take a little longer; we\u2019ve been following up automatically and are still on it. If there\u2019s no reply by day 14, we\u2019ll let you know.`,"waitingBanner"),viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",tryAnotherClinicA11y:"Request records from a different clinic",convert:"Upload my own records instead",converting:"Switching\u2026",convertHint:"We\u2019ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we\u2019ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting\u2026",cancel:"Cancel request",cancelling:"Cancelling\u2026",cancelA11y:"Cancel this records request",cancellingA11y:"Cancelling, please wait",resend:"Resend email",resending:"Resending\u2026",resendA11y:"Resend the authorization email to the clinic",resendingA11y:"Resending the email, please wait",errors:Object.freeze({cancel:"We couldn\u2019t cancel this request. Please try again.",retry:"We couldn\u2019t retry this request. Please try again.",email:"We couldn\u2019t update the clinic email. Please try again.",convert:"We couldn\u2019t switch this to an upload. Please try again.",start:"We couldn\u2019t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function Rp(e){if(e.wireStatus==="clinic_declined")return "The clinic declined to release the records.";if(e.wireStatus==="clinic_responded_no_records")return "The clinic replied but didn\u2019t include your records.";switch(e.failureCode){case "no_response":return "The clinic didn\u2019t reply after several reminders over 14 days.";case "parse_timeout":case "parse_error":return "We received the records but couldn\u2019t read them. Uploading a clean copy usually fixes this.";case "hard_bounce":case "dispatch_failed":return "We couldn\u2019t deliver the email to the clinic.";default:return "This request didn\u2019t go through."}}i(Rp,"fallbackFailureTitle");function Fs(e){let t=e.failureReason?.trim()??"";return t.length>0?t:Rp(e)}i(Fs,"failureTitle");var vp=1440*60*1e3;function ci(e,t){if(!e.createdAt)return 0;let r=Date.parse(e.createdAt);if(Number.isNaN(r))return 0;let o=t-r;return o<=0?0:Math.floor(o/vp)}i(ci,"requestElapsedDays");var xp=7;function zs(e,t){return e.wireStatus!=="awaiting_response"?false:ci(e,t)>=xp}i(zs,"requestWaitingTooLong");function di(e){return e.status==="failed"}i(di,"isTerminalFailure");function Ns(e){return di(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(Ns,"shouldOfferRecovery");function Hs(e,t){let[r,o]=useState(""),[n,l]=useState(""),[s,c]=useState([]),[a,d]=useState(null),[u,p]=useState([]),[f,h]=useState(true),[R,v]=useState(false),[y,g]=useState(false),[b,w]=useState(null),[x,E]=useState(null),[D,k]=useState(0),S=useRef(0),I=useRef(true),Y=t?.latitude,z=t?.longitude,$=useMemo(()=>Y!==void 0&&z!==void 0?{latitude:Y,longitude:z}:void 0,[Y,z]);useEffect(()=>(I.current=true,()=>{I.current=false,S.current+=1;}),[e]),useEffect(()=>{let H=true;return h(true),e.recentClinics({limit:5}).then(C=>{H&&(C.ok&&p(C.value.clinics),h(false));}).catch(()=>{H&&h(false);}),()=>{H=false;}},[e]),useEffect(()=>{let H=r.trim();if(H.length<ai){l("");return}let C=setTimeout(()=>l(H),Vs);return ()=>clearTimeout(C)},[r]);let G=n.length>=ai;useEffect(()=>{let H=S.current+=1;if(c([]),d(null),w(null),E(null),!G){v(false);return}v(true),e.searchClinics({query:n,limit:25,...$?{location:$}:{}}).then(C=>{!I.current||H!==S.current||(C.ok?(c(C.value.clinics),d(C.value.nextCursor)):w(C.error),v(false));}).catch(()=>{I.current&&H===S.current&&v(false);});},[e,n,G,$,D]);let Z=useCallback(()=>{if(!G||a===null||y)return;let H=S.current;g(true),E(null),e.searchClinics({query:n,limit:25,cursor:a,...$?{location:$}:{}}).then(C=>{!I.current||H!==S.current||(C.ok?(c(T=>[...T,...C.value.clinics]),d(C.value.nextCursor)):E(C.error),g(false));}).catch(()=>{I.current&&H===S.current&&g(false);});},[e,a,n,G,y,$]),oe=useCallback(H=>o(H),[]),Ee=useCallback(()=>k(H=>H+1),[]);return useMemo(()=>({query:r,debouncedQuery:n,isSearchActive:G,clinics:s,recent:u,recentLoading:f,initialLoading:R,loadingMore:y,hasNextPage:a!==null,error:b,pageError:x,setQuery:oe,loadMore:Z,retry:Ee}),[r,n,G,s,u,f,R,y,a,b,x,oe,Z,Ee])}i(Hs,"useClinicPicker");function pi(e,t,r,o){return Object.freeze({key:e?.id??`free:${t??""}`,clinic:e,freeText:t,email:r,idempotencyKey:o})}i(pi,"clinicDraftFor");var Nr=10,Jn=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),sn=i((e,t=1)=>z.string().refine(r=>!yr(r)&&[...r].length>=t&&[...r].length<=e),"text"),js=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),wp=z.object({clinicId:Jn.optional(),clinicFreeText:sn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:sn(320,3).refine(e=>!js(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Jn.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0)),Cp=z.object({petRef:sn(128),ownerName:sn(200).refine(e=>e.trim().length>0&&!js(e)),authorizationVersion:sn(64),clinics:z.array(wp).min(1).max(Nr)}).strict(),Ep=z.object({request_group_id:Jn,pet_ref:z.string(),created_count:z.number().int().nonnegative(),failed_count:z.number().int().nonnegative(),results:z.array(z.object({idempotency_key:z.string(),clinic_id:Jn.nullable().optional(),clinic_free_text:z.string().nullable().optional(),created:z.boolean(),request:z.unknown().optional(),failure_code:z.string().nullable().optional(),failure_reason:z.string().nullable().optional()}))});function $s(e){let t=e.funnel??mr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!Cp.safeParse(r).success)return B(q("validationFailed",{retryable:false}));let o=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(s=>({...s.clinicId!==void 0?{clinic_id:s.clinicId}:{clinic_free_text:s.clinicFreeText},...s.clinicEmail!==void 0?{clinic_email:s.clinicEmail}:{},...s.signatureId!==void 0?{signature_id:s.signatureId}:{signature_png_base64:s.signaturePngBase64},idempotency_key:s.idempotencyKey}))}});if(!o.ok)return o;let n=Ep.safeParse(o.value);if(!n.success||n.data.pet_ref!==r.petRef)return Us();let l=[];for(let s of n.data.results){let c=s.request===void 0||s.request===null?null:cr(s.request);if(s.created!==(c!==null))return Us();l.push(Object.freeze({idempotencyKey:s.idempotency_key,clinicId:s.clinic_id??null,clinicFreeText:s.clinic_free_text??null,created:s.created,request:c,failureCode:s.failure_code??null,failureReason:s.failure_reason??null}));}return _e(Object.freeze({requestGroupId:n.data.request_group_id,petRef:n.data.pet_ref,results:Object.freeze(l),createdCount:n.data.created_count,failedCount:n.data.failed_count}))}}}i($s,"createRecordsClinicBatchClient");function Us(){return B(q("internalError",{retryable:false}))}i(Us,"malformed");var Ws=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Sp=z.object({clinics:z.array(z.object({clinic_id:Ws,name:z.string().min(1),address:z.string().nullable(),phone:z.string().nullable(),email_status:z.string(),distance_km:z.number().finite().nonnegative().nullable()})),next_cursor:z.string().nullable().optional()}),kp=z.object({authorization_version:z.string().min(1),scope_template:z.string().min(1),authorization_template:z.string().min(1)}),Tp=z.object({upload_id:z.string().min(1),upload_url:z.string().url().refine(e=>e.startsWith("https://")),upload_fields:z.record(z.string())});function Gs(e){let{repository:t}=e,r=i(async n=>{let l=await n;if(!l.ok)return l;let s=cr(l.value);return s===null?Tr():_e(s)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let s=Sp.safeParse(l.value);return s.success?_e(Object.freeze({clinics:Object.freeze(s.data.clinics.map(c=>Object.freeze({id:c.clinic_id,name:c.name,address:c.address,phone:c.phone,emailStatus:c.email_status,distanceKm:c.distance_km}))),nextCursor:s.data.next_cursor??null})):Tr()},"page");return {searchClinics:i((n={})=>o(t.searchClinics(n)),"searchClinics"),recentClinics:i((n={})=>o(t.recentClinics(n)),"recentClinics"),async getRequestGroup(n){let l=await t.getRequestGroup(n);if(!l.ok)return l;let s=Xa(l.value);return s===null?Tr():_e(s)},async getAuthorizationCopy(){let n=await t.getAuthorizationCopy();if(!n.ok)return n;let l=kp.safeParse(n.value);return l.success?_e(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):Tr()},async createClinicRequest(n){let l=await r(t.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?Tr():l},retryRequest:i(n=>r(t.retryRequest(n)),"retryRequest"),revokeRequest:i(n=>r(t.revokeRequest(n)),"revokeRequest"),updateClinicEmail:i((n,l)=>r(t.updateClinicEmail(n,l)),"updateClinicEmail"),convertToUpload:i(n=>r(t.convertToUpload(n)),"convertToUpload"),async initiateSignatureUpload(n){let l=await t.initiateSignatureUpload(n);if(!l.ok)return l;let s=Tp.safeParse(l.value);return s.success?_e(Object.freeze({uploadId:s.data.upload_id,uploadUrl:s.data.upload_url,uploadFields:Object.freeze(s.data.upload_fields)})):Tr()},async completeSignatureUpload(n){let l=await t.completeSignatureUpload(n);if(!l.ok)return l;let s=z.object({signature_id:Ws}).safeParse(l.value);return s.success?_e(s.data.signature_id):Tr()}}}i(Gs,"createRecordsClinicController");function Tr(){return B(q("internalError",{retryable:false}))}i(Tr,"malformed");var fr="/widget/v1/records",Ys=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),br=i((e,t=1)=>z.string().refine(r=>!yr(r)&&[...r].length>=t&&[...r].length<=e),"text"),Qs=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),Xs=br(320,3).refine(e=>!Qs(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),Ks=br(64),_p=z.object({limit:z.number().int().min(1).max(25).optional()}).strict(),Pp=z.object({query:br(200,0).optional(),location:z.object({latitude:z.number().finite().min(-90).max(90),longitude:z.number().finite().min(-180).max(180)}).strict().optional(),limit:z.number().int().min(1).max(100).optional(),cursor:br(512,0).optional()}).strict(),Ip=z.object({petRef:br(128),ownerName:br(200).refine(e=>e.trim().length>0&&!Qs(e)),authorizationVersion:br(64),clinicId:Ys.optional(),clinicFreeText:br(200).refine(e=>e.trim().length>0).optional(),clinicEmail:Xs.optional(),signatureId:Ys.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0));function Js(e){let t=e.funnel??mr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((n,l,s=false)=>t.send(`records.clinic.${n}`,l,l.method==="GET"||s?void 0:{idempotent:false,maxAttempts:1}),"send"),o=i((n,l,s)=>Ks.safeParse(n).success?r(l,{method:"POST",path:`${fr}/requests/${encodeURIComponent(n)}/${l}`,...s?{body:s}:{}}):gr(),"recover");return {searchClinics(n){return Pp.safeParse(n).success?r("search",{method:"GET",path:`${fr}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):gr()},recentClinics(n){return _p.safeParse(n).success?r("recent",{method:"GET",path:`${fr}/clinics/recent`,query:{limit:n.limit}}):gr()},getRequestGroup(n){return Ks.safeParse(n).success?r("requestGroup",{method:"GET",path:`${fr}/request-groups/${encodeURIComponent(n)}`}):gr()},getAuthorizationCopy:i(()=>r("authorizationCopy",{method:"GET",path:`${fr}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return Ip.safeParse(n).success?r("create",{method:"POST",path:`${fr}/clinic-requests`,body:{pet_ref:n.petRef,owner_name:n.ownerName,authorization_version:n.authorizationVersion,idempotency_key:n.idempotencyKey,...n.clinicId!==void 0?{clinic_id:n.clinicId}:{clinic_free_text:n.clinicFreeText},...n.clinicEmail!==void 0?{clinic_email:n.clinicEmail}:{},...n.signatureId!==void 0?{signature_id:n.signatureId}:{signature_png_base64:n.signaturePngBase64}}},true):gr()},retryRequest:i(n=>o(n,"retry"),"retryRequest"),revokeRequest:i(n=>o(n,"revoke"),"revokeRequest"),convertToUpload:i(n=>o(n,"convert-to-upload"),"convertToUpload"),updateClinicEmail(n,l){return Xs.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):gr()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?gr():r("signatureInitiate",{method:"POST",path:`${fr}/signatures/initiate`,body:{content_type:"image/png",file_size:n}})},completeSignatureUpload(n){return /^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n)?r("signatureComplete",{method:"POST",path:`${fr}/signatures/complete`,body:{upload_id:n}}):gr()}}}i(Js,"createHttpRecordsClinicRepository");function gr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(gr,"invalid");function Nt(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:l}=e.registry;return Gs({repository:Js({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>{let l=i(async s=>{if(t===null||n.current!==o)return B(q("accessDenied"));let c=await s();return n.current===o?c:B(q("accessDenied"))},"run");return {searchClinics:i(s=>l(()=>o.searchClinics(s)),"searchClinics"),recentClinics:i(s=>l(()=>o.recentClinics(s)),"recentClinics"),getRequestGroup:i(s=>l(()=>o.getRequestGroup(s)),"getRequestGroup"),getAuthorizationCopy:i(()=>l(()=>o.getAuthorizationCopy()),"getAuthorizationCopy"),createClinicRequest:i(s=>l(()=>o.createClinicRequest(s)),"createClinicRequest"),retryRequest:i(s=>l(()=>o.retryRequest(s)),"retryRequest"),revokeRequest:i(s=>l(()=>o.revokeRequest(s)),"revokeRequest"),updateClinicEmail:i((s,c)=>l(()=>o.updateClinicEmail(s,c)),"updateClinicEmail"),convertToUpload:i(s=>l(()=>o.convertToUpload(s)),"convertToUpload"),initiateSignatureUpload:i(s=>l(()=>o.initiateSignatureUpload(s)),"initiateSignatureUpload"),completeSignatureUpload:i(s=>l(()=>o.completeSignatureUpload(s)),"completeSignatureUpload")}},[o,t])}i(Nt,"useEverfurRecordsClinic");function mi(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:l}=e.registry;return $s({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>({async createClinicRequestBatch(l){if(t===null||n.current!==o)return B(q("accessDenied"));let s=await o.createClinicRequestBatch(l);return n.current===o?s:B(q("accessDenied"))}}),[o,t])}i(mi,"useEverfurRecordsClinicBatch");var gi=class gi extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,o){return Object.is(r.resetKey,o.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(gi,"HostRenderBoundary");var yi=gi;function Ap({render:e}){return e()}i(Ap,"RenderHost");function fi({render:e,fallback:t,resetKey:r}){return createElement(yi,{fallback:t,resetKey:r,children:createElement(Ap,{render:e})})}i(fi,"HostRender");var Op=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function Lp(e){return Op[e]}i(Lp,"requires");function rl(e,t,r){let o=Lp(e),n=new Map;for(let c of t)n.set(c.resource,c);if(r?.isPending===true&&o.some(c=>!n.has(c)))return bi({name:e,enabled:false,isPending:true,limits:{}});let l=Vp(o,n);return o.filter(c=>n.get(c)?.granted!==true).length===0?bi({name:e,enabled:true,isPending:false,limits:l}):bi({name:e,enabled:false,isPending:false,limits:l,disabled:qp(o,n)})}i(rl,"decideCapability");function Vp(e,t){let r={};for(let o of e){let n=t.get(o)?.limits;if(n)for(let[l,s]of Object.entries(n)){let c=r[l];r[l]=c===void 0?s:Math.min(c,s);}}return r}i(Vp,"mergeLimits");function qp(e,t){for(let r of e){let o=t.get(r)?.disabled;if(o)return Object.freeze({reason:o.reason,level:o.level,recoverable:o.recoverable})}return Object.freeze({reason:Fo("accessDenied"),level:"user_entitlement",recoverable:false})}i(qp,"disabledFor");function bi(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(bi,"freezeDecision");function hi(e){let{runtime:t}=ke(),r=t.entitlements,o=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>rl(e,o.decisions,{isPending:o.isPending}),[e,o])}i(hi,"useCapability");var Np=48;function Mp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Mp,"selectView");function Ne(e){let{capability:t,children:r,renderDisabled:o,renderPending:n,style:l}=e,s=hi(t),c=useMemo(()=>Mp(s),[s]);switch(c){case "enabled":return r;case "pending":return n?jsx(fi,{render:n,fallback:jsx(ol,{capability:t,style:l})}):jsx(ol,{capability:t,style:l});case "disabled":return o?jsx(fi,{render:()=>o(s),fallback:jsx(il,{decision:s,style:l}),resetKey:s}):jsx(il,{decision:s,style:l});default:return pr(c)}}i(Ne,"CapabilityGate");function ol({capability:e,style:t}){let r=L(),o=useMemo(()=>al(r),[r]);return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:o.skeletonBar})})}i(ol,"PendingSkeleton");function il({decision:e,style:t}){let r=L(),o=useMemo(()=>al(r),[r]),n=e.disabled?.reason??"";return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:n,children:n.length>0?jsx(m,{style:o.offstateText,children:n}):null})}i(il,"OffState");function al(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({offstate:{minHeight:Np,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:o.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{..._(e,"regular"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:o.xs,backgroundColor:t.brandSofter}})}i(al,"makeStyles");var ln=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function Me(e){let t=L(),r=useMemo(()=>Up(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${ln.title}. ${ln.body}`,children:[jsx(m,{style:r.title,children:ln.title}),jsx(m,{style:r.body,children:ln.body})]})}i(Me,"ClinicalDisclaimer");function Up(e){let{color:t,space:r,type:o}=e;return StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{..._(e,"bold"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.secondary,letterSpacing:o.letterSpacing.eyebrow},body:{..._(e,"regular"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.muted}})}i(Up,"makeStyles");function Je(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(Je,"slotBox");function ot(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(ot,"slotText");var cl=Object.freeze({idle:Object.freeze({title:"Find your pet\u2019s clinic",body:"Search for the clinic that holds your pet\u2019s records. We\u2019ll request them on your behalf once you sign the authorization.",action:null}),no_requests:Object.freeze({title:"No record requests yet",body:"When you request records from a clinic, you\u2019ll be able to track every step here.",action:null}),no_records:Object.freeze({title:"Nothing to show just yet",body:"Once your pet\u2019s records arrive and our team reviews them, lab trends and visits will appear here.",action:null}),rate_limited:Object.freeze({title:"Slow down a moment",body:"You\u2019ve made a lot of requests just now. You can try again shortly.",action:"Try again"}),service_unavailable:Object.freeze({title:"Records search is temporarily down",body:"We\u2019re working on it. Please try again in a few minutes.",action:"Try again"}),error:Object.freeze({title:"Couldn\u2019t reach Everfur",body:"Check your connection and try again.",action:"Try again"})}),xi=60;function dl(e){return `Try again in ${e}s`}i(dl,"coolingActionLabel");var ul="Try again, available shortly";function Qe({variant:e,onAction:t,message:r,testID:o}){let n=Yp(),l=cl[e],[s,c]=useState(e==="rate_limited"?xi:0);useEffect(()=>{e==="rate_limited"&&c(xi);},[e]),useEffect(()=>{if(s<=0)return;let u=setTimeout(()=>c(p=>Math.max(0,p-1)),1e3);return ()=>clearTimeout(u)},[s]);let a=e==="rate_limited"&&s>0,d=a?dl(s):l.action;return jsxs(View,{style:n.container,accessibilityRole:"summary",testID:o,children:[jsx(View,{style:n.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:n.title,children:l.title}),jsx(m,{style:n.body,children:r??l.body}),d!==null&&t?jsx(Pressable,{onPress:t,disabled:a,accessibilityRole:"button",accessibilityLabel:a?ul:d,accessibilityState:{disabled:a},style:[n.action,a?n.actionDisabled:null],testID:o?`${o}-action`:`records-empty-${e}-action`,children:jsx(m,{style:n.actionLabel,children:d})}):null]})}i(Qe,"RecordsEmptyState");function Yp(){let e=L();return useMemo(()=>Kp(e),[e])}i(Yp,"useStyles");function Kp(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=r.lg+r.xs+r.xs/2;return StyleSheet.create({container:{paddingVertical:r.xxl,paddingHorizontal:r.xl,alignItems:"center",gap:r.sm+r.xs/2},glyph:{width:s,height:s,borderRadius:s/2,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug)-1,color:t.brandInk,textAlign:"center"},body:{..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.normal),color:t.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:r.sm,minHeight:r.xxl+r.sm,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,backgroundColor:t.brand,alignItems:"center",justifyContent:"center",...Je(l.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug)-1,...ot(l.primaryButton)}})}i(Kp,"makeStyles");var Ze="Back";function et({title:e,onBack:t,right:r,testID:o,variant:n="brand"}){let l=dn();return jsxs(View,{style:l.row,testID:o,children:[t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Ze,hitSlop:12,style:l.back,testID:o?`${o}-back`:void 0,children:jsx(View,{style:l.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):jsx(View,{style:l.back}),jsx(m,{style:n==="document"?l.documentTitle:l.title,accessibilityRole:"header",numberOfLines:1,children:e}),jsx(View,{style:l.right,children:r??jsx(View,{style:l.back})})]})}i(et,"ScreenHeader");function fl(){let e=dn();return jsxs(View,{style:e.listGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar})]})}i(fl,"ListGlyph");function gl(){let e=dn();return jsxs(View,{style:e.shareGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:[e.shareDot,e.shareDotTop]}),jsx(View,{style:[e.shareDot,e.shareDotLeft]}),jsx(View,{style:[e.shareDot,e.shareDotBottom]}),jsx(View,{style:[e.shareStroke,e.shareStrokeUp]}),jsx(View,{style:[e.shareStroke,e.shareStrokeDown]})]})}i(gl,"ShareGlyph");function bl(){let e=dn();return jsxs(View,{style:e.sendGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.sendBody}),jsx(View,{style:e.sendFold})]})}i(bl,"SendGlyph");function hl(){let e=dn();return jsxs(View,{style:e.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.downloadStem}),jsx(View,{style:e.downloadHead}),jsx(View,{style:e.downloadTray})]})}i(hl,"DownloadGlyph");function dn(){let e=L();return useMemo(()=>em(e),[e])}i(dn,"useStyles");function em(e){let{color:t,space:r,type:o}=e,n=r.xxl+r.md,l=r.md,s=r.xs/2,c=r.lg+r.xs+r.xs/2;return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md,gap:r.sm},back:{width:n,height:n,alignItems:"center",justifyContent:"center"},chevron:{width:l,height:l,borderLeftWidth:s,borderBottomWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginLeft:r.xs},title:{flex:1,..._(e,"bold"),fontSize:o.size.heading,lineHeight:Math.round(o.size.heading*o.lineHeight.tight)+1,color:t.brandInk},documentTitle:{flex:1,textAlign:"center",..._(e,"bold"),fontSize:o.size.subtitle,lineHeight:Math.round(o.size.subtitle*o.lineHeight.snug),color:t.text.primary},right:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2},listGlyph:{width:c,height:c,justifyContent:"space-evenly"},listBar:{height:s,borderRadius:s,backgroundColor:t.brandInk},shareGlyph:{width:c-r.xs,height:c-r.xs},shareDot:{position:"absolute",width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs,borderWidth:s,borderColor:t.brandInk},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:r.xs+r.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:r.xs,top:r.sm,width:r.sm+r.xs/2,height:s,backgroundColor:t.brandInk},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:c-r.xs,height:c-r.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],borderRadius:s},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:s,backgroundColor:t.brandInk},downloadGlyph:{width:c-r.xs,height:c-r.xs,alignItems:"center"},downloadStem:{width:s,height:r.sm+r.xs/2,backgroundColor:t.brandInk},downloadHead:{width:r.sm,height:r.sm,borderRightWidth:s,borderBottomWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginTop:-r.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:r.xs+r.xs/2,borderLeftWidth:s,borderRightWidth:s,borderBottomWidth:s,borderColor:t.brandInk}})}i(em,"makeStyles");var nm=120,om=44;function im({reason:e,onExit:t,exitLabel:r,style:o}){let{color:n,space:l,radius:s,type:c}=L();return jsxs(View,{testID:"records-gate-off",style:[{minHeight:nm,justifyContent:"center",gap:l.md,padding:l.lg,borderRadius:s.md,borderWidth:1,borderColor:n.brandBorder,backgroundColor:n.surfaceCream},o],children:[e.length>0?jsx(m,{style:{fontSize:c.size.bodyTight,color:n.text.muted},children:e}):null,jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:r,testID:"records-gate-off-exit",style:{minHeight:om,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:l.lg,borderRadius:s.pill,borderWidth:1.5,borderColor:n.brand},children:jsx(m,{style:{fontSize:c.size.body,color:n.brand},children:r})})]})}i(im,"RecordsGateOffState");function Be(e,t){return e===void 0?{}:{renderDisabled:i(r=>jsx(im,{reason:r.disabled?.reason??"",onExit:e,exitLabel:t}),"renderDisabled")}}i(Be,"recordsGateExit");var sm="your pet";function He(e){let t=e?.trim()??"";return t.length>0?t:sm}i(He,"petNameOr");var dt=Object.freeze({title:"Health records",openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${He(e)}\u2019s lab trends`,"lead"),retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:i(e=>`Important: ${e}`,"important")}),Mt=Object.freeze({title:"Marker Summary",marker:"Marker",markers:"Markers",outOfRange:"OUT OF RANGE",inRange:"IN RANGE",noRange:"NO RANGE",subtitle:"Summary of your pet\u2019s biomarkers",ask:"Ask about these markers",askA11y:"Ask Everfur about these markers",a11y:i((e,t,r,o)=>`Marker summary: ${e} ${e===1?"marker":"markers"}, ${t} in range, ${r} out of range${o>0?`, ${o} without a range`:""}.`,"a11y")}),wi=Object.freeze({counter:i((e,t)=>`${e+1} of ${t}`,"counter"),a11y:i((e,t,r)=>e!==null?`${e}, marker ${t+1} of ${r}. Swipe left or right to see more markers.`:`Marker ${t+1} of ${r}`,"a11y")}),or=Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we\u2019ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y"),status:i(e=>`Status: ${e}`,"status"),latestA11y:i((e,t,r)=>`Latest reading ${e}, ${t}, collected ${r}`,"latestA11y"),readingsA11y:i(e=>`${e} readings, oldest to newest`,"readingsA11y")}),Ct=Object.freeze({title:"Where this reading came from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn\u2019t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading",askA11y:"Ask Everfur about this reading"}),Mr=Object.freeze({title:i(e=>`${He(e)}\u2019s records request`,"title"),body:i(e=>`We\u2019re requesting ${He(e)}\u2019s records from your vet. This usually takes a few days; we\u2019ll show lab trends here as soon as they arrive.`,"body"),a11y:i(e=>`Records request in progress for ${He(e)}.`,"a11y"),openA11y:i((e,t)=>`Open ${He(e)}\u2019s records request. ${t}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),_r=Object.freeze({title:i(e=>`Add ${He(e)}\u2019s records`,"title"),body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicA11y:i(e=>`Request ${He(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${He(e)}\u2019s records`,"uploadDocumentA11y")});var to="rgba(0,0,0,0.4)";function be(){let e=L();return useMemo(()=>um(e),[e])}i(be,"useScreenStyles");function hr({disclaimer:e,style:t}){let r=be();return e.trim().length===0?null:jsxs(View,{style:[r.band,t],accessible:true,accessibilityRole:"text",accessibilityLabel:dt.important(e),testID:"records-disclaimer-band",children:[jsx(View,{style:r.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:r.infoGlyphText,children:"i"})}),jsx(m,{style:r.bandText,children:e})]})}i(hr,"DisclaimerBand");function re({label:e,onPress:t,kind:r="primary",disabled:o=false,busy:n=false,accessibilityLabel:l,testID:s,style:c}){let a=be(),d=L(),u=r==="primary"?a.pillPrimary:r==="outline"?a.pillOutline:r==="danger"?a.pillDanger:r==="ask"?a.pillAsk:a.pillLink,p=r==="primary"?a.pillPrimaryLabel:r==="danger"?a.pillDangerLabel:r==="ask"?a.pillAskLabel:r==="link"?a.pillLinkLabel:a.pillOutlineLabel;return jsxs(Pressable,{onPress:t,disabled:o||n,accessibilityRole:"button",accessibilityLabel:l??e,accessibilityState:{disabled:o||n,busy:n},style:[a.pill,u,o?a.pillDisabled:null,c],testID:s,children:[n?jsx(ActivityIndicator,{size:"small",color:r==="primary"?d.color.onPrimary:d.color.brandInk}):null,jsx(m,{style:p,children:e})]})}i(re,"Pill");function Kt({label:e,tone:t="neutral",testID:r}){let o=be(),{bg:n,fg:l}=o.chipTones[t];return jsx(View,{style:[o.chip,n],testID:r,children:jsx(m,{style:[o.chipText,l],children:e})})}i(Kt,"Chip");function Bt({title:e,count:t}){let r=be();return jsxs(View,{style:r.sectionHeader,children:[jsx(m,{style:r.sectionTitle,accessibilityRole:"header",children:e}),t!==void 0?jsx(m,{style:r.sectionCount,children:t}):null]})}i(Bt,"SectionHeader");function Pr({direction:e="right"}){let t=be(),r=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsx(View,{style:[t.chevron,{transform:[{rotate:r}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(Pr,"Chevron");function um(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((v,y)=>Math.round(v*y),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl+r.md,p=i((v,y,g,b="regular")=>({..._(e,b),fontSize:v,lineHeight:a(v,y),color:g}),"text"),f=ot(l.recordCard),h=e.brightness==="dark"?t.errorRed:t.danger,R=i((v,y)=>({bg:{backgroundColor:v},fg:{color:y}}),"tone");return {chipTones:{neutral:R(t.badgeBgNeutral,t.text.secondary),info:R(t.brandSoft,t.brandInk),warning:R(t.badgeBgCaution,t.warningStrong),critical:R(t.badgeBgCritical,t.danger),positive:R(t.badgeBgPositive,t.success)},...StyleSheet.create({root:{flex:1,backgroundColor:t.background},body:{flex:1},content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg},contentTight:{paddingHorizontal:r.sm,paddingBottom:r.xxl,gap:r.lg},inset:{paddingHorizontal:r.sm},section:{gap:r.sm+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.xs},sectionTitle:{...p(s.body+1,c.snug,t.text.primary,"bold")},sectionCount:{...p(s.bodyTight,c.snug,t.text.muted,"medium")},card:{borderRadius:o.lg-r.xs,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.xs,...Je(l.recordCard,d)},creamCard:{borderRadius:o.lg-r.xs/2,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md,...Je(l.recordCard,d)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,paddingVertical:r.md},rowDivider:{borderTopWidth:d,borderTopColor:t.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:r.xs+r.xs/2},rowTitle:{...p(s.body,c.snug,t.text.primary,"medium"),...f},rowDetail:{...p(s.caption,c.normal,t.text.secondary),marginTop:r.xs/2,...f},rowValue:{...p(s.body+1,c.snug,t.text.primary,"bold"),marginTop:r.xs/2,...f},rowMuted:{...p(s.caption,c.normal,t.text.muted),...f},chip:{borderRadius:o.pill,paddingHorizontal:r.sm,paddingVertical:r.xs-1,alignSelf:"flex-start"},chipText:{...p(s.tiny,c.snug,t.text.primary,"medium")},pill:{minHeight:u,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm},pillPrimary:{backgroundColor:t.brand,...Je(l.primaryButton)},pillPrimaryLabel:{...p(s.body,c.snug,t.onPrimary,"bold"),...ot(l.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:t.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...p(s.body,c.snug,t.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:t.danger,backgroundColor:t.surface},pillDangerLabel:{...p(s.bodyTight,c.snug,t.danger,"bold")},pillAsk:{borderWidth:d,borderColor:t.borderRingCream,backgroundColor:t.surface},pillAskLabel:{...p(s.body,c.snug,t.text.primary,"bold")},pillLink:{backgroundColor:"transparent",paddingHorizontal:r.sm},pillLinkLabel:{...p(s.body,c.snug,t.linkInk,"bold")},pillDisabled:{opacity:.5},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},infoNoteText:{flex:1,...p(s.bodyTight,c.normal,t.text.primary)},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCaution,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},cautionNoteText:{flex:1,...p(s.bodyTight,c.normal,t.warningStrong)},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2},statusText:p(s.bodyTight,c.relaxed,t.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCritical,padding:r.md},errorText:{flex:1,...p(s.bodyTight,c.normal,h)},band:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft},bandText:{flex:1,...p(s.caption,c.normal,t.text.secondary)},infoGlyph:{width:r.md+r.xs/2,height:r.md+r.xs/2,borderRadius:o.pill,borderWidth:1,borderColor:t.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...p(s.small,c.tight,t.text.secondary,"bold")},chevron:{width:r.sm,height:r.sm,borderTopWidth:r.xs/2,borderRightWidth:r.xs/2,borderColor:t.text.muted},lead:{paddingHorizontal:r.sm,...p(s.body+1,c.snug,t.text.primary,"bold")},field:{minHeight:u,paddingHorizontal:r.md,paddingVertical:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,..._(e,"regular"),fontSize:s.body},fieldLabel:{...p(s.bodyTight,c.normal,t.text.secondary,"medium")},muted:p(s.caption,c.normal,t.text.muted),bodyText:p(s.body,c.normal,t.text.primary)})}}i(um,"makeScreenStyles");function Br(e,t){return e===null?"":t?`${e} ${t}`:e}i(Br,"formatEntityValue");var vl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Q(e){if(!e)return "-";let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(t!==null){let n=vl[Number(t[2])-1];return n===void 0?"-":`${n} ${Number(t[3])}, ${t[1]}`}let r=Date.parse(e);if(Number.isNaN(r))return "-";let o=new Date(r);return `${vl[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(Q,"formatRecordsDate");var fe=Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:i(e=>`Measured ${e}`,"measured"),uploadedDocument:"Uploaded document",kind:Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:i(e=>`Dr. ${e}`,"doctor"),lot:i(e=>`Lot ${e}`,"lot"),expires:i(e=>`Expires ${e}`,"expires")});function Qt(e){switch(e){case "above":return {label:"Above range",outOfRange:true};case "below":return {label:"Below range",outOfRange:true};case "in_range":return {label:"In range",outOfRange:false};default:return {label:"No range on file",outOfRange:false}}}i(Qt,"markerStatusLabel");function Hr(e,t){return t<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${t} visits`}i(Hr,"trajectoryLabel");function ir(e){let t=e.replace(/_/g," ").trim();return t.length===0?e:t.charAt(0).toUpperCase()+t.slice(1)}i(ir,"humanize");var xl=Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function Ir(e){return Object.prototype.hasOwnProperty.call(xl,e)?xl[e]:ir(e)}i(Ir,"bodySystemLabel");var wl=Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function Ur(e){return Object.prototype.hasOwnProperty.call(wl,e)?wl[e]:ir(e)}i(Ur,"soapSectionLabel");function Cl(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(Cl,"formatWeightKg");function Et(e,t,r){if((e===null||!Number.isFinite(e))&&r)return r;if(e===null||!Number.isFinite(e))return "-";let o=e.toFixed(3).replace(/\.?0+$/,"");return t?`${o} ${t}`:o}i(Et,"formatMarkerReading");function Ei(e,t,r){let o=Hr(t,r);return e?`${fe.measured(Q(e))}${o?` \xB7 ${o}`:""}`:o}i(Ei,"labDetailLine");var de=Object.freeze({openA11y:"Share medical record",title:"Share medical record",helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",createLink:"Create link and share",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn\u2019t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",copyLinkA11y:i(e=>`Copy share link, ${e}`,"copyLinkA11y"),turnOff:"Turn off",turnOffA11y:i(e=>`Turn off share link, ${e}`,"turnOffA11y"),turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",copied:"Link copied.",copyFailed:"Could not copy the link.",turnedOff:"Link turned off."})});function pm(e,t){if(!e)return false;let r=Date.parse(e);return Number.isNaN(r)?false:r<=t}i(pm,"isShareExpired");function mm(e,t){let r=Q(e);return r==="-"?t?"Expired":"No expiry date":t?`Expired ${r}`:`Expires ${r}`}i(mm,"formatShareExpiry");function El(e,t,r){let o=e.map(n=>{let l=pm(n.expiresAt,r),s=mm(n.expiresAt,l),c=Q(n.createdAt),a=l?"Expired":"Active",d=s.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return {shareId:n.shareId,shareUrl:t[n.shareId]??null,active:!l,statusLabel:a,expiryLabel:s,createdLabel:c==="-"?null:`Created ${c}`,a11yLabel:`Share link. ${a}. ${s}.`,actionContext:d}});return Object.freeze([...o.filter(n=>n.active),...o.filter(n=>!n.active)])}i(El,"buildShareRows");function ro(e,t){let r=e?.httpStatus;if(tr(e)){if(t==="create")return "Records access for this pet is off, so a new link cannot be created.";if(t==="download")return "Records access for this pet is off, so the PDF cannot be downloaded."}if(r===429)return "You are creating links a little too fast. Wait a moment, then try again.";if(t==="revoke"&&(r===404||r===409||r===410))return "That link was already turned off.";if(r===401||r===403)return "You need to be signed in as this pet's owner to do that.";switch(t){case "create":return "Could not create a share link. Please try again.";case "revoke":return "Could not turn off that link. Please try again.";default:return "Could not download the record PDF. Please try again."}}i(ro,"shareErrorMessage");function ve({width:e,height:t,radius:r,style:o}){let{color:n,radius:l}=L();return jsx(View,{style:[{width:e,height:t,borderRadius:r??l.xs,backgroundColor:n.skeleton},o],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(ve,"SkeletonBlock");var Si=180,kl=70,no=22,fm=300,Tl=44,oo=24,ki=34,gm=6,bm=5;function io({testID:e}){let t=mn(),r=i(o=>jsxs(View,{style:t.actionRow,children:[jsxs(View,{style:t.actionLeft,children:[jsx(ve,{width:18,height:18,radius:9}),jsx(ve,{width:"55%",height:14,radius:7})]}),jsx(ve,{width:18,height:18,radius:9})]},o),"action");return jsxs(View,{style:t.dashboard,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:dt.loading,testID:e,children:[jsx(View,{style:t.inset,children:jsxs(View,{style:t.summaryCard,children:[jsx(ve,{width:Si,height:Si,radius:Si/2}),jsxs(View,{style:t.badges,children:[jsx(ve,{width:kl,height:no,radius:no/2}),jsx(ve,{width:kl,height:no,radius:no/2})]})]})}),jsx(ve,{width:150,height:16,radius:8,style:t.inset}),jsx(View,{style:t.carouselCard,children:jsx(ve,{width:"100%",height:fm,radius:14})}),jsxs(View,{style:t.dots,children:[jsx(ve,{width:6,height:6,radius:3}),jsx(ve,{width:18,height:6,radius:3}),jsx(ve,{width:6,height:6,radius:3})]}),jsx(ve,{width:46,height:12,radius:6,style:t.centered}),jsx(View,{style:t.inset,children:jsx(ve,{width:"100%",height:Tl,radius:12})}),jsxs(View,{style:[t.inset,t.actions],children:[r("a"),r("b")]})]})}i(io,"DashboardSkeleton");function _l({testID:e}){let t=mn();return jsxs(View,{style:t.request,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ge.loading,testID:e,children:[jsx(View,{children:[0,1,2,3].map(r=>jsxs(View,{style:t.railRow,children:[jsxs(View,{style:t.railColumn,children:[jsx(ve,{width:oo,height:oo,radius:oo/2}),r<3?jsx(ve,{width:2,height:20,radius:1,style:t.connector}):null]}),jsxs(View,{style:t.railBody,children:[jsx(ve,{width:"55%",height:14,radius:7}),jsx(ve,{width:"75%",height:11,radius:6})]})]},r))}),jsxs(View,{style:t.statusCard,children:[jsx(ve,{width:"90%",height:13,radius:6}),jsx(ve,{width:"60%",height:13,radius:6})]}),jsx(ve,{width:"100%",height:50,radius:25})]})}i(_l,"RequestSkeleton");function Pl({testID:e}){let t=mn();return jsxs(View,{style:t.timeline,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:fe.loadingTimeline,testID:e,children:[jsx(View,{style:t.timelineDisclaimer,children:jsx(ve,{width:"100%",height:Tl,radius:12})}),Array.from({length:gm},(r,o)=>jsxs(View,{children:[o>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,children:[jsx(ve,{width:ki,height:ki,radius:ki/2}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.timelineTop,children:[jsx(ve,{width:44,height:10,radius:5}),jsx(ve,{width:56,height:12,radius:6})]}),jsx(ve,{width:"70%",height:14,radius:7}),o%2===0?jsx(ve,{width:"45%",height:12,radius:6}):null]})]})]},o))]})}i(Pl,"TimelineSkeleton");function Il({testID:e}){let t=mn();return jsx(View,{style:t.clinics,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:xe.loading,testID:e,children:Array.from({length:bm},(r,o)=>jsxs(View,{style:t.clinicRow,children:[jsx(ve,{width:"65%",height:14,radius:7}),jsx(ve,{width:"40%",height:11,radius:6})]},o))})}i(Il,"ClinicsSkeleton");function Dl({testID:e}){let t=mn();return jsx(View,{style:t.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:de.loadingLinks,testID:e,children:[0,1].map(r=>jsxs(View,{style:t.shareRow,children:[jsx(ve,{width:"55%",height:13}),jsx(ve,{width:"40%",height:11})]},r))})}i(Dl,"SharesSkeleton");var Ti=62;function mn(){let e=L();return useMemo(()=>hm(e),[e])}i(mn,"useStyles");function hm(e){let{color:t,space:r,radius:o}=e,n=StyleSheet.hairlineWidth;return StyleSheet.create({dashboard:{flex:1,paddingHorizontal:r.sm,paddingTop:r.xs,gap:r.lg,backgroundColor:t.background},inset:{paddingHorizontal:r.sm},summaryCard:{alignItems:"center",borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg+r.xs,gap:r.md+r.xs/2},badges:{flexDirection:"row",gap:r.md},carouselCard:{borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg},dots:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.xs+r.xs/2},centered:{alignSelf:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},request:{paddingHorizontal:r.lg,paddingTop:r.xs,gap:r.lg+r.xs/2,backgroundColor:t.background},railRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md},railColumn:{alignItems:"center",width:oo},connector:{marginVertical:r.xs/2},railBody:{flex:1,paddingBottom:r.lg+r.xs/2,gap:r.xs+r.xs/2},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2,gap:r.sm},timeline:{flex:1,backgroundColor:t.background},timelineDisclaimer:{paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBody:{flex:1,gap:r.xs-1},timelineTop:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},timelineSeparator:{height:n,backgroundColor:t.brandBorder,marginLeft:Ti},clinics:{gap:r.md},clinicRow:{borderRadius:o.lg-r.xs/2,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2,gap:r.sm},shares:{gap:r.md,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:n,borderColor:t.brandBorder},shareRow:{gap:r.xs+r.xs/2}})}i(hm,"makeStyles");var Em=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function _i(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",style:e.style,...Be(e.onBack,Ze),children:t===null?jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsx(Sm,{...Fe(e,["onNavigate","onBack"])},JSON.stringify([t,r,e.petRef]))})}i(_i,"EverfurClinicPicker");function Sm({petRef:e,controller:t,recordsController:r,location:o,onNavigate:n,onBack:l,style:s}){let c=be(),a=Tm(),d=L(),u=Nt(),p=Hs(t??u,o),f=yt(r?{petRef:e,controller:r}:{petRef:e}),h=useRef(rr()),[R,v]=useState(false),[y,g]=useState(null),[b,w]=useState(false),[x,E]=useState(""),[D,k]=useState(false),[S,I]=useState(""),[Y,z]=useState(false),$=useCallback(A=>{n?.({name:"consent",clinic:pi(A,null,"",h.current())});},[n]),G=i(()=>{R||(v(true),g(null),f.createRequest(`records-upload-${Date.now().toString(36)}`).then(A=>{if(v(false),!A.ok){g(ge.errors.start);return}n?.({name:"request",requestId:A.value.id});}));},"startUpload"),Z=D?x:p.query,oe=Em.test(S.trim()),Ee=Z.trim().length>0&&oe,H=i(A=>{let{layoutMeasurement:M,contentOffset:K,contentSize:ye}=A.nativeEvent;M.height+K.y>=ye.height-M.height*.6&&p.loadMore();},"onEndReached"),C=p.isSearchActive?p.clinics:p.recent,T=p.isSearchActive?p.error?wt(p.error):!p.initialLoading&&p.clinics.length===0?"idle":null:p.recent.length>0||p.recentLoading?null:"idle";return jsxs(View,{style:[c.root,s],children:[jsx(et,{title:xe.title,onBack:l,testID:"records-clinic-header"}),jsxs(View,{style:a.searchBar,children:[jsx(View,{style:a.searchGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(qe,{value:p.query,onChangeText:p.setQuery,placeholder:xe.placeholder,placeholderTextColor:d.color.text.muted,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",maxLength:200,accessibilityLabel:xe.searchA11y,style:a.searchInput,testID:"records-clinic-search-input"}),p.query.length>0?jsx(Pressable,{onPress:()=>p.setQuery(""),accessibilityRole:"button",accessibilityLabel:xe.clearSearch,hitSlop:8,testID:"records-clinic-search-clear",children:jsx(m,{style:a.clearGlyph,children:"\xD7"})}):null]}),n?jsxs(View,{style:a.uploadWrap,children:[y?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:y})}):null,jsx(re,{label:R?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",accessibilityLabel:xe.uploadOwnA11y,busy:R,onPress:G,testID:"records-clinic-upload-own"})]}):null,jsxs(ScrollView,{contentContainerStyle:a.list,keyboardShouldPersistTaps:"handled",onScroll:p.isSearchActive?H:void 0,scrollEventThrottle:200,testID:"records-clinic-results",children:[p.isSearchActive?jsxs(View,{style:a.fallbackCard,testID:"records-clinic-fallback-card",children:[jsxs(Pressable,{onPress:()=>w(A=>!A),accessibilityRole:"button",accessibilityLabel:b?xe.fallback.collapseA11y:xe.fallback.expandA11y,style:a.fallbackHeader,testID:"records-clinic-fallback",children:[jsxs(View,{style:a.fallbackCopy,children:[jsx(m,{style:a.fallbackTitle,numberOfLines:1,children:xe.fallback.title}),jsx(m,{style:a.fallbackSubtitle,numberOfLines:2,children:xe.fallback.subtitle})]}),jsx(Pr,{direction:b?"up":"down"})]}),b?jsxs(View,{style:a.fallbackForm,children:[jsx(m,{style:c.fieldLabel,children:xe.fallback.nameLabel}),jsx(qe,{accessibilityLabel:xe.fallback.nameLabel,style:c.field,value:Z,onChangeText:A=>{E(A),k(true);},placeholder:xe.fallback.namePlaceholder,placeholderTextColor:d.color.text.placeholder,autoCapitalize:"words",autoCorrect:false,maxLength:200,testID:"records-clinic-fallback-name"}),jsx(m,{style:c.fieldLabel,children:xe.fallback.emailLabel}),jsx(qe,{accessibilityLabel:xe.fallback.emailLabel,style:c.field,value:S,onChangeText:A=>{I(A),z(false);},onBlur:()=>z(true),placeholder:xe.fallback.emailPlaceholder,placeholderTextColor:d.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,testID:"records-clinic-fallback-email"}),Y&&S.trim().length>0&&!oe?jsx(m,{style:c.errorText,accessibilityRole:"alert",children:ge.errors.invalidEmail}):null,jsx(m,{style:c.muted,children:xe.fallback.reviewNote}),jsx(re,{label:xe.fallback.submit,accessibilityLabel:xe.fallback.submitA11y,disabled:!Ee||!n,onPress:()=>n?.({name:"consent",clinic:pi(null,Z.trim(),S.trim().toLowerCase(),h.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):p.recent.length>0?jsx(m,{style:a.sectionLabel,accessibilityRole:"header",testID:"records-clinic-recent-label",children:xe.recentlyUsed}):null,p.isSearchActive&&p.initialLoading?jsx(Il,{testID:"records-clinic-page-loading"}):null,C.map(A=>jsx(km,{clinic:A,onSelect:$,styles:a},A.id)),T&&!p.initialLoading?jsx(Qe,{variant:T,message:p.isSearchActive&&T==="idle"?xe.noMatch(p.debouncedQuery):p.error?.displayMessage,onAction:p.error?.retryable===true?p.retry:void 0,testID:"records-clinic-empty"}):null,jsxs(View,{style:a.footer,children:[p.loadingMore?jsxs(View,{style:a.footerLoading,testID:"records-clinic-loading-more",children:[jsx(ActivityIndicator,{color:d.color.brandInk,size:"small"}),jsx(m,{style:c.muted,children:xe.loadingMore})]}):null,p.pageError?jsx(Pressable,{onPress:p.loadMore,accessibilityRole:"button",accessibilityLabel:xe.loadMoreRetryA11y,style:a.footerRetry,testID:"records-clinic-page-error-retry",children:jsx(m,{style:a.footerRetryLabel,children:xe.loadMoreFailed})}):null]})]}),jsx(Me,{})]})}i(Sm,"PickerBody");function km({clinic:e,onSelect:t,styles:r}){let o=As(e.emailStatus),n=Os(e.distanceKm),l=[e.name,e.address,e.phone?`phone ${e.phone}`:null,n?Ls(e.distanceKm):null,o.a11y].filter(Boolean).join(", ");return jsxs(Pressable,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:xe.selectA11y(l),hitSlop:8,style:r.item,testID:`records-clinic-${e.id}`,children:[jsxs(View,{style:r.itemHeader,children:[jsx(m,{style:r.itemName,numberOfLines:1,children:e.name}),n?jsx(m,{style:r.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:n}):null]}),e.address?jsx(m,{style:r.itemAddress,numberOfLines:2,children:e.address}):null,e.phone?jsx(m,{style:r.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:e.phone}):null,jsx(View,{style:[r.badge,o.tone==="positive"?r.badgePositive:o.tone==="caution"?r.badgeCaution:r.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:[r.badgeLabel,o.tone==="positive"?r.badgePositiveText:o.tone==="caution"?r.badgeCautionText:r.badgeNeutralText],children:o.label})})]})}i(km,"ClinicRow");function Tm(){let e=L();return useMemo(()=>_m(e),[e])}i(Tm,"useLocalStyles");function _m(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=i((c,a,d,u="regular")=>({..._(e,u),fontSize:c,lineHeight:Math.round(c*a),color:d}),"text");return StyleSheet.create({searchBar:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.md+r.xs/2,height:r.xxl+r.md,marginHorizontal:r.lg,marginBottom:r.sm,borderRadius:o.lg+r.xs/2,backgroundColor:t.surfaceSubtle,borderWidth:l,borderColor:t.borderHairlineGreen},searchGlyph:{width:r.md,height:r.md,borderRadius:o.pill,borderWidth:2,borderColor:t.text.muted},searchInput:{flex:1,...s(n.size.body,n.lineHeight.snug,t.text.primary),paddingVertical:0},clearGlyph:s(n.size.heading,n.lineHeight.tight,t.text.muted),uploadWrap:{paddingHorizontal:r.lg,paddingBottom:r.md,gap:r.sm},list:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.md},sectionLabel:{...s(n.size.caption,n.lineHeight.normal,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:o.lg-r.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.md},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:r.md,minHeight:r.xxl+r.md},fallbackCopy:{flex:1,gap:r.xs/2},fallbackTitle:{...s(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},fallbackSubtitle:s(n.size.caption,n.lineHeight.normal,t.text.muted),fallbackForm:{gap:r.sm},item:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},itemName:{flex:1,...s(n.size.body,n.lineHeight.snug,t.brandInk,"bold")},itemDistance:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},itemAddress:s(n.size.caption,n.lineHeight.normal,t.text.primary),itemPhone:s(n.size.caption,n.lineHeight.normal,t.text.muted),badge:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+1,paddingVertical:r.xs},badgePositive:{backgroundColor:t.badgeBgPositive},badgeCaution:{backgroundColor:t.badgeBgCaution},badgeNeutral:{backgroundColor:t.badgeBgNeutral},badgeLabel:{...s(n.size.micro,n.lineHeight.snug,t.text.muted,"bold")},badgePositiveText:{color:t.success},badgeCautionText:{color:t.cautionAccent},badgeNeutralText:{color:t.text.muted},footer:{gap:r.sm,paddingTop:r.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.md},footerRetry:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...s(n.size.bodyTight,n.lineHeight.snug,t.brandInk,"bold")}})}i(_m,"makeLocalStyles");var Oe=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${Nr} clinics`,sendA11y:i(e=>e===1?"Send 1 records request":`Send ${e} records requests`,"sendA11y"),send:i(e=>`Send ${e} ${e===1?"request":"requests"}`,"send"),sending:"Sending\u2026",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:i(e=>`Remove ${e}`,"remove"),emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn\u2019t send any of these requests. See the details below and try again.",partial:i((e,t,r)=>`${e} of ${t} requests sent. ${r} couldn\u2019t be sent.`,"partial"),allSent:i(e=>`${e} ${e===1?"request":"requests"} sent.`,"allSent"),responded:i((e,t)=>`${e} of ${t} ${t===1?"clinic":"clinics"} responded`,"responded")});function yn(e,t,r,o){let n={owner_name:t,pet_name:r,clinic_name:o},l=false,s=e.scopeTemplate.replace(/\{([^{}]+)\}/g,(c,a)=>Object.prototype.hasOwnProperty.call(n,a)?n[a]??"":(l=true,""));return l||/[{}]/.test(s)?null:s}i(yn,"renderClinicScope");function fn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(fn,"clinicNeedsEmail");function Ol(e,t,r){let[o,n]=useState(e.ownerName),[l,s]=useState(""),[c,a]=useState(null),[d,u]=useState(""),[p,f]=useState([]),[h,R]=useState([]),[v,y]=useState(null),[g,b]=useState(null),[w,x]=useState(false),[E,D]=useState(false),[k,S]=useState(null),[I,Y]=useState(0),z=useRef(false),$=useRef(false),G=useRef(0),Z=useRef(rr()),oe=useRef(null),Ee=useRef(null),H=useRef(0);useEffect(()=>(z.current=true,$.current=false,x(false),()=>{z.current=false,H.current+=1,G.current+=1,oe.current=null,Ee.current?.abort();}),[t]),useEffect(()=>{let ie=true;return y(null),oe.current=null,t.getAuthorizationCopy().then(we=>{ie&&(we.ok?(y(we.value),b(null)):b(we.error));}).catch(()=>{ie&&b(q("internalError"));}),()=>{ie=false;}},[t,I]),useEffect(()=>{let ie=true;return R([]),t.recentClinics({limit:5}).then(we=>{ie&&we.ok&&R(we.value.clinics);}).catch(()=>{}),()=>{ie=false;}},[t]);let C=i(()=>{oe.current=null,b(null);},"invalidate"),T=c?.name??l.trim(),A=v?yn(v,o.trim(),e.petName,T):null,M=fn(c),K=!!(v&&A&&o.trim()&&e.petName.trim()&&T&&(!M||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.trim()))&&r),ye=i(async()=>{if($.current)return;let ie=++G.current;D(true);try{let we=await t.searchClinics({query:l.trim(),limit:100});if(!z.current||ie!==G.current)return;we.ok?(f(we.value.clinics),b(null)):b(we.error);}catch{z.current&&ie===G.current&&b(q("internalError"));}finally{z.current&&ie===G.current&&D(false);}},"search"),Ve=i(async()=>{if($.current||k||!K||!v||!A||!r)return;$.current=true;let ie=H.current,we=i(()=>z.current&&H.current===ie,"current");x(true),b(null);try{if(!oe.current){Ee.current=new AbortController;let Xe=await r({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:T,authorizationVersion:v.authorizationVersion,scopeText:A,signal:Ee.current.signal});if(!we()||Xe===null)return;let Vt=c&&(!M||c.emailStatus==="none")?{clinicId:c.id}:{clinicFreeText:T};oe.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:v.authorizationVersion,...Vt,...M?{clinicEmail:d.trim().toLowerCase()}:{},...Xe.signatureId!==void 0?{signatureId:Xe.signatureId}:{signaturePngBase64:Xe.signaturePngBase64},idempotencyKey:Z.current()};}if(!we())return;let vt=await t.createClinicRequest(oe.current);if(!we())return;if(!vt.ok){b(vt.error);return}if(vt.value.petRef!==e.petRef){b(q("internalError"));return}S(vt.value),oe.current=null,e.onCreated?.(vt.value);}catch{we()&&b(q("internalError"));}finally{$.current=false,we()&&x(false);}},"submit");return {ownerName:o,query:l,clinic:c,email:d,clinics:p,copy:v,scope:A,error:g,busy:w,searching:E,created:k,ready:K,needsEmail:M,recent:p.length===0&&c===null?h:[],setOwnerName(ie){$.current||(C(),n(ie));},setQuery(ie){$.current||(C(),G.current+=1,D(false),f([]),a(null),u(""),s(ie));},setEmail(ie){$.current||(C(),u(ie));},selectClinic(ie){$.current||(C(),G.current+=1,D(false),f([]),a(ie),s(ie.name),u(""));},invalidate:C,search:ye,submit:Ve,retryCopy(){b(null),Y(ie=>ie+1);}}}i(Ol,"useClinicRequestForm");var Pm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function bn(e){return e.clinic?.name??e.freeText??""}i(bn,"draftName");function gn(e){return fn(e.clinic)}i(gn,"draftNeedsEmail");function Ll(e,t,r,o,n){let[l,s]=useState(e.ownerName),[c,a]=useState(""),[d,u]=useState([]),[p,f]=useState([]),[h,R]=useState([]),[v,y]=useState(null),[g,b]=useState(null),[w,x]=useState(false),[E,D]=useState(false),[k,S]=useState(null),[I,Y]=useState(null),[z,$]=useState(0),G=useRef(false),Z=useRef(false),oe=useRef(0),Ee=useRef(0),H=useRef(rr()),C=useRef(null),T=useRef(null);useEffect(()=>(G.current=true,Z.current=false,x(false),()=>{G.current=false,Ee.current+=1,oe.current+=1,C.current=null,T.current?.abort();}),[t,r]),useEffect(()=>{let F=true;return y(null),C.current=null,t.getAuthorizationCopy().then(Re=>{F&&(Re.ok?(y(Re.value),b(null)):b(Re.error));}).catch(()=>{F&&b(q("internalError"));}),()=>{F=false;}},[t,z]),useEffect(()=>{let F=true;return f([]),t.recentClinics({limit:5}).then(Re=>{F&&Re.ok&&f(Re.value.clinics);}).catch(()=>{}),()=>{F=false;}},[t]);let A=i(()=>{C.current=null,b(null);},"invalidate"),M=h.map(bn),K=v?M.map(F=>yn(v,l.trim(),e.petName,F)):[],ye=K.every(F=>F!==null)?K.join(`
1
+ import {createContext,forwardRef,useRef,useMemo,useState,useCallback,useEffect,useReducer,createElement,useContext,useSyncExternalStore,Component}from'react';import {z}from'zod';import {TextInput,View,Pressable,ScrollView,ActivityIndicator,StyleSheet,PanResponder,KeyboardAvoidingView,Image,Linking,BackHandler,Text,Modal,AccessibilityInfo}from'react-native';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var Ud=Object.defineProperty;var i=(e,t)=>Ud(e,"name",{value:t,configurable:true});var No=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(No.map(e=>e.wireCode));var jd=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),Ua=Object.freeze(No.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:jd[e.wireCode]}))),$d=new Map(Ua.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Wd=Object.freeze(["http_envelope",...[...new Set(Ua.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Vn(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let o of [t??"http_envelope",...Wd]){let n=$d.get(o+r);if(n)return n}}i(Vn,"contractErrorFor");function Gd(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Gd,"contractDocUrl");function ja(e){return null}i(ja,"publishedDocUrl");var Yd=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function $a(e){return Yd[e]}i($a,"categoryFor");function Wa(e){let t=Vn(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),o=r.replace(/[^A-Z0-9]/g,"");if(o==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(o){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Wa,"fromWire");var Kd=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Mo(e){return Kd.has(e)}i(Mo,"isAutoRetryable");var Qd=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Ga(e){return Mo(e)||Qd.has(e)}i(Ga,"isRetryableCode");var Xd=500,Bo=8e3,Ya=4;function Ka(e,t=Math.random){let r=Math.max(0,e),o=Math.min(Xd*2**r,Bo);return Math.floor(t()*o)}i(Ka,"backoffDelayMs");var Jd=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function Ho(e){return Jd[e]}i(Ho,"userFacingError");function Qa(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(Qa,"defineHidden");var Zd=/^[a-z][a-z0-9_]{0,63}$/;function q(e,t){let r=Vn(t?.wireCode,t?.wireEnvelope),o={code:e,category:$a(e),retryable:t?.retryable??Ga(e),displayMessage:Ho(e)};if(t?.httpStatus!==void 0&&(o.httpStatus=t.httpStatus),t?.requestId&&(o.requestId=t.requestId),typeof t?.reasonCode=="string"&&Zd.test(t.reasonCode)&&(o.reasonCode=t.reasonCode),r);return t?.wireMessage&&Qa(o,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Qa(o,"raw",t.raw),Object.freeze(o)}i(q,"makeEverfurError");function _e(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(_e,"ok");function B(e){return Object.freeze({ok:false,error:e})}i(B,"err");var qn=class qn extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,qn.prototype);}};i(qn,"EverfurConfigError");var rn=qn;var ts=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),Xa=Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function eu(e){let t=Object.prototype.hasOwnProperty.call(Xa,e)?Xa[e]:void 0;if(t!==void 0)return t;let r=e;return ts.has(r)?r:"parsing"}i(eu,"normalizeStatus");function rs(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(rs,"normalizeOrigin");var tu=z.object({request_id:z.string().min(1),pet_ref:z.string().min(1),status:z.string(),simple_status:z.string().nullish(),simple_status_detail:z.string().nullish(),status_label:z.string().optional(),dispatch_status:z.string().nullish(),can_retry_send:z.boolean().optional(),can_revoke:z.boolean().optional(),can_convert_to_upload:z.boolean().optional(),can_update_clinic_email:z.boolean().optional(),reminder_count:z.number().int().nonnegative().optional(),last_reminder_at:z.string().nullish(),waiting_expectation:z.string().nullish(),document_count:z.number().optional(),held_item_count:z.number().optional(),received_at:z.string().nullish(),parsing_started_at:z.string().nullish(),review_started_at:z.string().nullish(),created_at:z.string().optional(),updated_at:z.string().optional(),source:z.string().nullish().catch(null),action_needed_label:z.string().nullish().catch(null),failure_reason:z.string().nullish().catch(null),failure_code:z.string().nullish().catch(null),recovery_stage:z.string().nullish().catch(null),show_clinic_phone:z.boolean().optional().catch(void 0),clinic_name:z.string().nullish().catch(null),clinic_email:z.string().nullish().catch(null),clinic_phone:z.string().nullish().catch(null),converted_to_upload_at:z.string().nullish().catch(null),request_group_id:z.string().nullish().catch(null)}).passthrough();function ur(e){let t=tu.safeParse(e);if(!t.success)return null;let r=t.data,o=nu(r.simple_status),n=o==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":o==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":o??eu(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:n,simpleStatus:o,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:Za(r.document_count,0),heldItemCount:Za(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(ur,"mapRequestView");var ru=z.object({request_group_id:z.string().min(1),pet_ref:z.string().min(1),total:z.number().int().nonnegative(),responded:z.number().int().nonnegative(),pending:z.number().int().nonnegative(),members:z.array(z.unknown())});function ns(e){let t=ru.safeParse(e);if(!t.success)return null;let r=t.data,o=Uo(r.members);return o.some(n=>n.petRef!==r.pet_ref)?null:Object.freeze({requestGroupId:r.request_group_id,petRef:r.pet_ref,total:r.total,responded:r.responded,pending:r.pending,members:o})}i(ns,"mapRequestGroup");function nu(e){return !e||e==="awaiting_upload"||e==="in_review"?null:ts.has(e)?e:null}i(nu,"normalizeSimpleStatus");function Uo(e){let t=Array.isArray(e)?e:[],r=[];for(let o of t){let n=ur(o);n!==null&&r.push(n);}return Object.freeze(r)}i(Uo,"mapRequestList");var ou=z.object({source_doc_id:z.string().min(1),request_id:z.string().min(1)});function os(e){let t=ou.safeParse(e);return t.success?Object.freeze({documentId:t.data.source_doc_id,requestId:t.data.request_id,status:"received"}):null}i(os,"mapUploadedDocument");var iu=z.object({label:z.string(),value:z.string()}),jo=z.object({key:z.string(),category:z.string().optional(),label:z.string().optional(),value:z.string().nullish(),unit:z.string().nullish(),observed_at:z.string().nullish(),status:z.string().nullish(),origin:z.string().nullish(),canonical_key:z.string().nullish()}),au=z.object({at:z.string(),value:z.number().nullish(),display:z.string().nullish(),origin:z.string().nullish()}),su=z.object({key:z.string(),label:z.string().optional(),points:z.array(au).optional()}),lu=z.object({title:z.string(),detail:z.string().nullish(),due_at:z.string().nullish()}),$o=z.object({doc_id:z.string(),title:z.string().nullish(),page_count:z.number().nullish(),received_at:z.string().nullish()});function Wo(e){return Object.freeze({key:e.key,category:e.category??"",label:e.label??e.key,value:e.value??null,unit:e.unit??null,observedAt:e.observed_at??null,status:e.status??null,origin:rs(e.origin),canonicalKey:e.canonical_key??null})}i(Wo,"mapEntityRow");function Go(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(Go,"mapDocumentRow");var cu=z.object({identity:z.array(iu).optional(),entities:z.array(jo).optional(),entity_series:z.array(su).optional(),forward_looking:z.array(lu).optional(),documents:z.array($o).optional()});function is(e,t){let r=uu(t)?t:{},o=es(r.schema_version,"epdf/1.0"),n=es(r.disclaimer,""),l=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Ja(l,o,n);let s=cu.safeParse(r);if(!s.success)return Ja(l,o,n);let c=s.data,a=(c.identity??[]).map(R=>Object.freeze({label:R.label,value:R.value})),d=(c.entities??[]).map(Wo),u=(c.entity_series??[]).map(R=>Object.freeze({key:R.key,label:R.label??R.key,points:Object.freeze((R.points??[]).map(v=>Object.freeze({at:v.at,value:v.value??null,display:v.display??null,origin:rs(v.origin)})))})),p=(c.forward_looking??[]).map(R=>Object.freeze({title:R.title,detail:R.detail??null,dueAt:R.due_at??null})),g={};for(let R of c.documents??[])g[R.doc_id]=Go(R);let h=r.is_empty===true||a.length===0&&d.length===0&&u.length===0&&p.length===0&&Object.keys(g).length===0;return Object.freeze({petRef:l,schemaVersion:o,isEmpty:h,withheld:false,generatedAt:pu(r.generated_at),identity:Object.freeze(a),entities:Object.freeze(d),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(p),documents:Object.freeze(g),disclaimer:n})}i(is,"mapRecordView");function Ja(e,t,r){return Object.freeze({petRef:e,schemaVersion:t,isEmpty:false,withheld:true,generatedAt:null,identity:Object.freeze([]),entities:Object.freeze([]),entitySeries:Object.freeze([]),forwardLooking:Object.freeze([]),documents:Object.freeze({}),disclaimer:r})}i(Ja,"withheldView");var du=z.object({pet_ref:z.string().optional(),granted:z.boolean().optional(),version:z.string().nullish(),granted_at:z.string().nullish()});function zn(e,t){let r=du.safeParse(t),o=r.success?r.data:{};return Object.freeze({petRef:typeof o.pet_ref=="string"&&o.pet_ref.length>0?o.pet_ref:e,granted:o.granted===true,version:o.version??null,grantedAt:o.granted_at??null})}i(zn,"mapConsent");function uu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(uu,"isObject");function Za(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(Za,"numberOr");function es(e,t){return typeof e=="string"&&e.length>0?e:t}i(es,"strOr");function pu(e){return typeof e=="string"&&e.length>0?e:null}i(pu,"strOrNull");var as=Object.freeze(["published","failed","revoked"]);function Mr(e){return as.includes(e)}i(Mr,"isTerminalStatus");function pr(e){if(e===null)return null;let t=e.recordsReason;return t==="consent_required"||t==="session_required"||t==="entitlement"||t==="pet_not_found"?t:null}i(pr,"recordsDenialReasonOf");var mu="records_consent_required";function yu(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,o=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof o=="string"&&o.length>0?o:null}i(yu,"recordsWireCodeOf");function rr(e){return e===null||e.httpStatus!==409?false:yu(e)===mu}i(rr,"isRecordsConsentRequired");var fu=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Fn(e){return e!==fu}i(Fn,"isUploadTransportAvailable");var ss=Object.freeze({record(){}}),mr=25*1024*1024,ls=64,nn=128,mt=128,on="application/pdf",cs=9e4;function us(e){return new Yo(e)}i(us,"createRecordsController");var Ko=class Ko{constructor(t){this.recordCache=new Map;this.consentEpoch=new Map;this.reportedGaps=new Set;this.repository=t.repository,this.uploads=t.uploads,this.telemetry=t.telemetry??ss,this.newIdempotencyKey=t.newIdempotencyKey??vu(),this.timers=t.timers??hu,this.uploadDeadlineMs=t.uploadDeadlineMs??cs;}async createUploadRequest(t){let r=await this.repository.createRequest({pet_ref:t.petRef,idempotency_key:t.idempotencyKey});if(!r.ok)return this.onRequestError(r.error);let o=ur(r.value);return o===null?B(Nn()):(this.observeRequest(o),_e(o))}async getRequest(t){let r=await this.repository.getRequest(t);if(!r.ok)return this.onRequestError(r.error);let o=ur(r.value);return o===null?B(Nn()):(this.observeRequest(o),_e(o))}async listRequests(){let t=await this.repository.listRequests();if(!t.ok)return this.onRequestError(t.error);let r=Uo(t.value);for(let o of r)this.observeRequest(o);return _e(r)}async uploadDocument(t){let{requestId:r,file:o}=t,n=gu(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),B(ds(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(r,{content_type:on,file_size:o.sizeBytes});if(!l.ok)return this.onRequestError(l.error);let s=await this.postToS3(l.value,o,t);if(!s.ok)return this.telemetry.record("records.upload.failed",{reason:s.reason}),B(ds(s.reason));let c=await this.repository.completeUpload(r,{upload_id:l.value.upload_id});if(!c.ok)return c.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:bu(c.error)??"corrupt"}),this.onRequestError(c.error);let a=os(c.value);return a===null?B(Nn()):_e(a)}async postToS3(t,r,o){let n=new AbortController,l=Ru(n.signal,o.signal),s=this.timers.setTimeout(()=>n.abort(),this.uploadDeadlineMs);try{let c={signal:l};return o.onProgress&&(c.onProgress=o.onProgress),await this.uploads.postMultipart(t,r,c),{ok:!0}}catch{return {ok:false,reason:n.signal.aborted&&o.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(s);}}async getRecord(t){let r=this.consentEpoch.get(t)??0,o=await this.repository.getRecord(t);if(r!==(this.consentEpoch.get(t)??0))return B(Object.freeze({...q("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let l=pr(o.error);return l==="consent_required"?(this.recordCache.delete(t),this.telemetry.record("records.consent.denied",{pet_ref:t})):l==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t}),B(o.error)}let n=is(t,o.value);return n.petRef!==t?B(Nn()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:t}),this.recordCache.delete(t),_e(n)):(this.recordCache.set(t,n),_e(n))}peekCachedRecord(t){return this.recordCache.get(t)??null}async getConsent(t){let r=await this.repository.getConsent(t);return r.ok?_e(zn(t,r.value)):B(r.error)}async grantConsent(t){let r=await this.repository.putConsent(t.petRef,{consent_version:t.consentVersion,idempotency_key:t.idempotencyKey});return r.ok?_e(zn(t.petRef,r.value)):(pr(r.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t.petRef}),B(r.error))}async revokeConsent(t){let r=await this.repository.deleteConsent(t);return r.ok?(this.consentEpoch.set(t,(this.consentEpoch.get(t)??0)+1),this.recordCache.delete(t),_e(zn(t,r.value))):B(r.error)}reportCapabilityDenied(t){this.telemetry.record("records.capability.denied",t?{pet_ref:t}:{});}observeRequest(t){t.reviewStartedAt!==null&&!this.reportedGaps.has(t.id)&&(this.reportedGaps.add(t.id),this.telemetry.record("records.parse.gap",{request_id:t.id}));}onRequestError(t){return pr(t)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),B(t)}};i(Ko,"RecordsControllerImpl");var Yo=Ko;function gu(e){if(e.mimeType!==on)return "unsupported_format";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>mr?"oversize":null}i(gu,"validateFile");function bu(e){let t=e.wireMessage;return t==="unsupported_format"||t==="oversize"||t==="corrupt"?t:null}i(bu,"reasonFromWire");function ds(e){return q("mediaUploadFailed",{retryable:false,wireMessage:e})}i(ds,"uploadFailed");function Nn(){return q("internalError",{retryable:true})}i(Nn,"internal");var hu={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function Ru(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let o=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),r.signal}i(Ru,"mergeSignals");function vu(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(vu,"defaultIdempotencyFactory");function yr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(yr,"assertNever");function ps(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(ps,"errorFrame");function Cu(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(Cu,"authHeaders");function an(e,t){return {...e,headers:{...Eu(e.headers),...Cu(t)}}}i(an,"withAuthHeaders");function Eu(e){if(!e)return {};let t={};for(let[r,o]of Object.entries(e)){let n=r.toLowerCase();n==="authorization"||n==="x-everfur-partner-key"||(t[r]=o);}return t}i(Eu,"stripAuthHeaders");async function ms(e,t){if(t.mode==="anonymous")return t.transport.request(an(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return B(Qo())}let o=await t.transport.request(an(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(o.ok||o.error.httpStatus!==401)return o;let n;try{n=await t.identity.currentToken({forceRefresh:!0});}catch{return B(Qo())}let l=await t.transport.request(an(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?B(Qo(l.error.httpStatus)):l}i(ms,"authedSend");function Qo(e){return q("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(Qo,"authRejectedError");function ys(e){return q("internalError",{retryable:true,wireMessage:Su(e)})}i(ys,"networkError");function Su(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Su,"describeCause");var ku=3e4,Tu=Bo*2,_u="idempotency-key",Pu=new Set(["POST","PUT","PATCH","DELETE"]),Iu=Object.freeze({onEvent(){}}),Du=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Au(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(Au,"seededIdempotencyKey");function fr(e){let t=e.observer??Iu,r=e.timers??Du,o=e.rng??Math.random,n=e.sleep??((g,h)=>ju(g,r,h)),l=e.maxAttempts??Ya,s=e.unaryTimeoutMs??ku,c=e.newIdempotencyKey??nr(),a=i(g=>{try{t.onEvent(g);}catch{}},"emit");async function d(g,h,R){let v=R?.maxAttempts,x=Math.max(1,v??l),y=R?.idempotent??Pu.has(h.method),f=R?.idempotencyKey===void 0?null:Au(R.idempotencyKey),E=y?f??c():null,b=Ou(h,E),C=0;for(;;){let D=i(H=>Object.freeze({call:g,method:h.method,path:h.path,attempt:C,...E?{idempotencyKey:E}:{},...H}),"stamp");a(D({phase:"attempt"}));let S=Hu(s,r),k=Uu(S.signal,h.signal),I;try{I=await ms({...b,signal:k.signal},e.auth);}catch(H){I=B(ys(H));}finally{k.dispose(),S.cancel();}if(I.ok)return a(D({phase:"settled",ok:true,reason:"ok"})),I;let G=I.error,z=Vu(G,C,{maxAttempts:x,rng:o,now:r.now(),aborted:h.signal?.aborted===true,...v!==void 0?{perCallMaxAttempts:v}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),Y={ok:false,code:G.code,reason:z.reason,...G.httpStatus!==void 0?{httpStatus:G.httpStatus}:{},...G.requestId!==void 0?{requestId:G.requestId}:{}};if(!z.retry)return a(D({phase:"settled",...Y})),B(G);if(a(D({phase:"retry",...Y,delayMs:z.delayMs})),await n(z.delayMs,h.signal),h.signal?.aborted===true)return a(D({phase:"settled",...Y,reason:"aborted"})),B(G);C+=1;}}i(d,"send");async function u(g){return an(g,await Bu(e.auth))}i(u,"authorize");async function*p(g,h,R){a(Object.freeze({call:g,phase:"stream.open",method:h.method,path:h.path,attempt:0}));try{yield*e.auth.transport.stream(h,R);}catch{yield ps({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:u,stream:p})}i(fr,"createRequestFunnel");function Ou(e,t){let r={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==_u&&(r[o]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Ou,"assembleHeaders");function nr(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(nr,"defaultIdempotencyKeyFactory");var Lu=10;function Vu(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let o=qu(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!Mo(e.code))return {retry:false,reason:"terminal-code"};let n=o==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let s=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(Lu,Math.floor(d)))},"policyCeiling"),c=r.perCallMaxAttempts??s()??r.maxAttempts;if(t+1>=c)return {retry:false,reason:"attempts-exhausted"};let a=zu(e,r.now);return a!==null?a>Tu?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:a}:{retry:true,reason:n,delayMs:Ka(t,r.rng)}}i(Vu,"decideRetry");function qu(e){let t=e.code==="unknown"?Wa(Mu(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(qu,"throttleKind");function zu(e,t){let r=Fu(e.raw);if(r===null)return null;let o=r-t;return o>0?o:0}i(zu,"retryOverrideMs");function Fu(e){for(let t of gs(e)){let r=t.resets_at,o=Nu(r);if(o!==null)return o}return null}i(Fu,"findResetsAt");function gs(e){if(!fs(e))return [];let t=[e];for(let r of ["error","detail"]){let o=e[r];fs(o)&&t.push(o);}return t}i(gs,"candidateScopes");function Nu(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(Nu,"parseInstantMs");function Mu(e){for(let t of gs(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(Mu,"rawWireCode");function fs(e){return typeof e=="object"&&e!==null}i(fs,"isRecord");async function Bu(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(Bu,"resolveDeviceAuth");function Hu(e,t){let r=new AbortController,o=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(o),"cancel")}}i(Hu,"boundedSignal");function Uu(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let o=new AbortController;if(e.aborted||t.aborted)return o.abort(),{signal:o.signal,dispose:r};let n=i(()=>o.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),{signal:o.signal,dispose:i(()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",n);},"dispose")}}i(Uu,"mergeSignals");function ju(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(o=>{let n=t.setTimeout(()=>{r?.removeEventListener("abort",l),o();},e),l=i(()=>{t.clearTimeout(n),o();},"onAbort");r?.addEventListener("abort",l,{once:true});})}i(ju,"delayAbortable");function gr(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let o=e.charCodeAt(t+1);if(!(o>=56320&&o<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(gr,"hasLoneSurrogate");var or="/widget/v1/records";function hs(e){let{auth:t}=e,r=t.mode,o=e.funnel??fr({auth:t,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(a,d,u)=>{let p=await o.send(a,d);return p.ok?p:B(Gu(p.error,r,u))},"send"),l=i((a,d)=>typeof d!="string"||d.length===0?q("validationFailed",{retryable:false,wireMessage:`${a} is required and must be a non-empty string`}):gr(d)?q("validationFailed",{retryable:false,wireMessage:`${a} contains an unpaired surrogate and cannot be encoded`}):null,"segmentError"),s=i((a,d,u)=>{let p=l(a,d);if(p!==null)return p;let h=[...d].length;return h>u?q("validationFailed",{retryable:false,wireMessage:`${a} is ${h} characters; the server accepts at most ${u}`}):null},"boundsError"),c=i((...a)=>a.find(d=>d!==null)??null,"firstError");return {createRequest:i(a=>{let d=c(s("idempotency_key",a.idempotency_key,nn),s("pet_ref",a.pet_ref,mt));return d?Promise.resolve(B(d)):n("records.createRequest",Xo(`${or}/requests`,a),"request")},"createRequest"),initiateUpload:i((a,d)=>{let u=l("request_id",a);return u?Promise.resolve(B(u)):n("records.initiateUpload",Xo(`${or}/requests/${encodeURIComponent(a)}/uploads/initiate`,d),"request")},"initiateUpload"),completeUpload:i((a,d)=>{let u=l("request_id",a);return u?Promise.resolve(B(u)):n("records.completeUpload",Xo(`${or}/requests/${encodeURIComponent(a)}/uploads/complete`,d),"request")},"completeUpload"),getRequest:i(a=>{let d=l("request_id",a);return d?Promise.resolve(B(d)):n("records.getRequest",Mn(`${or}/requests/${encodeURIComponent(a)}`),"request")},"getRequest"),listRequests:i(async()=>{let a=await n("records.listRequests",Mn(`${or}/requests`),"request");if(!a.ok)return a;let d=a.value;return {ok:true,value:Array.isArray(d)?d:d.items??[]}},"listRequests"),getRecord:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.getRecord",Mn(`${or}/pets/${encodeURIComponent(a)}/record`),"content")},"getRecord"),getConsent:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.getConsent",Mn(`${or}/pets/${encodeURIComponent(a)}/consent`),"consent")},"getConsent"),putConsent:i((a,d)=>{let u=c(s("consent_version",d.consent_version,ls),s("idempotency_key",d.idempotency_key,nn),s("pet_ref",a,mt));return u?Promise.resolve(B(u)):n("records.putConsent",Yu(`${or}/pets/${encodeURIComponent(a)}/consent`,d),"consent")},"putConsent"),deleteConsent:i(a=>{let d=s("pet_ref",a,mt);return d?Promise.resolve(B(d)):n("records.deleteConsent",Ku(`${or}/pets/${encodeURIComponent(a)}/consent`),"consent")},"deleteConsent")}}i(hs,"createHttpRecordsRepository");function bs(e,t){let r={...e,recordsReason:t};for(let o of ["wireMessage","raw"]){let n=Object.getOwnPropertyDescriptor(e,o);n!==void 0&&Object.defineProperty(r,o,n);}return Object.freeze(r)}i(bs,"withReason");var $u="pet_not_registered";function Wu(e){return e.httpStatus!==404?null:e.reasonCode===$u?"pet_not_found":"entitlement"}i(Wu,"recordsErrorReasonFor");function Gu(e,t,r){let o=Wu(e);return o!==null?bs(e,o):e.code!=="accessDenied"?e:bs(e,t==="anonymous"?"session_required":r==="content"?"consent_required":"entitlement")}i(Gu,"tagReason");function Mn(e){return {method:"GET",path:e}}i(Mn,"get");function Xo(e,t){return {method:"POST",path:e,body:t}}i(Xo,"post");function Yu(e,t){return {method:"PUT",path:e,body:t}}i(Yu,"put");function Ku(e){return {method:"DELETE",path:e}}i(Ku,"del");var Rs=Symbol.for("@everfur/sdk#EverfurContext@v1"),vs=globalThis,xs=vs[Rs]??(vs[Rs]=createContext(null));xs.displayName??="EverfurContext";function ke(){let e=useContext(xs);if(e===null)throw new rn("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ke,"useEverfurContext");var Jo=new Map,Zo=new Set;function ws(e){Jo.set(e,(Jo.get(e)??0)+1);for(let t of [...Zo])t();}i(ws,"notifyRecordsConsentWithdrawn");function ep(e){return Jo.get(e)??0}i(ep,"recordsConsentEpochOf");function tp(e){return Zo.add(e),()=>{Zo.delete(e);}}i(tp,"subscribe");function Bn(e){let t=useCallback(()=>ep(e),[e]);return useSyncExternalStore(tp,t,t)}i(Bn,"useRecordsConsentEpoch");var ti={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},Es=4e3,np=30;function yt(e){let{petRef:t}=e,r=useRef(e.uploadTransport);r.current=e.uploadTransport;let o=e.uploadTransport!==void 0,{runtime:n,userRef:l,scopeEpoch:s}=ke(),c=useMemo(()=>({}),[n,l,t,s,e.controller]),a=useRef(c),[d,u]=useState({scope:c,controller:e.controller??null}),p=e.controller??(d.scope===c?d.controller:null),[g,h]=useState({scope:c,value:ti}),R=g.scope===c?g.value:ti,v=useCallback(w=>{h(T=>T.scope===c?{scope:c,value:w(T.value)}:T);},[c]),x=useRef(0);useEffect(()=>(a.current=c,h({scope:c,value:ti}),()=>{a.current=null,x.current+=1;}),[c]),useEffect(()=>{if(e.controller)return;let{services:w}=n.registry,T={record:i((M,X)=>w.telemetry.track(M,X),"record")},O=n.registry.acquire("records",`${l??""}|${t}${o?"|own-upload":""}`,()=>us({repository:hs({auth:w.authFor(l),...w.errorPolicy?{errorPolicy:w.errorPolicy}:{}}),uploads:o?{postMultipart:i((M,X,ye)=>(r.current??w.uploadTransport).postMultipart(M,X,ye),"postMultipart")}:w.uploadTransport,telemetry:T}),()=>{});return u({scope:c,controller:O}),()=>{n.registry.release(O);}},[n,l,t,e.controller,s,c,o]);let y=useCallback(w=>{v(T=>({...T,...w}));},[v]),f=useCallback(async()=>{if(!p||a.current!==c)return;let w=x.current+=1;D.current=0,I(),y({loading:true,error:null,denialReason:null,withheld:false});let[T,O]=await Promise.all([p.getConsent(t),p.listRequests()]);if(w!==x.current)return;let M=T.ok?T.value:null,X=O.ok?O.value.filter(Ve=>Ve.petRef===t):[],ye=O.ok?null:O.error;if(M&&M.granted){let Ve=await p.getRecord(t);if(w!==x.current)return;if(Ve.ok){y({consent:M,requests:X,record:Ve.value,withheld:Ve.value.withheld,error:Ve.value.withheld?lp():ye,denialReason:null,loading:false});return}y({consent:M,requests:X,record:null,error:Ve.error,denialReason:pr(Ve.error),withheld:false,loading:false});return}y({consent:M,requests:X,record:null,error:T.ok?ye:T.error,denialReason:M?"consent_required":sp(T),withheld:false,loading:false});},[p,t,y,c]);useEffect(()=>(f(),()=>{x.current+=1;}),[f]);let E=useMemo(()=>ap(R.requests),[R.requests]),b=E?.id??null,C=E?.status??null,D=useRef(0),S=useRef(null),[k,I]=useReducer(w=>w+1,0);useEffect(()=>{if(!p||b===null||C===null||Mr(C)||C==="in_review")return;S.current!==String(b)&&(S.current=String(b),D.current=0);let w=false,T=i(async()=>{if(w||D.current>=np)return;D.current+=1;let M=await p.getRequest(b);if(!w){if(M.ok&&M.value.petRef===t){if(v(X=>({...X,requests:Un(X.requests,M.value)})),Mr(M.value.status)){M.value.status==="published"&&f();return}if(M.value.status==="in_review")return}O=setTimeout(()=>{T();},Es);}},"tick"),O=setTimeout(()=>{T();},Es);return ()=>{w=true,clearTimeout(O);}},[p,b,C,f,k,t,v]);let G=useCallback(async w=>{if(!p||a.current!==c)return jn();let T=await p.createUploadRequest({petRef:t,idempotencyKey:w});return a.current===c&&T.ok&&T.value.petRef===t&&v(O=>({...O,requests:Un(O.requests,T.value)})),T},[p,t,c,v]),z=useCallback((w,T)=>{v(O=>({...O,uploadQueue:O.uploadQueue.map(M=>M.key===w?T(M):M)}));},[v]),Y=useCallback(async(w,T)=>{let O=Date.now().toString(36),M=T.map((ye,Ve)=>{let ie=op(ye);return {key:`${O}-${Ve}`,name:ye.name??null,status:ie===null?"queued":"skipped",progress:0,skipReason:ie,error:null}}),X=[...M];if(!p||a.current!==c)return Object.freeze(X);v(ye=>({...ye,uploadQueue:M,isUploading:true,uploadProgress:0}));for(let[ye,Ve]of T.entries()){let ie=M[ye];if(ie.status==="skipped")continue;if(a.current!==c)break;z(ie.key,Xe=>({...Xe,status:"uploading",progress:0})),y({uploadProgress:0});let we=await p.uploadDocument({requestId:w,file:Ve,onProgress:i(Xe=>{if(a.current!==c)return;let qt=Math.min(1,Math.max(0,Xe));z(ie.key,zt=>({...zt,progress:Math.max(zt.progress,qt)})),y({uploadProgress:qt});},"onProgress")});if(a.current!==c)break;let vt=we.ok?{...ie,status:"done",progress:1}:{...ie,status:"failed",error:we.error};if(X[ye]=vt,z(ie.key,()=>vt),we.ok){let Xe=await p.getRequest(w);a.current===c&&Xe.ok&&Xe.value.petRef===t&&v(qt=>({...qt,requests:Un(qt.requests,Xe.value)}));}}return a.current===c&&y({isUploading:false,uploadProgress:null}),Object.freeze(X)},[p,y,z,t,c,v]),H=useCallback(async(w,T)=>{if(!p||a.current!==c)return jn();let O=`${Date.now().toString(36)}-0`;v(X=>({...X,isUploading:true,uploadProgress:0,uploadQueue:[{key:O,name:T.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let M=await p.uploadDocument({requestId:w,file:T,onProgress:i(X=>{a.current===c&&(y({uploadProgress:X}),z(O,ye=>({...ye,progress:Math.max(ye.progress,Math.min(1,X))})));},"onProgress")});if(a.current!==c)return M;if(y({isUploading:false,uploadProgress:null}),z(O,X=>M.ok?{...X,status:"done",progress:1}:{...X,status:"failed",error:M.error}),M.ok){let X=await p.getRequest(w);a.current===c&&X.ok&&X.value.petRef===t&&v(ye=>({...ye,requests:Un(ye.requests,X.value)}));}return M},[p,y,z,t,c,v]),Z=useCallback(async(w,T)=>{if(!p||a.current!==c)return jn();let O=await p.grantConsent({petRef:t,consentVersion:w,idempotencyKey:T});return O.ok&&a.current===c&&f(),O},[p,t,f,c]),oe=useCallback(async()=>{if(!p||a.current!==c)return jn();let w=await p.revokeConsent(t);return w.ok&&ws(t),w.ok&&a.current===c&&(x.current+=1,y({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:w.value})),w},[p,t,y,c]),Ee=useCallback(()=>{f();},[f]),U=ip(R,p!==null);return useMemo(()=>({status:U,record:R.record,requests:R.requests,activeRequest:E,consent:R.consent,error:R.error,denialReason:R.denialReason,withheld:R.withheld,isUploading:R.isUploading,uploadProgress:R.uploadProgress,uploadQueue:R.uploadQueue,createRequest:G,uploadDocument:H,uploadDocuments:Y,grantConsent:Z,revokeConsent:oe,refresh:Ee}),[U,R,E,G,H,Y,Z,oe,Ee])}i(yt,"useEverfurRecords");function op(e){if(e.mimeType!==on)return "unsupported";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>mr?"too_large":null}i(op,"skipReasonFor");function ip(e,t){return e.loading||!t?"loading":e.withheld||e.denialReason!==null||e.error!==null?"error":e.record!==null&&!e.record.isEmpty||e.requests.length>0?"populated":"empty"}i(ip,"selectStatus");function ap(e){if(e.length===0)return null;let t=e[0];for(let r of e)r.updatedAt>t.updatedAt&&(t=r);return t}i(ap,"newestRequest");function Un(e,t){let r=e.filter(o=>o.id!==t.id);return [t,...r]}i(Un,"replaceRequest");function sp(e){return e.ok?"consent_required":pr(e.error)??"consent_required"}i(sp,"consentDenial");function lp(){return q("internalError",{retryable:false})}i(lp,"withheldSentinel");function jn(){return {ok:false,error:q("internalError",{retryable:true})}}i(jn,"notReady");function ri(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(ri,"reportHostFailure");function cp(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(cp,"isThenable");function $n(e,...t){if(typeof e=="function")try{let r=e(...t);return cp(r)&&Promise.resolve(r).then(void 0,ri),r}catch(r){ri(r);return}}i($n,"callHost");var Ss=new WeakMap;function ln(e){if(typeof e!="function")return;let t=Ss.get(e);if(t!==void 0)return t;let r=i((...o)=>{$n(e,...o);},"guarded");return Ss.set(e,r),r}i(ln,"guardHost");function ze(e,t){let r=null;for(let o of t){let n=e[o];typeof n=="function"&&(r??={...e},r[o]=ln(n));}return r??e}i(ze,"guardHostProps");function Tr(e,...t){let r;try{r=e(...t);}catch(o){return ri(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(r).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(Tr,"callHostAsync");var ks=Object.freeze({name:"dashboard"});function Wn(e=ks){return Object.freeze({stack:Object.freeze([e])})}i(Wn,"initialRecordsNav");function Gn(e){return e.stack[e.stack.length-1]??ks}i(Gn,"currentRecordsScreen");function ni(e,t){return Object.freeze({stack:Object.freeze([...e.stack,t])})}i(ni,"pushRecordsNav");function oi(e,t){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),t])})}i(oi,"replaceRecordsNav");function ii(e){return Wn(e)}i(ii,"resetRecordsNav");function Yn(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(Yn,"popRecordsNav");function Ts(e,t){return t.name==="dashboard"?ii(t):Gn(e).name==="upload"&&t.name==="request"?oi(e,t):ni(e,t)}i(Ts,"transitionRecordsNav");function ai(e,t){switch(t.type){case "push":return ni(e,t.screen);case "pop":return Yn(e).state;case "replace":return oi(e,t.screen);case "reset":return ii(t.screen);case "navigate":return Ts(e,t.screen);default:return e}}i(ai,"recordsNavReducer");function ci(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))ci(e[t]);}return e}i(ci,"deepFreeze");var dp=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Ps={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Is={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},_s={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},up={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},pp={regular:"400",medium:"500",bold:"700"},mp={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},yp=0,Kn="System",Qn="monospace",fp=["content","heading","control","compact","badge"];function gp(e){let t={};for(let r of fp)t[r]=e;return t}i(gp,"authoredTierSizes");function Ds(){return {family:Kn,mono:Qn,fontUrl:null,families:{regular:Kn,medium:Kn,bold:Kn,mono:Qn,monoMedium:Qn,monoBold:Qn},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:_s,tierSizes:gp(_s),lineHeight:up,weight:pp,letterSpacing:mp,scale:1,maxScale:yp,scaleCaps:dp}}i(Ds,"baseType");var As={},si=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function li(e){return `cubic-bezier(${e.join(", ")})`}i(li,"cssCubicBezier");var Os={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:li(si.standard),emphasized:li(si.emphasized),exit:li(si.exit)},reducedMotion:false},bp={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#B91C1C",errorRed:"#FF1B00",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},Ls=ci({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:bp,space:Ps,radius:Is,type:Ds(),motion:Os,slots:As}),hp={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A938C",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"};ci({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:hp,space:Ps,radius:Is,type:Ds(),motion:Os,slots:As});var Vs=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),qs=globalThis,di=qs[Vs]??(qs[Vs]=createContext(Ls));di.displayName??="EverfurThemeContext";function V(){return useContext(di)}i(V,"useEverfurTheme");function Ep(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Ep,"tierMultiplier");function m({tier:e="content",...t}){let{type:r}=V(),o=Ep(r,e);return createElement(Text,o===void 0?t:{maxFontSizeMultiplier:o,...t})}i(m,"Text");var qe=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Sp=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function _(e,t){let r=e.type,o=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:o}:{fontFamily:o,fontWeight:r.weight[Sp[t]]}}i(_,"face");var $=Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you\u2019re authorizing",send:"Send request",sending:"Sending\u2026",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can\u2019t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:i(e=>`Typed signature: ${e}`,"typedSignatureA11y"),missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used"});var xe=Object.freeze({title:$.title,placeholder:$.placeholder,searchA11y:$.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload\u2026",uploadOwnA11y:"Upload records you already have",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:$.recentlyUsed,noMatch:i(e=>`No clinics match \u201C${e}\u201D. You can still request records using the option above.`,"noMatch"),loadingMore:"Loading more\u2026",loadMoreFailed:"Couldn\u2019t load more. Tap to retry.",loadMoreRetryA11y:"Retry loading more clinics",selectA11y:i(e=>`Request records from ${e}`,"selectA11y"),fallback:Object.freeze({title:"Can\u2019t find your clinic?",subtitle:"Add it by email and we\u2019ll request your records.",expandA11y:"Can't find your clinic? Add it by email to request records.",collapseA11y:"Hide the request-by-email form",nameLabel:"Clinic name",namePlaceholder:"Your clinic\u2019s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue",submitA11y:"Request records by email"})});function Fs(e){switch(e){case "verified":return {label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case "unverified":return {label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return {label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}i(Fs,"clinicEmailStatusBadge");function Ns(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(Ns,"formatClinicDistanceLabel");function Ms(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(Ms,"formatClinicDistanceForA11y");var Bs=300,ui=2;var de=Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"});function Hs(e){return !Mr(e.status)}i(Hs,"isRecordsInProgress");function Xn(e,t){if(t===null)return null;let r=e.filter(l=>l.petRef===t);if(r.length===0)return null;let o=r.find(l=>l.status==="published");return o!==void 0?o:r.filter(Hs).sort((l,s)=>s.updatedAt.localeCompare(l.updatedAt))[0]??null}i(Xn,"pickPetRecordsRequest");function pi(e){if(e.hasMarkers)return "published";let t=Xn(e.requests,e.petRef);return t===null?"none":t.status==="published"||Hs(t)?"in_progress":"none"}i(pi,"deriveRecordsDashboardState");function kp(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(kp,"selectDashboardLoading");function mi(e){return kp(e)?"loading":e.hasFullRecord?"record":e.markersError||e.recordError&&!e.hasMarkers?"error":e.dashboardState==="in_progress"&&e.drivingRequest!==null?"in_progress":e.dashboardState==="none"?"none":"labs_only"}i(mi,"selectDashboardView");function wt(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(wt,"recordsEmptyVariantForError");var ge=Object.freeze({loading:"Loading record request",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there\u2019s no reply by day 14.",waitingBanner:i(e=>`It\u2019s been ${e} ${e===1?"day":"days"}. Some clinics take a little longer; we\u2019ve been following up automatically and are still on it. If there\u2019s no reply by day 14, we\u2019ll let you know.`,"waitingBanner"),viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",tryAnotherClinicA11y:"Request records from a different clinic",convert:"Upload my own records instead",converting:"Switching\u2026",convertHint:"We\u2019ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we\u2019ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting\u2026",cancel:"Cancel request",cancelling:"Cancelling\u2026",cancelA11y:"Cancel this records request",cancellingA11y:"Cancelling, please wait",resend:"Resend email",resending:"Resending\u2026",resendA11y:"Resend the authorization email to the clinic",resendingA11y:"Resending the email, please wait",errors:Object.freeze({cancel:"We couldn\u2019t cancel this request. Please try again.",retry:"We couldn\u2019t retry this request. Please try again.",email:"We couldn\u2019t update the clinic email. Please try again.",convert:"We couldn\u2019t switch this to an upload. Please try again.",start:"We couldn\u2019t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function Tp(e){if(e.wireStatus==="clinic_declined")return "The clinic declined to release the records.";if(e.wireStatus==="clinic_responded_no_records")return "The clinic replied but didn\u2019t include your records.";switch(e.failureCode){case "no_response":return "The clinic didn\u2019t reply after several reminders over 14 days.";case "parse_timeout":case "parse_error":return "We received the records but couldn\u2019t read them. Uploading a clean copy usually fixes this.";case "hard_bounce":case "dispatch_failed":return "We couldn\u2019t deliver the email to the clinic.";default:return "This request didn\u2019t go through."}}i(Tp,"fallbackFailureTitle");function Us(e){let t=e.failureReason?.trim()??"";return t.length>0?t:Tp(e)}i(Us,"failureTitle");var _p=1440*60*1e3;function yi(e,t){if(!e.createdAt)return 0;let r=Date.parse(e.createdAt);if(Number.isNaN(r))return 0;let o=t-r;return o<=0?0:Math.floor(o/_p)}i(yi,"requestElapsedDays");var Pp=7;function js(e,t){return e.wireStatus!=="awaiting_response"?false:yi(e,t)>=Pp}i(js,"requestWaitingTooLong");function fi(e){return e.status==="failed"}i(fi,"isTerminalFailure");function $s(e){return fi(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i($s,"shouldOfferRecovery");function Ys(e,t){let[r,o]=useState(""),[n,l]=useState(""),[s,c]=useState([]),[a,d]=useState(null),[u,p]=useState([]),[g,h]=useState(true),[R,v]=useState(false),[x,y]=useState(false),[f,E]=useState(null),[b,C]=useState(null),[D,S]=useState(0),k=useRef(0),I=useRef(true),G=t?.latitude,z=t?.longitude,Y=useMemo(()=>G!==void 0&&z!==void 0?{latitude:G,longitude:z}:void 0,[G,z]);useEffect(()=>(I.current=true,()=>{I.current=false,k.current+=1;}),[e]),useEffect(()=>{let U=true;return h(true),e.recentClinics({limit:5}).then(w=>{U&&(w.ok&&p(w.value.clinics),h(false));}).catch(()=>{U&&h(false);}),()=>{U=false;}},[e]),useEffect(()=>{let U=r.trim();if(U.length<ui){l("");return}let w=setTimeout(()=>l(U),Bs);return ()=>clearTimeout(w)},[r]);let H=n.length>=ui;useEffect(()=>{let U=k.current+=1;if(c([]),d(null),E(null),C(null),!H){v(false);return}v(true),e.searchClinics({query:n,limit:25,...Y?{location:Y}:{}}).then(w=>{!I.current||U!==k.current||(w.ok?(c(w.value.clinics),d(w.value.nextCursor)):E(w.error),v(false));}).catch(()=>{I.current&&U===k.current&&v(false);});},[e,n,H,Y,D]);let Z=useCallback(()=>{if(!H||a===null||x)return;let U=k.current;y(true),C(null),e.searchClinics({query:n,limit:25,cursor:a,...Y?{location:Y}:{}}).then(w=>{!I.current||U!==k.current||(w.ok?(c(T=>[...T,...w.value.clinics]),d(w.value.nextCursor)):C(w.error),y(false));}).catch(()=>{I.current&&U===k.current&&y(false);});},[e,a,n,H,x,Y]),oe=useCallback(U=>o(U),[]),Ee=useCallback(()=>S(U=>U+1),[]);return useMemo(()=>({query:r,debouncedQuery:n,isSearchActive:H,clinics:s,recent:u,recentLoading:g,initialLoading:R,loadingMore:x,hasNextPage:a!==null,error:f,pageError:b,setQuery:oe,loadMore:Z,retry:Ee}),[r,n,H,s,u,g,R,x,a,f,b,oe,Z,Ee])}i(Ys,"useClinicPicker");function bi(e,t,r,o){return Object.freeze({key:e?.id??`free:${t??""}`,clinic:e,freeText:t,email:r,idempotencyKey:o})}i(bi,"clinicDraftFor");var Br=10,Zn=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),cn=i((e,t=1)=>z.string().refine(r=>!gr(r)&&[...r].length>=t&&[...r].length<=e),"text"),Qs=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),Ip=z.object({clinicId:Zn.optional(),clinicFreeText:cn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:cn(320,3).refine(e=>!Qs(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Zn.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0)),Dp=z.object({petRef:cn(128),ownerName:cn(200).refine(e=>e.trim().length>0&&!Qs(e)),authorizationVersion:cn(64),clinics:z.array(Ip).min(1).max(Br)}).strict(),Ap=z.object({request_group_id:Zn,pet_ref:z.string(),created_count:z.number().int().nonnegative(),failed_count:z.number().int().nonnegative(),results:z.array(z.object({idempotency_key:z.string(),clinic_id:Zn.nullable().optional(),clinic_free_text:z.string().nullable().optional(),created:z.boolean(),request:z.unknown().optional(),failure_code:z.string().nullable().optional(),failure_reason:z.string().nullable().optional()}))});function Xs(e){let t=e.funnel??fr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!Dp.safeParse(r).success)return B(q("validationFailed",{retryable:false}));let o=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(s=>({...s.clinicId!==void 0?{clinic_id:s.clinicId}:{clinic_free_text:s.clinicFreeText},...s.clinicEmail!==void 0?{clinic_email:s.clinicEmail}:{},...s.signatureId!==void 0?{signature_id:s.signatureId}:{signature_png_base64:s.signaturePngBase64},idempotency_key:s.idempotencyKey}))}});if(!o.ok)return o;let n=Ap.safeParse(o.value);if(!n.success||n.data.pet_ref!==r.petRef)return Ks();let l=[];for(let s of n.data.results){let c=s.request===void 0||s.request===null?null:ur(s.request);if(s.created!==(c!==null))return Ks();l.push(Object.freeze({idempotencyKey:s.idempotency_key,clinicId:s.clinic_id??null,clinicFreeText:s.clinic_free_text??null,created:s.created,request:c,failureCode:s.failure_code??null,failureReason:s.failure_reason??null}));}return _e(Object.freeze({requestGroupId:n.data.request_group_id,petRef:n.data.pet_ref,results:Object.freeze(l),createdCount:n.data.created_count,failedCount:n.data.failed_count}))}}}i(Xs,"createRecordsClinicBatchClient");function Ks(){return B(q("internalError",{retryable:false}))}i(Ks,"malformed");var Js=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Op=z.object({clinics:z.array(z.object({clinic_id:Js,name:z.string().min(1),address:z.string().nullable(),phone:z.string().nullable(),email_status:z.string(),distance_km:z.number().finite().nonnegative().nullable()})),next_cursor:z.string().nullable().optional()}),Lp=z.object({authorization_version:z.string().min(1),scope_template:z.string().min(1),authorization_template:z.string().min(1)}),Vp=z.object({upload_id:z.string().min(1),upload_url:z.string().url().refine(e=>e.startsWith("https://")),upload_fields:z.record(z.string())});function Zs(e){let{repository:t}=e,r=i(async n=>{let l=await n;if(!l.ok)return l;let s=ur(l.value);return s===null?_r():_e(s)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let s=Op.safeParse(l.value);return s.success?_e(Object.freeze({clinics:Object.freeze(s.data.clinics.map(c=>Object.freeze({id:c.clinic_id,name:c.name,address:c.address,phone:c.phone,emailStatus:c.email_status,distanceKm:c.distance_km}))),nextCursor:s.data.next_cursor??null})):_r()},"page");return {searchClinics:i((n={})=>o(t.searchClinics(n)),"searchClinics"),recentClinics:i((n={})=>o(t.recentClinics(n)),"recentClinics"),async getRequestGroup(n){let l=await t.getRequestGroup(n);if(!l.ok)return l;let s=ns(l.value);return s===null?_r():_e(s)},async getAuthorizationCopy(){let n=await t.getAuthorizationCopy();if(!n.ok)return n;let l=Lp.safeParse(n.value);return l.success?_e(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):_r()},async createClinicRequest(n){let l=await r(t.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?_r():l},retryRequest:i(n=>r(t.retryRequest(n)),"retryRequest"),revokeRequest:i(n=>r(t.revokeRequest(n)),"revokeRequest"),updateClinicEmail:i((n,l)=>r(t.updateClinicEmail(n,l)),"updateClinicEmail"),convertToUpload:i(n=>r(t.convertToUpload(n)),"convertToUpload"),async initiateSignatureUpload(n){let l=await t.initiateSignatureUpload(n);if(!l.ok)return l;let s=Vp.safeParse(l.value);return s.success?_e(Object.freeze({uploadId:s.data.upload_id,uploadUrl:s.data.upload_url,uploadFields:Object.freeze(s.data.upload_fields)})):_r()},async completeSignatureUpload(n){let l=await t.completeSignatureUpload(n);if(!l.ok)return l;let s=z.object({signature_id:Js}).safeParse(l.value);return s.success?_e(s.data.signature_id):_r()}}}i(Zs,"createRecordsClinicController");function _r(){return B(q("internalError",{retryable:false}))}i(_r,"malformed");var br="/widget/v1/records",el=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Rr=i((e,t=1)=>z.string().refine(r=>!gr(r)&&[...r].length>=t&&[...r].length<=e),"text"),rl=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),nl=Rr(320,3).refine(e=>!rl(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),tl=Rr(64),qp=z.object({limit:z.number().int().min(1).max(25).optional()}).strict(),zp=z.object({query:Rr(200,0).optional(),location:z.object({latitude:z.number().finite().min(-90).max(90),longitude:z.number().finite().min(-180).max(180)}).strict().optional(),limit:z.number().int().min(1).max(100).optional(),cursor:Rr(512,0).optional()}).strict(),Fp=z.object({petRef:Rr(128),ownerName:Rr(200).refine(e=>e.trim().length>0&&!rl(e)),authorizationVersion:Rr(64),clinicId:el.optional(),clinicFreeText:Rr(200).refine(e=>e.trim().length>0).optional(),clinicEmail:nl.optional(),signatureId:el.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0));function ol(e){let t=e.funnel??fr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((n,l,s=false)=>t.send(`records.clinic.${n}`,l,l.method==="GET"||s?void 0:{idempotent:false,maxAttempts:1}),"send"),o=i((n,l,s)=>tl.safeParse(n).success?r(l,{method:"POST",path:`${br}/requests/${encodeURIComponent(n)}/${l}`,...s?{body:s}:{}}):hr(),"recover");return {searchClinics(n){return zp.safeParse(n).success?r("search",{method:"GET",path:`${br}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):hr()},recentClinics(n){return qp.safeParse(n).success?r("recent",{method:"GET",path:`${br}/clinics/recent`,query:{limit:n.limit}}):hr()},getRequestGroup(n){return tl.safeParse(n).success?r("requestGroup",{method:"GET",path:`${br}/request-groups/${encodeURIComponent(n)}`}):hr()},getAuthorizationCopy:i(()=>r("authorizationCopy",{method:"GET",path:`${br}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return Fp.safeParse(n).success?r("create",{method:"POST",path:`${br}/clinic-requests`,body:{pet_ref:n.petRef,owner_name:n.ownerName,authorization_version:n.authorizationVersion,idempotency_key:n.idempotencyKey,...n.clinicId!==void 0?{clinic_id:n.clinicId}:{clinic_free_text:n.clinicFreeText},...n.clinicEmail!==void 0?{clinic_email:n.clinicEmail}:{},...n.signatureId!==void 0?{signature_id:n.signatureId}:{signature_png_base64:n.signaturePngBase64}}},true):hr()},retryRequest:i(n=>o(n,"retry"),"retryRequest"),revokeRequest:i(n=>o(n,"revoke"),"revokeRequest"),convertToUpload:i(n=>o(n,"convert-to-upload"),"convertToUpload"),updateClinicEmail(n,l){return nl.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):hr()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?hr():r("signatureInitiate",{method:"POST",path:`${br}/signatures/initiate`,body:{content_type:"image/png",file_size:n}})},completeSignatureUpload(n){return /^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n)?r("signatureComplete",{method:"POST",path:`${br}/signatures/complete`,body:{upload_id:n}}):hr()}}}i(ol,"createHttpRecordsClinicRepository");function hr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(hr,"invalid");function Mt(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:l}=e.registry;return Zs({repository:ol({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>{let l=i(async s=>{if(t===null||n.current!==o)return B(q("accessDenied"));let c=await s();return n.current===o?c:B(q("accessDenied"))},"run");return {searchClinics:i(s=>l(()=>o.searchClinics(s)),"searchClinics"),recentClinics:i(s=>l(()=>o.recentClinics(s)),"recentClinics"),getRequestGroup:i(s=>l(()=>o.getRequestGroup(s)),"getRequestGroup"),getAuthorizationCopy:i(()=>l(()=>o.getAuthorizationCopy()),"getAuthorizationCopy"),createClinicRequest:i(s=>l(()=>o.createClinicRequest(s)),"createClinicRequest"),retryRequest:i(s=>l(()=>o.retryRequest(s)),"retryRequest"),revokeRequest:i(s=>l(()=>o.revokeRequest(s)),"revokeRequest"),updateClinicEmail:i((s,c)=>l(()=>o.updateClinicEmail(s,c)),"updateClinicEmail"),convertToUpload:i(s=>l(()=>o.convertToUpload(s)),"convertToUpload"),initiateSignatureUpload:i(s=>l(()=>o.initiateSignatureUpload(s)),"initiateSignatureUpload"),completeSignatureUpload:i(s=>l(()=>o.completeSignatureUpload(s)),"completeSignatureUpload")}},[o,t])}i(Mt,"useEverfurRecordsClinic");function hi(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:l}=e.registry;return Xs({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>({async createClinicRequestBatch(l){if(t===null||n.current!==o)return B(q("accessDenied"));let s=await o.createClinicRequestBatch(l);return n.current===o?s:B(q("accessDenied"))}}),[o,t])}i(hi,"useEverfurRecordsClinicBatch");var xi=class xi extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,o){return Object.is(r.resetKey,o.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(xi,"HostRenderBoundary");var Ri=xi;function Mp({render:e}){return e()}i(Mp,"RenderHost");function vi({render:e,fallback:t,resetKey:r}){return createElement(Ri,{fallback:t,resetKey:r,children:createElement(Mp,{render:e})})}i(vi,"HostRender");var Bp=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function Hp(e){return Bp[e]}i(Hp,"requires");function ll(e,t,r){let o=Hp(e),n=new Map;for(let c of t)n.set(c.resource,c);if(r?.isPending===true&&o.some(c=>!n.has(c)))return wi({name:e,enabled:false,isPending:true,limits:{}});let l=Up(o,n);return o.filter(c=>n.get(c)?.granted!==true).length===0?wi({name:e,enabled:true,isPending:false,limits:l}):wi({name:e,enabled:false,isPending:false,limits:l,disabled:jp(o,n)})}i(ll,"decideCapability");function Up(e,t){let r={};for(let o of e){let n=t.get(o)?.limits;if(n)for(let[l,s]of Object.entries(n)){let c=r[l];r[l]=c===void 0?s:Math.min(c,s);}}return r}i(Up,"mergeLimits");function jp(e,t){for(let r of e){let o=t.get(r)?.disabled;if(o)return Object.freeze({reason:o.reason,level:o.level,recoverable:o.recoverable})}return Object.freeze({reason:Ho("accessDenied"),level:"user_entitlement",recoverable:false})}i(jp,"disabledFor");function wi(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(wi,"freezeDecision");function Ci(e){let{runtime:t}=ke(),r=t.entitlements,o=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>ll(e,o.decisions,{isPending:o.isPending}),[e,o])}i(Ci,"useCapability");var Gp=48;function Yp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Yp,"selectView");function Ne(e){let{capability:t,children:r,renderDisabled:o,renderPending:n,style:l}=e,s=Ci(t),c=useMemo(()=>Yp(s),[s]);switch(c){case "enabled":return r;case "pending":return n?jsx(vi,{render:n,fallback:jsx(dl,{capability:t,style:l})}):jsx(dl,{capability:t,style:l});case "disabled":return o?jsx(vi,{render:()=>o(s),fallback:jsx(ul,{decision:s,style:l}),resetKey:s}):jsx(ul,{decision:s,style:l});default:return yr(c)}}i(Ne,"CapabilityGate");function dl({capability:e,style:t}){let r=V(),o=useMemo(()=>pl(r),[r]);return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:o.skeletonBar})})}i(dl,"PendingSkeleton");function ul({decision:e,style:t}){let r=V(),o=useMemo(()=>pl(r),[r]),n=e.disabled?.reason??"";return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:n,children:n.length>0?jsx(m,{style:o.offstateText,children:n}):null})}i(ul,"OffState");function pl(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({offstate:{minHeight:Gp,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:o.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{..._(e,"regular"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:o.xs,backgroundColor:t.brandSofter}})}i(pl,"makeStyles");var dn=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function Me(e){let t=V(),r=useMemo(()=>Xp(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${dn.title}. ${dn.body}`,children:[jsx(m,{style:r.title,children:dn.title}),jsx(m,{style:r.body,children:dn.body})]})}i(Me,"ClinicalDisclaimer");function Xp(e){let{color:t,space:r,type:o}=e;return StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{..._(e,"bold"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.secondary,letterSpacing:o.letterSpacing.eyebrow},body:{..._(e,"regular"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.muted}})}i(Xp,"makeStyles");function Je(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(Je,"slotBox");function ot(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(ot,"slotText");var fl=Object.freeze({idle:Object.freeze({title:"Find your pet\u2019s clinic",body:"Search for the clinic that holds your pet\u2019s records. We\u2019ll request them on your behalf once you sign the authorization.",action:null}),no_requests:Object.freeze({title:"No record requests yet",body:"When you request records from a clinic, you\u2019ll be able to track every step here.",action:null}),no_records:Object.freeze({title:"Nothing to show just yet",body:"Once your pet\u2019s records arrive and our team reviews them, lab trends and visits will appear here.",action:null}),rate_limited:Object.freeze({title:"Slow down a moment",body:"You\u2019ve made a lot of requests just now. You can try again shortly.",action:"Try again"}),service_unavailable:Object.freeze({title:"Records search is temporarily down",body:"We\u2019re working on it. Please try again in a few minutes.",action:"Try again"}),error:Object.freeze({title:"Couldn\u2019t reach Everfur",body:"Check your connection and try again.",action:"Try again"})}),ki=60;function gl(e){return `Try again in ${e}s`}i(gl,"coolingActionLabel");var bl="Try again, available shortly";function Qe({variant:e,onAction:t,message:r,testID:o}){let n=rm(),l=fl[e],[s,c]=useState(e==="rate_limited"?ki:0);useEffect(()=>{e==="rate_limited"&&c(ki);},[e]),useEffect(()=>{if(s<=0)return;let u=setTimeout(()=>c(p=>Math.max(0,p-1)),1e3);return ()=>clearTimeout(u)},[s]);let a=e==="rate_limited"&&s>0,d=a?gl(s):l.action;return jsxs(View,{style:n.container,accessibilityRole:"summary",testID:o,children:[jsx(View,{style:n.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:n.title,children:l.title}),jsx(m,{style:n.body,children:r??l.body}),d!==null&&t?jsx(Pressable,{onPress:t,disabled:a,accessibilityRole:"button",accessibilityLabel:a?bl:d,accessibilityState:{disabled:a},style:[n.action,a?n.actionDisabled:null],testID:o?`${o}-action`:`records-empty-${e}-action`,children:jsx(m,{style:n.actionLabel,children:d})}):null]})}i(Qe,"RecordsEmptyState");function rm(){let e=V();return useMemo(()=>nm(e),[e])}i(rm,"useStyles");function nm(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=r.lg+r.xs+r.xs/2;return StyleSheet.create({container:{paddingVertical:r.xxl,paddingHorizontal:r.xl,alignItems:"center",gap:r.sm+r.xs/2},glyph:{width:s,height:s,borderRadius:s/2,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug)-1,color:t.brandInk,textAlign:"center"},body:{..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.normal),color:t.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:r.sm,minHeight:r.xxl+r.sm,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,backgroundColor:t.brand,alignItems:"center",justifyContent:"center",...Je(l.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug)-1,...ot(l.primaryButton)}})}i(nm,"makeStyles");var Ze="Back";function et({title:e,onBack:t,right:r,testID:o,variant:n="brand"}){let l=pn();return jsxs(View,{style:l.row,testID:o,children:[t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Ze,hitSlop:12,style:l.back,testID:o?`${o}-back`:void 0,children:jsx(View,{style:l.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):jsx(View,{style:l.back}),jsx(m,{style:n==="document"?l.documentTitle:l.title,accessibilityRole:"header",numberOfLines:1,children:e}),jsx(View,{style:l.right,children:r??jsx(View,{style:l.back})})]})}i(et,"ScreenHeader");function xl(){let e=pn();return jsxs(View,{style:e.listGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar})]})}i(xl,"ListGlyph");function wl(){let e=pn();return jsxs(View,{style:e.shareGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:[e.shareDot,e.shareDotTop]}),jsx(View,{style:[e.shareDot,e.shareDotLeft]}),jsx(View,{style:[e.shareDot,e.shareDotBottom]}),jsx(View,{style:[e.shareStroke,e.shareStrokeUp]}),jsx(View,{style:[e.shareStroke,e.shareStrokeDown]})]})}i(wl,"ShareGlyph");function Cl(){let e=pn();return jsxs(View,{style:e.sendGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.sendBody}),jsx(View,{style:e.sendFold})]})}i(Cl,"SendGlyph");function El(){let e=pn();return jsxs(View,{style:e.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.downloadStem}),jsx(View,{style:e.downloadHead}),jsx(View,{style:e.downloadTray})]})}i(El,"DownloadGlyph");function pn(){let e=V();return useMemo(()=>lm(e),[e])}i(pn,"useStyles");function lm(e){let{color:t,space:r,type:o}=e,n=r.xxl+r.md,l=r.md,s=r.xs/2,c=r.lg+r.xs+r.xs/2;return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md,gap:r.sm},back:{width:n,height:n,alignItems:"center",justifyContent:"center"},chevron:{width:l,height:l,borderLeftWidth:s,borderBottomWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginLeft:r.xs},title:{flex:1,..._(e,"bold"),fontSize:o.size.heading,lineHeight:Math.round(o.size.heading*o.lineHeight.tight)+1,color:t.brandInk},documentTitle:{flex:1,textAlign:"center",..._(e,"bold"),fontSize:o.size.subtitle,lineHeight:Math.round(o.size.subtitle*o.lineHeight.snug),color:t.text.primary},right:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2},listGlyph:{width:c,height:c,justifyContent:"space-evenly"},listBar:{height:s,borderRadius:s,backgroundColor:t.brandInk},shareGlyph:{width:c-r.xs,height:c-r.xs},shareDot:{position:"absolute",width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs,borderWidth:s,borderColor:t.brandInk},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:r.xs+r.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:r.xs,top:r.sm,width:r.sm+r.xs/2,height:s,backgroundColor:t.brandInk},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:c-r.xs,height:c-r.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],borderRadius:s},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:s,backgroundColor:t.brandInk},downloadGlyph:{width:c-r.xs,height:c-r.xs,alignItems:"center"},downloadStem:{width:s,height:r.sm+r.xs/2,backgroundColor:t.brandInk},downloadHead:{width:r.sm,height:r.sm,borderRightWidth:s,borderBottomWidth:s,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginTop:-r.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:r.xs+r.xs/2,borderLeftWidth:s,borderRightWidth:s,borderBottomWidth:s,borderColor:t.brandInk}})}i(lm,"makeStyles");var um=120,pm=44;function mm({reason:e,onExit:t,exitLabel:r,style:o}){let{color:n,space:l,radius:s,type:c}=V();return jsxs(View,{testID:"records-gate-off",style:[{minHeight:um,justifyContent:"center",gap:l.md,padding:l.lg,borderRadius:s.md,borderWidth:1,borderColor:n.brandBorder,backgroundColor:n.surfaceCream},o],children:[e.length>0?jsx(m,{style:{fontSize:c.size.bodyTight,color:n.text.muted},children:e}):null,jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:r,testID:"records-gate-off-exit",style:{minHeight:pm,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:l.lg,borderRadius:s.pill,borderWidth:1.5,borderColor:n.brand},children:jsx(m,{style:{fontSize:c.size.body,color:n.brand},children:r})})]})}i(mm,"RecordsGateOffState");function Be(e,t){return e===void 0?{}:{renderDisabled:i(r=>jsx(mm,{reason:r.disabled?.reason??"",onExit:e,exitLabel:t}),"renderDisabled")}}i(Be,"recordsGateExit");var fm="your pet";function He(e){let t=e?.trim()??"";return t.length>0?t:fm}i(He,"petNameOr");var dt=Object.freeze({title:"Health records",openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${He(e)}\u2019s lab trends`,"lead"),retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:i(e=>`Important: ${e}`,"important")}),Bt=Object.freeze({title:"Marker Summary",marker:"Marker",markers:"Markers",outOfRange:"OUT OF RANGE",inRange:"IN RANGE",noRange:"NO RANGE",subtitle:"Summary of your pet\u2019s biomarkers",ask:"Ask about these markers",askA11y:"Ask Everfur about these markers",a11y:i((e,t,r,o)=>`Marker summary: ${e} ${e===1?"marker":"markers"}, ${t} in range, ${r} out of range${o>0?`, ${o} without a range`:""}.`,"a11y")}),Ti=Object.freeze({counter:i((e,t)=>`${e+1} of ${t}`,"counter"),a11y:i((e,t,r)=>e!==null?`${e}, marker ${t+1} of ${r}. Swipe left or right to see more markers.`:`Marker ${t+1} of ${r}`,"a11y")}),ir=Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we\u2019ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y"),status:i(e=>`Status: ${e}`,"status"),latestA11y:i((e,t,r)=>`Latest reading ${e}, ${t}, collected ${r}`,"latestA11y"),readingsA11y:i(e=>`${e} readings, oldest to newest`,"readingsA11y")}),Ct=Object.freeze({title:"Where this reading came from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn\u2019t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading",askA11y:"Ask Everfur about this reading"}),Hr=Object.freeze({title:i(e=>`${He(e)}\u2019s records request`,"title"),body:i(e=>`We\u2019re requesting ${He(e)}\u2019s records from your vet. This usually takes a few days; we\u2019ll show lab trends here as soon as they arrive.`,"body"),a11y:i(e=>`Records request in progress for ${He(e)}.`,"a11y"),openA11y:i((e,t)=>`Open ${He(e)}\u2019s records request. ${t}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),Pr=Object.freeze({title:i(e=>`Add ${He(e)}\u2019s records`,"title"),body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicA11y:i(e=>`Request ${He(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${He(e)}\u2019s records`,"uploadDocumentA11y")});var ro="rgba(0,0,0,0.4)";function be(){let e=V();return useMemo(()=>Rm(e),[e])}i(be,"useScreenStyles");function vr({disclaimer:e,style:t}){let r=be();return e.trim().length===0?null:jsxs(View,{style:[r.band,t],accessible:true,accessibilityRole:"text",accessibilityLabel:dt.important(e),testID:"records-disclaimer-band",children:[jsx(View,{style:r.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:r.infoGlyphText,children:"i"})}),jsx(m,{style:r.bandText,children:e})]})}i(vr,"DisclaimerBand");function re({label:e,onPress:t,kind:r="primary",disabled:o=false,busy:n=false,accessibilityLabel:l,testID:s,style:c}){let a=be(),d=V(),u=r==="primary"?a.pillPrimary:r==="outline"?a.pillOutline:r==="danger"?a.pillDanger:r==="ask"?a.pillAsk:a.pillLink,p=r==="primary"?a.pillPrimaryLabel:r==="danger"?a.pillDangerLabel:r==="ask"?a.pillAskLabel:r==="link"?a.pillLinkLabel:a.pillOutlineLabel;return jsxs(Pressable,{onPress:t,disabled:o||n,accessibilityRole:"button",accessibilityLabel:l??e,accessibilityState:{disabled:o||n,busy:n},style:[a.pill,u,o?a.pillDisabled:null,c],testID:s,children:[n?jsx(ActivityIndicator,{size:"small",color:r==="primary"?d.color.onPrimary:d.color.brandInk}):null,jsx(m,{style:p,children:e})]})}i(re,"Pill");function Ht({label:e,tone:t="neutral",testID:r}){let o=be(),{bg:n,fg:l}=o.chipTones[t];return jsx(View,{style:[o.chip,n],testID:r,children:jsx(m,{style:[o.chipText,l],children:e})})}i(Ht,"Chip");function Pt({title:e,count:t}){let r=be();return jsxs(View,{style:r.sectionHeader,children:[jsx(m,{style:r.sectionTitle,accessibilityRole:"header",children:e}),t!==void 0?jsx(m,{style:r.sectionCount,children:t}):null]})}i(Pt,"SectionHeader");function Ir({direction:e="right"}){let t=be(),r=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsx(View,{style:[t.chevron,{transform:[{rotate:r}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(Ir,"Chevron");function Rm(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((v,x)=>Math.round(v*x),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl+r.md,p=i((v,x,y,f="regular")=>({..._(e,f),fontSize:v,lineHeight:a(v,x),color:y}),"text"),g=ot(l.recordCard),h=e.brightness==="dark"?t.errorRed:t.danger,R=i((v,x)=>({bg:{backgroundColor:v},fg:{color:x}}),"tone");return {chipTones:{neutral:R(t.badgeBgNeutral,t.text.secondary),info:R(t.brandSoft,t.brandInk),warning:R(t.badgeBgCaution,t.warningStrong),critical:R(t.badgeBgCritical,t.danger),positive:R(t.badgeBgPositive,t.success)},...StyleSheet.create({root:{flex:1,backgroundColor:t.background},body:{flex:1},content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg},contentTight:{paddingHorizontal:r.sm,paddingBottom:r.xxl,gap:r.lg},inset:{paddingHorizontal:r.sm},section:{gap:r.sm+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.xs},sectionTitle:{...p(s.body+1,c.snug,t.text.primary,"bold")},sectionCount:{...p(s.bodyTight,c.snug,t.text.muted,"medium")},card:{borderRadius:o.lg-r.xs,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.xs,...Je(l.recordCard,d)},creamCard:{borderRadius:o.lg-r.xs/2,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md,...Je(l.recordCard,d)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,paddingVertical:r.md},rowDivider:{borderTopWidth:d,borderTopColor:t.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:r.xs+r.xs/2},rowTitle:{...p(s.body,c.snug,t.text.primary,"medium"),...g},rowDetail:{...p(s.caption,c.normal,t.text.secondary),marginTop:r.xs/2,...g},rowValue:{...p(s.body+1,c.snug,t.text.primary,"bold"),marginTop:r.xs/2,...g},rowMuted:{...p(s.caption,c.normal,t.text.muted),...g},chip:{borderRadius:o.pill,paddingHorizontal:r.sm,paddingVertical:r.xs-1,alignSelf:"flex-start"},chipText:{...p(s.tiny,c.snug,t.text.primary,"medium")},pill:{minHeight:u,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm},pillPrimary:{backgroundColor:t.brand,...Je(l.primaryButton)},pillPrimaryLabel:{...p(s.body,c.snug,t.onPrimary,"bold"),...ot(l.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:t.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...p(s.body,c.snug,t.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:t.danger,backgroundColor:t.surface},pillDangerLabel:{...p(s.bodyTight,c.snug,t.danger,"bold")},pillAsk:{borderWidth:d,borderColor:t.borderRingCream,backgroundColor:t.surface},pillAskLabel:{...p(s.body,c.snug,t.text.primary,"bold")},pillLink:{backgroundColor:"transparent",paddingHorizontal:r.sm},pillLinkLabel:{...p(s.body,c.snug,t.linkInk,"bold")},pillDisabled:{opacity:.5},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},infoNoteText:{flex:1,...p(s.bodyTight,c.normal,t.text.primary)},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCaution,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},cautionNoteText:{flex:1,...p(s.bodyTight,c.normal,t.warningStrong)},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2},statusText:p(s.bodyTight,c.relaxed,t.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCritical,padding:r.md},errorText:{flex:1,...p(s.bodyTight,c.normal,h)},band:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft},bandText:{flex:1,...p(s.caption,c.normal,t.text.secondary)},infoGlyph:{width:r.md+r.xs/2,height:r.md+r.xs/2,borderRadius:o.pill,borderWidth:1,borderColor:t.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...p(s.small,c.tight,t.text.secondary,"bold")},chevron:{width:r.sm,height:r.sm,borderTopWidth:r.xs/2,borderRightWidth:r.xs/2,borderColor:t.text.muted},lead:{paddingHorizontal:r.sm,...p(s.body+1,c.snug,t.text.primary,"bold")},field:{minHeight:u,paddingHorizontal:r.md,paddingVertical:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,..._(e,"regular"),fontSize:s.body},fieldLabel:{...p(s.bodyTight,c.normal,t.text.secondary,"medium")},muted:p(s.caption,c.normal,t.text.muted),bodyText:p(s.body,c.normal,t.text.primary)})}}i(Rm,"makeScreenStyles");function Ur(e,t){return e===null?"":t?`${e} ${t}`:e}i(Ur,"formatEntityValue");var kl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Q(e){if(!e)return "-";let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(t!==null){let n=kl[Number(t[2])-1];return n===void 0?"-":`${n} ${Number(t[3])}, ${t[1]}`}let r=Date.parse(e);if(Number.isNaN(r))return "-";let o=new Date(r);return `${kl[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(Q,"formatRecordsDate");var fe=Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:i(e=>`Measured ${e}`,"measured"),uploadedDocument:"Uploaded document",kind:Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:i(e=>`Dr. ${e}`,"doctor"),lot:i(e=>`Lot ${e}`,"lot"),expires:i(e=>`Expires ${e}`,"expires")});function Xt(e){switch(e){case "above":return {label:"Above range",outOfRange:true};case "below":return {label:"Below range",outOfRange:true};case "in_range":return {label:"In range",outOfRange:false};default:return {label:"No range on file",outOfRange:false}}}i(Xt,"markerStatusLabel");function jr(e,t){return t<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${t} visits`}i(jr,"trajectoryLabel");function ar(e){let t=e.replace(/_/g," ").trim();return t.length===0?e:t.charAt(0).toUpperCase()+t.slice(1)}i(ar,"humanize");var Tl=Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function Dr(e){return Object.prototype.hasOwnProperty.call(Tl,e)?Tl[e]:ar(e)}i(Dr,"bodySystemLabel");var _l=Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function $r(e){return Object.prototype.hasOwnProperty.call(_l,e)?_l[e]:ar(e)}i($r,"soapSectionLabel");function Pl(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(Pl,"formatWeightKg");function Et(e,t,r){if((e===null||!Number.isFinite(e))&&r)return r;if(e===null||!Number.isFinite(e))return "-";let o=e.toFixed(3).replace(/\.?0+$/,"");return t?`${o} ${t}`:o}i(Et,"formatMarkerReading");function Pi(e,t,r){let o=jr(t,r);return e?`${fe.measured(Q(e))}${o?` \xB7 ${o}`:""}`:o}i(Pi,"labDetailLine");var ue=Object.freeze({openA11y:"Share medical record",title:"Share medical record",helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",createLink:"Create link and share",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn\u2019t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",copyLinkA11y:i(e=>`Copy share link, ${e}`,"copyLinkA11y"),turnOff:"Turn off",turnOffA11y:i(e=>`Turn off share link, ${e}`,"turnOffA11y"),turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",copied:"Link copied.",copyFailed:"Could not copy the link.",turnedOff:"Link turned off."})});function vm(e,t){if(!e)return false;let r=Date.parse(e);return Number.isNaN(r)?false:r<=t}i(vm,"isShareExpired");function xm(e,t){let r=Q(e);return r==="-"?t?"Expired":"No expiry date":t?`Expired ${r}`:`Expires ${r}`}i(xm,"formatShareExpiry");function Il(e,t,r){let o=e.map(n=>{let l=vm(n.expiresAt,r),s=xm(n.expiresAt,l),c=Q(n.createdAt),a=l?"Expired":"Active",d=s.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return {shareId:n.shareId,shareUrl:t[n.shareId]??null,active:!l,statusLabel:a,expiryLabel:s,createdLabel:c==="-"?null:`Created ${c}`,a11yLabel:`Share link. ${a}. ${s}.`,actionContext:d}});return Object.freeze([...o.filter(n=>n.active),...o.filter(n=>!n.active)])}i(Il,"buildShareRows");function no(e,t){let r=e?.httpStatus;if(rr(e)){if(t==="create")return "Records access for this pet is off, so a new link cannot be created.";if(t==="download")return "Records access for this pet is off, so the PDF cannot be downloaded."}if(r===429)return "You are creating links a little too fast. Wait a moment, then try again.";if(t==="revoke"&&(r===404||r===409||r===410))return "That link was already turned off.";if(r===401||r===403)return "You need to be signed in as this pet's owner to do that.";switch(t){case "create":return "Could not create a share link. Please try again.";case "revoke":return "Could not turn off that link. Please try again.";default:return "Could not download the record PDF. Please try again."}}i(no,"shareErrorMessage");function ve({width:e,height:t,radius:r,style:o}){let{color:n,radius:l}=V();return jsx(View,{style:[{width:e,height:t,borderRadius:r??l.xs,backgroundColor:n.skeleton},o],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(ve,"SkeletonBlock");var Ii=180,Al=70,oo=22,Cm=300,Ol=44,io=24,Di=34,Em=6,Sm=5;function ao({testID:e}){let t=fn(),r=i(o=>jsxs(View,{style:t.actionRow,children:[jsxs(View,{style:t.actionLeft,children:[jsx(ve,{width:18,height:18,radius:9}),jsx(ve,{width:"55%",height:14,radius:7})]}),jsx(ve,{width:18,height:18,radius:9})]},o),"action");return jsxs(View,{style:t.dashboard,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:dt.loading,testID:e,children:[jsx(View,{style:t.inset,children:jsxs(View,{style:t.summaryCard,children:[jsx(ve,{width:Ii,height:Ii,radius:Ii/2}),jsxs(View,{style:t.badges,children:[jsx(ve,{width:Al,height:oo,radius:oo/2}),jsx(ve,{width:Al,height:oo,radius:oo/2})]})]})}),jsx(ve,{width:150,height:16,radius:8,style:t.inset}),jsx(View,{style:t.carouselCard,children:jsx(ve,{width:"100%",height:Cm,radius:14})}),jsxs(View,{style:t.dots,children:[jsx(ve,{width:6,height:6,radius:3}),jsx(ve,{width:18,height:6,radius:3}),jsx(ve,{width:6,height:6,radius:3})]}),jsx(ve,{width:46,height:12,radius:6,style:t.centered}),jsx(View,{style:t.inset,children:jsx(ve,{width:"100%",height:Ol,radius:12})}),jsxs(View,{style:[t.inset,t.actions],children:[r("a"),r("b")]})]})}i(ao,"DashboardSkeleton");function Ll({testID:e}){let t=fn();return jsxs(View,{style:t.request,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ge.loading,testID:e,children:[jsx(View,{children:[0,1,2,3].map(r=>jsxs(View,{style:t.railRow,children:[jsxs(View,{style:t.railColumn,children:[jsx(ve,{width:io,height:io,radius:io/2}),r<3?jsx(ve,{width:2,height:20,radius:1,style:t.connector}):null]}),jsxs(View,{style:t.railBody,children:[jsx(ve,{width:"55%",height:14,radius:7}),jsx(ve,{width:"75%",height:11,radius:6})]})]},r))}),jsxs(View,{style:t.statusCard,children:[jsx(ve,{width:"90%",height:13,radius:6}),jsx(ve,{width:"60%",height:13,radius:6})]}),jsx(ve,{width:"100%",height:50,radius:25})]})}i(Ll,"RequestSkeleton");function Vl({testID:e}){let t=fn();return jsxs(View,{style:t.timeline,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:fe.loadingTimeline,testID:e,children:[jsx(View,{style:t.timelineDisclaimer,children:jsx(ve,{width:"100%",height:Ol,radius:12})}),Array.from({length:Em},(r,o)=>jsxs(View,{children:[o>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,children:[jsx(ve,{width:Di,height:Di,radius:Di/2}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.timelineTop,children:[jsx(ve,{width:44,height:10,radius:5}),jsx(ve,{width:56,height:12,radius:6})]}),jsx(ve,{width:"70%",height:14,radius:7}),o%2===0?jsx(ve,{width:"45%",height:12,radius:6}):null]})]})]},o))]})}i(Vl,"TimelineSkeleton");function ql({testID:e}){let t=fn();return jsx(View,{style:t.clinics,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:xe.loading,testID:e,children:Array.from({length:Sm},(r,o)=>jsxs(View,{style:t.clinicRow,children:[jsx(ve,{width:"65%",height:14,radius:7}),jsx(ve,{width:"40%",height:11,radius:6})]},o))})}i(ql,"ClinicsSkeleton");function zl({testID:e}){let t=fn();return jsx(View,{style:t.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ue.loadingLinks,testID:e,children:[0,1].map(r=>jsxs(View,{style:t.shareRow,children:[jsx(ve,{width:"55%",height:13}),jsx(ve,{width:"40%",height:11})]},r))})}i(zl,"SharesSkeleton");var Ai=62;function fn(){let e=V();return useMemo(()=>km(e),[e])}i(fn,"useStyles");function km(e){let{color:t,space:r,radius:o}=e,n=StyleSheet.hairlineWidth;return StyleSheet.create({dashboard:{flex:1,paddingHorizontal:r.sm,paddingTop:r.xs,gap:r.lg,backgroundColor:t.background},inset:{paddingHorizontal:r.sm},summaryCard:{alignItems:"center",borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg+r.xs,gap:r.md+r.xs/2},badges:{flexDirection:"row",gap:r.md},carouselCard:{borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg},dots:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.xs+r.xs/2},centered:{alignSelf:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},request:{paddingHorizontal:r.lg,paddingTop:r.xs,gap:r.lg+r.xs/2,backgroundColor:t.background},railRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md},railColumn:{alignItems:"center",width:io},connector:{marginVertical:r.xs/2},railBody:{flex:1,paddingBottom:r.lg+r.xs/2,gap:r.xs+r.xs/2},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2,gap:r.sm},timeline:{flex:1,backgroundColor:t.background},timelineDisclaimer:{paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBody:{flex:1,gap:r.xs-1},timelineTop:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},timelineSeparator:{height:n,backgroundColor:t.brandBorder,marginLeft:Ai},clinics:{gap:r.md},clinicRow:{borderRadius:o.lg-r.xs/2,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2,gap:r.sm},shares:{gap:r.md,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:n,borderColor:t.brandBorder},shareRow:{gap:r.xs+r.xs/2}})}i(km,"makeStyles");var Am=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Oi(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",style:e.style,...Be(e.onBack,Ze),children:t===null?jsx(m,{accessibilityRole:"alert",children:de.sessionRequired}):jsx(Om,{...ze(e,["onNavigate","onBack"])},JSON.stringify([t,r,e.petRef]))})}i(Oi,"EverfurClinicPicker");function Om({petRef:e,controller:t,recordsController:r,location:o,onNavigate:n,onBack:l,style:s}){let c=be(),a=Vm(),d=V(),u=Mt(),p=Ys(t??u,o),g=yt(r?{petRef:e,controller:r}:{petRef:e}),h=useRef(nr()),[R,v]=useState(false),[x,y]=useState(null),[f,E]=useState(false),[b,C]=useState(""),[D,S]=useState(false),[k,I]=useState(""),[G,z]=useState(false),Y=useCallback(O=>{n?.({name:"consent",clinic:bi(O,null,"",h.current())});},[n]),H=i(()=>{R||(v(true),y(null),g.createRequest(`records-upload-${Date.now().toString(36)}`).then(O=>{if(v(false),!O.ok){y(ge.errors.start);return}n?.({name:"request",requestId:O.value.id});}));},"startUpload"),Z=D?b:p.query,oe=Am.test(k.trim()),Ee=Z.trim().length>0&&oe,U=i(O=>{let{layoutMeasurement:M,contentOffset:X,contentSize:ye}=O.nativeEvent;M.height+X.y>=ye.height-M.height*.6&&p.loadMore();},"onEndReached"),w=p.isSearchActive?p.clinics:p.recent,T=p.isSearchActive?p.error?wt(p.error):!p.initialLoading&&p.clinics.length===0?"idle":null:p.recent.length>0||p.recentLoading?null:"idle";return jsxs(View,{style:[c.root,s],children:[jsx(et,{title:xe.title,onBack:l,testID:"records-clinic-header"}),jsxs(View,{style:a.searchBar,children:[jsx(View,{style:a.searchGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(qe,{value:p.query,onChangeText:p.setQuery,placeholder:xe.placeholder,placeholderTextColor:d.color.text.muted,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",maxLength:200,accessibilityLabel:xe.searchA11y,style:a.searchInput,testID:"records-clinic-search-input"}),p.query.length>0?jsx(Pressable,{onPress:()=>p.setQuery(""),accessibilityRole:"button",accessibilityLabel:xe.clearSearch,hitSlop:8,testID:"records-clinic-search-clear",children:jsx(m,{style:a.clearGlyph,children:"\xD7"})}):null]}),n?jsxs(View,{style:a.uploadWrap,children:[x?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:x})}):null,jsx(re,{label:R?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",accessibilityLabel:xe.uploadOwnA11y,busy:R,onPress:H,testID:"records-clinic-upload-own"})]}):null,jsxs(ScrollView,{contentContainerStyle:a.list,keyboardShouldPersistTaps:"handled",onScroll:p.isSearchActive?U:void 0,scrollEventThrottle:200,testID:"records-clinic-results",children:[p.isSearchActive?jsxs(View,{style:a.fallbackCard,testID:"records-clinic-fallback-card",children:[jsxs(Pressable,{onPress:()=>E(O=>!O),accessibilityRole:"button",accessibilityLabel:f?xe.fallback.collapseA11y:xe.fallback.expandA11y,style:a.fallbackHeader,testID:"records-clinic-fallback",children:[jsxs(View,{style:a.fallbackCopy,children:[jsx(m,{style:a.fallbackTitle,numberOfLines:1,children:xe.fallback.title}),jsx(m,{style:a.fallbackSubtitle,numberOfLines:2,children:xe.fallback.subtitle})]}),jsx(Ir,{direction:f?"up":"down"})]}),f?jsxs(View,{style:a.fallbackForm,children:[jsx(m,{style:c.fieldLabel,children:xe.fallback.nameLabel}),jsx(qe,{accessibilityLabel:xe.fallback.nameLabel,style:c.field,value:Z,onChangeText:O=>{C(O),S(true);},placeholder:xe.fallback.namePlaceholder,placeholderTextColor:d.color.text.placeholder,autoCapitalize:"words",autoCorrect:false,maxLength:200,testID:"records-clinic-fallback-name"}),jsx(m,{style:c.fieldLabel,children:xe.fallback.emailLabel}),jsx(qe,{accessibilityLabel:xe.fallback.emailLabel,style:c.field,value:k,onChangeText:O=>{I(O),z(false);},onBlur:()=>z(true),placeholder:xe.fallback.emailPlaceholder,placeholderTextColor:d.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,testID:"records-clinic-fallback-email"}),G&&k.trim().length>0&&!oe?jsx(m,{style:c.errorText,accessibilityRole:"alert",children:ge.errors.invalidEmail}):null,jsx(m,{style:c.muted,children:xe.fallback.reviewNote}),jsx(re,{label:xe.fallback.submit,accessibilityLabel:xe.fallback.submitA11y,disabled:!Ee||!n,onPress:()=>n?.({name:"consent",clinic:bi(null,Z.trim(),k.trim().toLowerCase(),h.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):p.recent.length>0?jsx(m,{style:a.sectionLabel,accessibilityRole:"header",testID:"records-clinic-recent-label",children:xe.recentlyUsed}):null,p.isSearchActive&&p.initialLoading?jsx(ql,{testID:"records-clinic-page-loading"}):null,w.map(O=>jsx(Lm,{clinic:O,onSelect:Y,styles:a},O.id)),T&&!p.initialLoading?jsx(Qe,{variant:T,message:p.isSearchActive&&T==="idle"?xe.noMatch(p.debouncedQuery):p.error?.displayMessage,onAction:p.error?.retryable===true?p.retry:void 0,testID:"records-clinic-empty"}):null,jsxs(View,{style:a.footer,children:[p.loadingMore?jsxs(View,{style:a.footerLoading,testID:"records-clinic-loading-more",children:[jsx(ActivityIndicator,{color:d.color.brandInk,size:"small"}),jsx(m,{style:c.muted,children:xe.loadingMore})]}):null,p.pageError?jsx(Pressable,{onPress:p.loadMore,accessibilityRole:"button",accessibilityLabel:xe.loadMoreRetryA11y,style:a.footerRetry,testID:"records-clinic-page-error-retry",children:jsx(m,{style:a.footerRetryLabel,children:xe.loadMoreFailed})}):null]})]}),jsx(Me,{})]})}i(Om,"PickerBody");function Lm({clinic:e,onSelect:t,styles:r}){let o=Fs(e.emailStatus),n=Ns(e.distanceKm),l=[e.name,e.address,e.phone?`phone ${e.phone}`:null,n?Ms(e.distanceKm):null,o.a11y].filter(Boolean).join(", ");return jsxs(Pressable,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:xe.selectA11y(l),hitSlop:8,style:r.item,testID:`records-clinic-${e.id}`,children:[jsxs(View,{style:r.itemHeader,children:[jsx(m,{style:r.itemName,numberOfLines:1,children:e.name}),n?jsx(m,{style:r.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:n}):null]}),e.address?jsx(m,{style:r.itemAddress,numberOfLines:2,children:e.address}):null,e.phone?jsx(m,{style:r.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:e.phone}):null,jsx(View,{style:[r.badge,o.tone==="positive"?r.badgePositive:o.tone==="caution"?r.badgeCaution:r.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:[r.badgeLabel,o.tone==="positive"?r.badgePositiveText:o.tone==="caution"?r.badgeCautionText:r.badgeNeutralText],children:o.label})})]})}i(Lm,"ClinicRow");function Vm(){let e=V();return useMemo(()=>qm(e),[e])}i(Vm,"useLocalStyles");function qm(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=i((c,a,d,u="regular")=>({..._(e,u),fontSize:c,lineHeight:Math.round(c*a),color:d}),"text");return StyleSheet.create({searchBar:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.md+r.xs/2,height:r.xxl+r.md,marginHorizontal:r.lg,marginBottom:r.sm,borderRadius:o.lg+r.xs/2,backgroundColor:t.surfaceSubtle,borderWidth:l,borderColor:t.borderHairlineGreen},searchGlyph:{width:r.md,height:r.md,borderRadius:o.pill,borderWidth:2,borderColor:t.text.muted},searchInput:{flex:1,...s(n.size.body,n.lineHeight.snug,t.text.primary),paddingVertical:0},clearGlyph:s(n.size.heading,n.lineHeight.tight,t.text.muted),uploadWrap:{paddingHorizontal:r.lg,paddingBottom:r.md,gap:r.sm},list:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.md},sectionLabel:{...s(n.size.caption,n.lineHeight.normal,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:o.lg-r.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.md},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:r.md,minHeight:r.xxl+r.md},fallbackCopy:{flex:1,gap:r.xs/2},fallbackTitle:{...s(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},fallbackSubtitle:s(n.size.caption,n.lineHeight.normal,t.text.muted),fallbackForm:{gap:r.sm},item:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},itemName:{flex:1,...s(n.size.body,n.lineHeight.snug,t.brandInk,"bold")},itemDistance:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},itemAddress:s(n.size.caption,n.lineHeight.normal,t.text.primary),itemPhone:s(n.size.caption,n.lineHeight.normal,t.text.muted),badge:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+1,paddingVertical:r.xs},badgePositive:{backgroundColor:t.badgeBgPositive},badgeCaution:{backgroundColor:t.badgeBgCaution},badgeNeutral:{backgroundColor:t.badgeBgNeutral},badgeLabel:{...s(n.size.micro,n.lineHeight.snug,t.text.muted,"bold")},badgePositiveText:{color:t.success},badgeCautionText:{color:t.cautionAccent},badgeNeutralText:{color:t.text.muted},footer:{gap:r.sm,paddingTop:r.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.md},footerRetry:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...s(n.size.bodyTight,n.lineHeight.snug,t.brandInk,"bold")}})}i(qm,"makeLocalStyles");var Oe=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${Br} clinics`,sendA11y:i(e=>e===1?"Send 1 records request":`Send ${e} records requests`,"sendA11y"),send:i(e=>`Send ${e} ${e===1?"request":"requests"}`,"send"),sending:"Sending\u2026",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:i(e=>`Remove ${e}`,"remove"),emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn\u2019t send any of these requests. See the details below and try again.",partial:i((e,t,r)=>`${e} of ${t} requests sent. ${r} couldn\u2019t be sent.`,"partial"),allSent:i(e=>`${e} ${e===1?"request":"requests"} sent.`,"allSent"),responded:i((e,t)=>`${e} of ${t} ${t===1?"clinic":"clinics"} responded`,"responded")});function gn(e,t,r,o){let n={owner_name:t,pet_name:r,clinic_name:o},l=false,s=e.scopeTemplate.replace(/\{([^{}]+)\}/g,(c,a)=>Object.prototype.hasOwnProperty.call(n,a)?n[a]??"":(l=true,""));return l||/[{}]/.test(s)?null:s}i(gn,"renderClinicScope");function bn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(bn,"clinicNeedsEmail");function Nl(e,t,r){let[o,n]=useState(e.ownerName),[l,s]=useState(""),[c,a]=useState(null),[d,u]=useState(""),[p,g]=useState([]),[h,R]=useState([]),[v,x]=useState(null),[y,f]=useState(null),[E,b]=useState(false),[C,D]=useState(false),[S,k]=useState(null),[I,G]=useState(0),z=useRef(false),Y=useRef(false),H=useRef(0),Z=useRef(nr()),oe=useRef(null),Ee=useRef(null),U=useRef(0);useEffect(()=>(z.current=true,Y.current=false,b(false),()=>{z.current=false,U.current+=1,H.current+=1,oe.current=null,Ee.current?.abort();}),[t]),useEffect(()=>{let ie=true;return x(null),oe.current=null,t.getAuthorizationCopy().then(we=>{ie&&(we.ok?(x(we.value),f(null)):f(we.error));}).catch(()=>{ie&&f(q("internalError"));}),()=>{ie=false;}},[t,I]),useEffect(()=>{let ie=true;return R([]),t.recentClinics({limit:5}).then(we=>{ie&&we.ok&&R(we.value.clinics);}).catch(()=>{}),()=>{ie=false;}},[t]);let w=i(()=>{oe.current=null,f(null);},"invalidate"),T=c?.name??l.trim(),O=v?gn(v,o.trim(),e.petName,T):null,M=bn(c),X=!!(v&&O&&o.trim()&&e.petName.trim()&&T&&(!M||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.trim()))&&r),ye=i(async()=>{if(Y.current)return;let ie=++H.current;D(true);try{let we=await t.searchClinics({query:l.trim(),limit:100});if(!z.current||ie!==H.current)return;we.ok?(g(we.value.clinics),f(null)):f(we.error);}catch{z.current&&ie===H.current&&f(q("internalError"));}finally{z.current&&ie===H.current&&D(false);}},"search"),Ve=i(async()=>{if(Y.current||S||!X||!v||!O||!r)return;Y.current=true;let ie=U.current,we=i(()=>z.current&&U.current===ie,"current");b(true),f(null);try{if(!oe.current){Ee.current=new AbortController;let Xe=await r({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:T,authorizationVersion:v.authorizationVersion,scopeText:O,signal:Ee.current.signal});if(!we()||Xe===null)return;let qt=c&&(!M||c.emailStatus==="none")?{clinicId:c.id}:{clinicFreeText:T};oe.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:v.authorizationVersion,...qt,...M?{clinicEmail:d.trim().toLowerCase()}:{},...Xe.signatureId!==void 0?{signatureId:Xe.signatureId}:{signaturePngBase64:Xe.signaturePngBase64},idempotencyKey:Z.current()};}if(!we())return;let vt=await t.createClinicRequest(oe.current);if(!we())return;if(!vt.ok){f(vt.error);return}if(vt.value.petRef!==e.petRef){f(q("internalError"));return}k(vt.value),oe.current=null,e.onCreated?.(vt.value);}catch{we()&&f(q("internalError"));}finally{Y.current=false,we()&&b(false);}},"submit");return {ownerName:o,query:l,clinic:c,email:d,clinics:p,copy:v,scope:O,error:y,busy:E,searching:C,created:S,ready:X,needsEmail:M,recent:p.length===0&&c===null?h:[],setOwnerName(ie){Y.current||(w(),n(ie));},setQuery(ie){Y.current||(w(),H.current+=1,D(false),g([]),a(null),u(""),s(ie));},setEmail(ie){Y.current||(w(),u(ie));},selectClinic(ie){Y.current||(w(),H.current+=1,D(false),g([]),a(ie),s(ie.name),u(""));},invalidate:w,search:ye,submit:Ve,retryCopy(){f(null),G(ie=>ie+1);}}}i(Nl,"useClinicRequestForm");var zm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Rn(e){return e.clinic?.name??e.freeText??""}i(Rn,"draftName");function hn(e){return bn(e.clinic)}i(hn,"draftNeedsEmail");function Ml(e,t,r,o,n){let[l,s]=useState(e.ownerName),[c,a]=useState(""),[d,u]=useState([]),[p,g]=useState([]),[h,R]=useState([]),[v,x]=useState(null),[y,f]=useState(null),[E,b]=useState(false),[C,D]=useState(false),[S,k]=useState(null),[I,G]=useState(null),[z,Y]=useState(0),H=useRef(false),Z=useRef(false),oe=useRef(0),Ee=useRef(0),U=useRef(nr()),w=useRef(null),T=useRef(null);useEffect(()=>(H.current=true,Z.current=false,b(false),()=>{H.current=false,Ee.current+=1,oe.current+=1,w.current=null,T.current?.abort();}),[t,r]),useEffect(()=>{let F=true;return x(null),w.current=null,t.getAuthorizationCopy().then(Re=>{F&&(Re.ok?(x(Re.value),f(null)):f(Re.error));}).catch(()=>{F&&f(q("internalError"));}),()=>{F=false;}},[t,z]),useEffect(()=>{let F=true;return g([]),t.recentClinics({limit:5}).then(Re=>{F&&Re.ok&&g(Re.value.clinics);}).catch(()=>{}),()=>{F=false;}},[t]);let O=i(()=>{w.current=null,f(null);},"invalidate"),M=h.map(Rn),X=v?M.map(F=>gn(v,l.trim(),e.petName,F)):[],ye=X.every(F=>F!==null)?X.join(`
2
2
 
3
- `):null,Ve=h.length>0&&h.every(F=>!gn(F)||Pm.test(F.email.trim())),ie=h.length>=Nr,we=!!(v&&ye&&l.trim()&&e.petName.trim()&&Ve&&o)&&k===null,vt=i(async()=>{if(Z.current)return;let F=++oe.current;D(true);try{let Re=await t.searchClinics({query:c.trim(),limit:100});if(!G.current||F!==oe.current)return;Re.ok?(u(Re.value.clinics),b(null)):b(Re.error);}catch{G.current&&F===oe.current&&b(q("internalError"));}finally{G.current&&F===oe.current&&D(false);}},"search"),Xe=i(F=>{Z.current||ie||k!==null||F.clinic!==null&&h.some(Re=>Re.clinic?.id===F.clinic?.id)||(A(),R(Re=>[...Re,{...F,key:H.current(),idempotencyKey:H.current()}]),u([]),a(""));},"add"),Vt=i(async()=>{if(Z.current||k!==null||!we||!v||!ye||!o)return;Z.current=true;let F=Ee.current,Re=i(()=>G.current&&Ee.current===F,"current");x(true),b(null);try{if(C.current===null){T.current=new AbortController;let xt=await o({petRef:e.petRef,petName:e.petName,ownerName:l.trim(),clinicName:M.join(", "),authorizationVersion:v.authorizationVersion,scopeText:ye,signal:T.current.signal});if(!Re()||xt===null)return;if(C.current=xt,xt.signaturePngBase64!==void 0&&n!==void 0){let Vd=await n(xt.signaturePngBase64,T.current.signal);if(!Re())return;C.current={signatureId:Vd.signatureId};}}let Ft=C.current,Jr=h.map(xt=>({...xt.clinic!==null&&(!gn(xt)||xt.clinic.emailStatus==="none")?{clinicId:xt.clinic.id}:{clinicFreeText:bn(xt)},...gn(xt)?{clinicEmail:xt.email.trim().toLowerCase()}:{},...Ft.signatureId!==void 0?{signatureId:Ft.signatureId}:{signaturePngBase64:Ft.signaturePngBase64},idempotencyKey:xt.idempotencyKey})),Zr=await r.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:v.authorizationVersion,clinics:Jr});if(!Re())return;if(!Zr.ok){b(Zr.error);return}S(Zr.value),e.onCreated?.(Zr.value),qt(Zr.value.requestGroupId,F);}catch{Re()&&b(q("internalError"));}finally{Z.current=false,Re()&&x(false);}},"submit"),qt=i(async(F,Re)=>{try{let Ft=await t.getRequestGroup(F);if(!G.current||Ee.current!==Re)return;Ft.ok&&Ft.value.petRef===e.petRef&&Y(Ft.value);}catch{}},"loadGroup"),Se=i(async()=>{k===null||Z.current||await qt(k.requestGroupId,Ee.current);},"refreshGroup");return {ownerName:l,query:c,clinics:d,copy:v,scopeText:ye,error:g,busy:w,searching:E,drafts:h,outcome:k,group:I,ready:we,atCap:ie,recent:d.length===0?p.filter(F=>!h.some(Re=>Re.clinic?.id===F.id)):[],setOwnerName(F){Z.current||(A(),s(F));},setQuery(F){Z.current||(oe.current+=1,D(false),u([]),a(F));},search:vt,addClinic(F){Xe({clinic:F,freeText:null,email:""});},addFreeText(){let F=c.trim();F.length!==0&&Xe({clinic:null,freeText:F,email:""});},setDraftEmail(F,Re){Z.current||(A(),R(Ft=>Ft.map(Jr=>Jr.key===F?{...Jr,email:Re}:Jr)));},removeDraft(F){Z.current||k!==null||(A(),R(Re=>Re.filter(Ft=>Ft.key!==F)));},submit:Vt,refreshGroup:Se,retryCopy(){b(null),$(F=>F+1);}}}i(Ll,"useClinicBatchForm");function Vl(e){try{let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.port&&t.port!=="443")return !1;let r=t.hostname.toLowerCase();return r==="s3.amazonaws.com"||r.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(r)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(r)||r==="s3-accelerate.amazonaws.com"||r.endsWith(".s3-accelerate.amazonaws.com")||r==="s3-accelerate.dualstack.amazonaws.com"||r.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}i(Vl,"trustedSignatureUploadUrl");var Im="Signature upload failed",Dm=3e4;function Am(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}i(Am,"base64ByteLength");async function Di(e,t,r,o){let n=i(()=>new Error(Im),"fail"),l=Am(e);if(l<=0||r.aborted)throw n();let s=await t.initiateSignatureUpload(l);if(!s.ok||r.aborted||!Vl(s.value.uploadUrl))throw n();let c=new FormData;for(let[f,h]of Object.entries(s.value.uploadFields))c.append(f,h);c.append("file",{uri:`data:image/png;base64,${e}`,name:"signature.png",type:"image/png"});let a=new AbortController,d=i(()=>a.abort(),"onAbort");r.addEventListener("abort",d,{once:true});let u=setTimeout(d,Dm);try{if(!(await(o??fetch)(s.value.uploadUrl,{method:"POST",body:c,credentials:"omit",signal:a.signal})).ok||r.aborted)throw n()}catch{throw n()}finally{clearTimeout(u),r.removeEventListener("abort",d);}let p=await t.completeSignatureUpload(s.value.uploadId);if(!p.ok||r.aborted)throw n();return {signatureId:p.value}}i(Di,"registerRnSignature");var jr=Object.freeze({width:360,height:120});function Nl(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(Nl,"blank");function Ml(e,t,r,o){for(let n=-o;n<=o;n+=1)for(let l=-o;l<=o;l+=1){if(l*l+n*n>o*o+o)continue;let s=t+l,c=r+n;s<0||c<0||s>=e.width||c>=e.height||(e.pixels[c*e.width+s]=1);}}i(Ml,"stamp");var Om=16384;function Lm(e,t){let[r,o]=e;if(!Number.isFinite(r)||!Number.isFinite(o))return null;let n=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),l=Math.min(2*t.height,Math.max(-t.height,Math.round(o)));return [n,l]}i(Lm,"padPoint");function Vm(e,t,r,o,n){let[l,s]=t,[c,a]=r,d=Math.abs(c-l),u=-Math.abs(a-s),p=l<c?1:-1,f=s<a?1:-1,h=d+u,R=0;for(;R<n&&(Ml(e,l,s,o),R+=1,!(l===c&&s===a));){let v=2*h;v>=u&&(h+=u,l+=p),v<=d&&(h+=d,s+=f);}return R}i(Vm,"line");function Bl(e,t=1){let r=Nl(jr.width,jr.height);for(let o of e){let n=[];for(let s of o){let c=Lm(s,r);c!==null&&n.push(c);}if(n.length===0)continue;if(n.length===1){let[s,c]=n[0];Ml(r,s,c,t);continue}let l=Om;for(let s=1;s<n.length&&l>0;s+=1)l-=Vm(r,n[s-1],n[s],t,l);}return r}i(Bl,"rasterizeStrokes");var qm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",Fm="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",zm="0123456789abcdefghijklmnopqrstuv",Fi=5,zi=7,Ai=Fi+1;function Nm(e,t){let r=qm.indexOf(e);return r<0?0:zm.indexOf(Fm.charAt(r*zi+t))}i(Nm,"glyphRow");function Hl(e){let t=Nl(jr.width,jr.height),r=e.trim();if(r.length===0)return t;let o=[...r],n=4;for(;n>1&&(o.length*Ai-1)*n>t.width-8;)n-=1;let l=(o.length*Ai-1)*n,s=Math.max(0,Math.floor((t.width-l)/2)),c=Math.floor((t.height-zi*n)/2);return o.forEach((a,d)=>{let u=s+d*Ai*n;for(let p=0;p<zi;p+=1){let f=Nm(a,p);for(let h=0;h<Fi;h+=1)if((f>>Fi-1-h&1)!==0)for(let R=0;R<n;R+=1)for(let v=0;v<n;v+=1){let y=u+h*n+v,g=c+p*n+R;y<t.width&&g<t.height&&(t.pixels[g*t.width+y]=1);}}}),t}i(Hl,"rasterizeTypedName");var Hi=class Hi{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let o=0;for(let n=0;n<r;n+=1)o=o<<1|t>>n&1;this.writeBits(o,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(Hi,"BitWriter");var Ni=Hi;function Mi(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i(Mi,"writeLiteral");var Oi=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],ql=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Li=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Fl=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function Mm(e,t,r){let o=Oi.length-1;for(;Oi[o]>t;)o-=1;Mi(e,257+o),ql[o]>0&&e.writeBits(t-Oi[o],ql[o]);let n=Li.length-1;for(;Li[n]>r;)n-=1;e.writeCode(n,5),Fl[n]>0&&e.writeBits(r-Li[n],Fl[n]);}i(Mm,"writeMatch");var Bm=32768,Vi=3,Hm=258,zl=15,Um=64;function jm(e){let t=new Ni;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<zl).fill(-1),o=new Int32Array(e.length).fill(-1),n=i(c=>(e[c]<<10^e[c+1]<<5^e[c+2])&(1<<zl)-1,"hashAt"),l=i(c=>{if(c+Vi>e.length)return;let a=n(c);o[c]=r[a],r[a]=c;},"insert"),s=0;for(;s<e.length;){let c=0,a=0;if(s+Vi<=e.length){let d=r[n(s)],u=0,p=Math.min(Hm,e.length-s);for(;d>=0&&u<Um&&s-d<=Bm;){let f=0;for(;f<p&&e[d+f]===e[s+f];)f+=1;if(f>c&&(c=f,a=s-d,f===p))break;d=o[d],u+=1;}}if(c>=Vi){Mm(t,c,a);for(let d=0;d<c;d+=1)l(s+d);s+=c;}else Mi(t,e[s]),l(s),s+=1;}return Mi(t,256),t.finish()}i(jm,"deflate");function $m(e){let t=1,r=0;for(let o of e)t=(t+o)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i($m,"adler32");var so=null;function Wm(e){if(so===null){so=new Uint32Array(256);for(let r=0;r<256;r+=1){let o=r;for(let n=0;n<8;n+=1)o=o&1?3988292384^o>>>1:o>>>1;so[r]=o>>>0;}}let t=4294967295;for(let r of e)t=so[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(Wm,"crc32");function hn(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(hn,"u32");function qi(e,t){let r=Uint8Array.from([...e].map(n=>n.charCodeAt(0))),o=new Uint8Array(r.length+t.length);return o.set(r,0),o.set(t,r.length),[...hn(t.length),...o,...hn(Wm(o))]}i(qi,"chunk");var lo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Gm(e){let t="";for(let r=0;r<e.length;r+=3){let o=e[r],n=r+1<e.length?e[r+1]:0,l=r+2<e.length?e[r+2]:0,s=o<<16|n<<8|l;t+=lo.charAt(s>>18&63)+lo.charAt(s>>12&63),t+=r+1<e.length?lo.charAt(s>>6&63):"=",t+=r+2<e.length?lo.charAt(s&63):"=";}return t}i(Gm,"toBase64");function Bi(e){let{width:t,height:r,pixels:o}=e,n=Math.ceil(t/8)+1,l=new Uint8Array(n*r);for(let u=0;u<r;u+=1){let p=u*n;l[p]=0,l.fill(255,p+1,p+n);for(let f=0;f<t;f+=1)if(o[u*t+f]===1){let h=p+1+(f>>3);l[h]=l[h]&~(128>>(f&7));}}let s=jm(l),c=new Uint8Array(2+s.length+4);c[0]=120,c[1]=1,c.set(s,2),c.set(hn($m(l)),2+s.length);let a=Uint8Array.from([...hn(t),...hn(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...qi("IHDR",a),...qi("IDAT",c),...qi("IEND",new Uint8Array(0))]);return Gm(d)}i(Bi,"encodeSignaturePng");var Xm=8,$l=2,Rn=3;function Lr({onChange:e,disabled:t=false}){let r=Jm(),[o,n]=useState("draw"),[l,s]=useState(""),[c,a]=useState([]),[d,u]=useState(0),p=useRef([]),f=useRef(null),h=d>0?jr.width/d:1,R=useRef(h);R.current=h;let v=useRef(t);v.current=t,useEffect(()=>{if(o==="type"){jn(e,l.trim().length>0?Bi(Hl(l)):null);return}let E=c.reduce((D,k)=>D+k.length,0);jn(e,E>=Xm?Bi(Bl(c)):null);},[o,l,c,e]);let y=i(E=>{let{locationX:D,locationY:k}=E.nativeEvent;return [D*R.current,k*R.current]},"point"),g=useMemo(()=>PanResponder.create({onStartShouldSetPanResponder:i(()=>!v.current,"onStartShouldSetPanResponder"),onMoveShouldSetPanResponder:i(()=>!v.current,"onMoveShouldSetPanResponder"),onPanResponderTerminationRequest:i(()=>false,"onPanResponderTerminationRequest"),onPanResponderGrant:i(E=>{p.current=[y(E)];},"onPanResponderGrant"),onPanResponderMove:i(E=>{let D=y(E),k=p.current[p.current.length-1];k!==void 0&&Math.abs(k[0]-D[0])<$l&&Math.abs(k[1]-D[1])<$l||(p.current=[...p.current,D],a(S=>[...S.filter(I=>I!==f.current),f.current=p.current]));},"onPanResponderMove"),onPanResponderRelease:i(()=>{let E=p.current;p.current=[],a(D=>[...D.filter(k=>k!==f.current),E]),f.current=null;},"onPanResponderRelease"),onPanResponderTerminate:i(()=>{let E=p.current;p.current=[],a(D=>[...D.filter(k=>k!==f.current),E]),f.current=null;},"onPanResponderTerminate")}),[]),b=useCallback(()=>{v.current||(p.current=[],f.current=null,a([]),s(""));},[]),w=useCallback(()=>{b(),n(E=>E==="draw"?"type":"draw");},[b]),x=i(E=>u(E.nativeEvent.layout.width),"onLayout");return jsxs(View,{style:r.container,testID:"records-signature-pad",children:[jsx(m,{style:r.label,children:o==="draw"?U.draw:U.type}),o==="type"?jsx(qe,{accessibilityLabel:U.type,style:r.input,value:l,maxLength:100,editable:!t,autoComplete:"off",autoCorrect:false,onChangeText:E=>{v.current||s(E);}}):null,jsx(View,{onLayout:x,style:[r.canvas,{height:d>0?d/3:120}],accessible:true,accessibilityLabel:U.sign,accessibilityRole:"image",testID:"records-signature-canvas",...o==="draw"?g.panHandlers:{},children:o==="type"?jsx(m,{style:r.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:l.trim()}):c.map((E,D)=>E.map(([k,S],I)=>jsx(View,{pointerEvents:"none",style:[r.dot,{left:k/h-Rn/2,top:S/h-Rn/2}]},`${D}-${I}`)))}),jsxs(View,{style:r.actions,children:[jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:U.clear,accessibilityState:{disabled:t},disabled:t,onPress:b,style:r.button,children:jsx(m,{style:r.buttonLabel,children:U.clear})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:o==="draw"?U.toType:U.toDraw,accessibilityState:{disabled:t},disabled:t,onPress:w,style:r.button,children:jsx(m,{style:r.buttonLabel,children:o==="draw"?U.toType:U.toDraw})})]})]})}i(Lr,"SignaturePad");function Jm(){let e=L();return useMemo(()=>Zm(e),[e])}i(Jm,"useStyles");function Zm(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({container:{gap:r.sm},label:{..._(e,"regular"),fontSize:n.size.body,color:t.text.primary},input:{minHeight:44,padding:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,..._(e,"regular"),fontSize:n.size.body},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,overflow:"hidden",justifyContent:"center"},dot:{position:"absolute",width:Rn,height:Rn,borderRadius:Rn/2,backgroundColor:"#111111"},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:"#111111",paddingHorizontal:r.md},actions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},button:{minHeight:44,paddingHorizontal:r.md,justifyContent:"center",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,backgroundColor:t.surface},buttonLabel:{..._(e,"regular"),fontSize:n.size.body,color:t.text.primary}})}i(Zm,"makeStyles");function ji(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,U.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsx(ry,{...Fe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(ji,"EverfurClinicRequestBatch");function ry(e){let t=Nt(),r=mi(),o=e.controller??t,[n,l]=useState(null),s=useCallback(async()=>n===null?null:{signaturePngBase64:n},[n]),c=useCallback((y,g)=>Di(y,o,g),[o]),a=Ll(e,o,e.batchClient??r,e.onCaptureSignature??s,e.onCaptureSignature?void 0:c),d=e.onCaptureSignature!==void 0||n!==null,u=L(),p={minHeight:44,padding:u.space.sm,borderWidth:1,borderColor:u.color.borderHairlineGreen,borderRadius:u.radius.sm,color:u.color.text.primary,backgroundColor:u.color.surface},f={color:u.color.text.primary,fontSize:u.type.size.body},h={color:u.color.text.muted,fontSize:u.type.size.bodyTight},R=i((y,g,b=false,w=y)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:w,accessibilityState:{disabled:b},disabled:b,onPress:g,style:[p,{justifyContent:"center",opacity:b?.5:1}],children:jsx(m,{style:f,children:y})}),"button"),v=a.busy?Oe.sending:a.drafts.length===0?Oe.addToContinue:a.error?Oe.tryAgain:Oe.send(a.drafts.length);return jsxs(View,{accessibilityLabel:a.outcome?Oe.resultTitle:Oe.title,style:[{backgroundColor:u.color.surface,padding:u.space.lg,gap:u.space.md,borderRadius:u.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[f,{..._(u,"bold"),fontSize:u.type.size.heading}],children:a.outcome?Oe.resultTitle:Oe.title}),jsx(m,{style:f,children:e.petName}),a.outcome?jsxs(View,{style:{gap:u.space.sm},testID:"records-batch-result",children:[jsx(m,{accessibilityRole:"summary",accessibilityLiveRegion:"polite",style:f,children:a.outcome.createdCount===0?Oe.allFailed:a.outcome.failedCount>0?Oe.partial(a.outcome.createdCount,a.outcome.results.length,a.outcome.failedCount):Oe.allSent(a.outcome.createdCount)}),jsx(m,{accessibilityRole:"header",style:f,children:Oe.perClinic}),a.outcome.results.map((y,g)=>{let b=y.request?.clinicName??a.drafts[g]?.clinic?.name??y.clinicFreeText??"",w=y.created?Oe.sent:Oe.notSent;return jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:[`${b}. ${w}.`,y.created?y.request?.statusLabel:y.failureReason].filter(Boolean).join(" "),testID:`records-batch-row-${y.created?"created":"failed"}`,children:[jsx(m,{style:f,children:b}),jsx(m,{style:h,children:w}),y.created&&y.request?.statusLabel?jsx(m,{style:h,children:y.request.statusLabel}):null,!y.created&&y.failureReason?jsx(m,{style:h,children:y.failureReason}):null]},y.idempotencyKey)}),a.group?jsx(m,{accessibilityLiveRegion:"polite",style:f,children:Oe.responded(a.group.responded,a.group.total)}):null,a.group?.members.map(y=>y.statusLabel?jsx(m,{style:h,children:[y.clinicName,y.statusLabel].filter(Boolean).join(": ")},y.id):null)]}):jsxs(Fragment,{children:[jsx(m,{style:f,children:U.ownerName}),jsx(qe,{accessibilityLabel:U.ownerName,style:p,value:a.ownerName,maxLength:200,editable:!a.busy,autoComplete:"name",onChangeText:a.setOwnerName}),a.drafts.map(y=>jsxs(View,{style:{gap:u.space.xs},testID:`records-batch-draft-${y.key}`,children:[jsx(m,{style:f,children:bn(y)}),gn(y)?jsxs(Fragment,{children:[jsx(m,{style:h,children:y.email.trim()?y.email:Oe.emailToAdd}),jsx(qe,{accessibilityLabel:U.email,style:p,value:y.email,placeholder:U.emailPlaceholder,placeholderTextColor:u.color.text.placeholder,maxLength:320,editable:!a.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:g=>a.setDraftEmail(y.key,g)})]}):null,R(Oe.remove(bn(y)),()=>a.removeDraft(y.key),a.busy)]},y.key)),jsx(m,{style:f,children:a.atCap?Oe.atCap:Oe.addClinic}),!a.atCap&&jsxs(Fragment,{children:[jsx(qe,{accessibilityLabel:U.clinic,style:p,value:a.query,placeholder:U.placeholder,placeholderTextColor:u.color.text.placeholder,maxLength:200,editable:!a.busy,onChangeText:a.setQuery}),R(U.search,()=>{a.search();},a.busy||a.searching||a.query.trim().length<2),a.query.trim().length>0&&a.clinics.length===0&&!a.searching&&R(Oe.addClinic,a.addFreeText,a.busy),a.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:f,children:ce.loading}),a.recent.length>0&&jsx(m,{accessibilityRole:"header",style:f,children:U.recentlyUsed}),a.recent.map(y=>jsx(View,{children:R([y.name,y.address,y.phone].filter(Boolean).join(", "),()=>a.addClinic(y),a.busy)},`recent-${y.id}`)),a.clinics.map(y=>jsx(View,{children:R([y.name,y.address,y.phone].filter(Boolean).join(", "),()=>a.addClinic(y),a.busy)},y.id))]}),jsx(m,{accessibilityRole:"header",style:f,children:U.scopeHeading}),a.copy?jsx(m,{style:f,children:a.drafts.length>0&&a.ownerName.trim()?a.scopeText??q("internalError").displayMessage:ce.consentRequired}):!a.error&&jsx(m,{accessibilityLiveRegion:"polite",style:f,children:ce.loading}),!e.onCaptureSignature&&jsx(Lr,{onChange:l,disabled:a.busy}),!d&&jsx(m,{accessibilityRole:"alert",style:f,children:U.missingSignature}),a.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:f,children:a.error.displayMessage}),!a.copy&&a.error&&R(ce.retry,a.retryCopy),R(v,()=>{a.submit();},a.busy||!a.ready||!d,Oe.sendA11y(a.drafts.length))]}),e.onClose&&R(U.cancel,e.onClose,a.busy),jsx(Me,{})]})}i(ry,"BatchBody");var se=Object.freeze({scopeHeading:"What you\u2019re authorizing",scopeBody:"You\u2019re asking your pet\u2019s clinic to release their medical records to Everfur, on your behalf, so we can organize them for you.",whatWeDo:Object.freeze(["We email the clinic a signed copy of this authorization.","When records arrive, our team reviews them before they appear in your app.","You can revoke this request at any time."]),retentionNote:"We keep the records you receive so you always have them. See our Privacy Policy for how records are stored and used.",authorizeLabel:i((e,t)=>`I authorize ${t} to release ${He(e)}\u2019s records to Everfur.`,"authorizeLabel"),missingSignatureError:"Please add your signature before submitting.",missingDraftError:"Something went wrong with your selection. Please go back and pick the clinic again.",newClinicDirectSendNote:"We\u2019ll email this clinic directly to request your pet\u2019s medical records. Clinics usually reply within a week.",titleFreeText:"Confirm your request",titleDirectory:"Authorize records release",noEmailNote:i((e,t)=>`We don\u2019t have an email on file for ${t}. Add it so we can request ${He(e)}\u2019s records.`,"noEmailNote"),emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",emailRequired:"Enter the clinic email before sending the request.",reuseSignature:"Reuse a previous signature",reuseHint:"\u2026or sign again below",reuseTileA11y:"Use this earlier signature",reuseTileSelectedA11y:"Earlier signature, selected",signType:"Type your name to sign",signDraw:"Sign with your finger",clear:"Clear",clearA11y:"Clear signature",fullName:"Your full name",fullNamePlaceholder:"Jane Doe",toType:"Can\u2019t draw? Type your name instead",toTypeA11y:"Can\u2019t draw? Type your name to sign instead",toDraw:"Draw your signature instead",signatureHint:i(e=>`Your signature is added to the authorization sent to ${e}.`,"signatureHint"),submit:"Authorize & send request",submitting:"Submitting\u2026",submitA11y:"Submit authorization"});var ny="value_text",Kl=64,Ql=512;function Xl(e){return e!==null&&e.httpStatus===409&&!tr(e)}i(Xl,"isFactReviewerLocked");var vn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:ny}),Jl=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,Zl=/^\d{4}-\d{2}-\d{2}$/;function ec(e){if(e==null)return "text";let t=e.trim();return Jl.test(t)?"num":Zl.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(ec,"inferFactValueKind");function $i(e,t){let r=t.trim(),o=ec(e);if(o==="num"&&Jl.test(r)){let n=Number(r);if(Number.isFinite(n))return Object.freeze({[vn.num]:n})}return o==="date"&&Zl.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[vn.date]:r}):Object.freeze(o==="bool"&&(r==="true"||r==="false")?{[vn.bool]:r==="true"}:{[vn.text]:r})}i($i,"factCorrectionFor");var Ie=z.string().nullish(),mo=z.number().nullish(),oy=z.object({collected_at:Ie,at:Ie,value:mo,unit:Ie,qualitative_result:Ie,ref_low:mo,ref_high:mo,status:Ie,source_clinic:Ie,source_doc_id:Ie,doc_id:Ie,reviewed:z.boolean().nullish()}),iy=z.object({collected_at:Ie,at:Ie,value:mo,unit:Ie,qualitative_result:Ie,status:Ie}),ay=z.object({marker_id:z.string().min(1),canonical_name:Ie,name:Ie,loinc_code:Ie,canonical_unit:Ie,unit:Ie,panel_name:Ie,panel:Ie,meaning_text:Ie,meaning:Ie,latest:iy.nullish(),trajectory:Ie,points:z.array(oy).optional()}),sy=z.object({total_markers:z.number().int().nonnegative(),in_range_count:z.number().int().nonnegative(),out_of_range_count:z.number().int().nonnegative(),unknown_count:z.number().int().nonnegative()}),ly=z.object({markers:z.array(ay).optional(),summary:sy.nullish(),disclaimer:z.string().optional(),featured_marker_id:Ie});function cy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(cy,"isObject");function tc(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(tc,"withheldMarkers");function rc(e,t){let r=cy(t)?t:{},o=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return tc(o);let n=ly.safeParse(r);if(!n.success)return tc(o);let l=n.data,s=i(a=>Object.freeze({at:a.collected_at??a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,sourceClinic:a.source_clinic??null,docId:a.source_doc_id??a.doc_id??null,reviewed:a.reviewed===true}),"point"),c=(l.markers??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.canonical_name??a.name??a.marker_id,loincCode:a.loinc_code??null,unit:a.canonical_unit??a.unit??null,panel:a.panel_name??a.panel??null,meaning:a.meaning_text??a.meaning??null,latest:a.latest?Object.freeze({at:a.latest.collected_at??a.latest.at??null,value:a.latest.value??null,unit:a.latest.unit??null,qualitativeResult:a.latest.qualitative_result??null,status:a.latest.status??null}):null,trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(s))}));return Object.freeze({petRef:o,withheld:false,markers:Object.freeze(c),summary:l.summary?Object.freeze({totalMarkers:l.summary.total_markers,inRangeCount:l.summary.in_range_count,outOfRangeCount:l.summary.out_of_range_count,unknownCount:l.summary.unknown_count}):null,disclaimer:l.disclaimer??"",featuredMarkerId:l.featured_marker_id??null})}i(rc,"mapRecordMarkers");var dy=z.string().min(1).refine(e=>e.startsWith("https://")),xn=z.string().nullish(),uy=z.object({share_id:z.string().min(1),share_url:z.string().min(1),expires_at:xn}),py=z.object({shares:z.array(z.object({share_id:z.string().min(1),expires_at:xn,created_at:xn,view_count:z.number().int().nonnegative().nullish(),last_viewed_at:xn})).optional()}),my=z.object({download_url:dy,expires_at:xn});function yy(e,t){let r=e.trim();if(r.length===0)return null;try{let o=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return o===null||o.protocol!=="https:"?null:o.toString()}catch{return null}}i(yy,"resolveShareUrl");function nc(e,t){let r=uy.safeParse(e);if(!r.success)return null;let o=yy(r.data.share_url,t);return o===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:o,expiresAt:r.data.expires_at??null})}i(nc,"mapRecordShareLink");function oc(e){let t=py.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null}))):null}i(oc,"mapRecordShareList");function ic(e){let t=my.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(ic,"mapRecordPdfLink");var fy=z.object({signatures:z.array(z.object({signature_id:z.string().min(1),preview_url:z.string().min(1).refine(e=>e.startsWith("https://")),created_at:z.string().nullish()})).optional()});function ac(e){let t=fy.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(ac,"mapSignatureSuggestions");var N=z.string().nullish(),wn=z.number().nullish(),gy=z.object({at:N,value:wn,unit:N,qualitative_result:N,ref_low:wn,ref_high:wn,status:N,doc_id:N}),by=z.object({marker_id:z.string(),name:z.string(),loinc_code:N,unit:N,panel:N,meaning:N,latest:z.object({at:N,value:wn,unit:N,qualitative_result:N,status:N}).nullish(),trajectory:N,points:z.array(gy).optional()}),hy=z.object({encounter_id:z.string(),date:N,type:N,clinic_name:N,veterinarian:N,doc_id:N}),Ry=z.object({note_id:z.string(),encounter_id:N,observed_on:N,sections:z.array(z.object({section:z.string(),text:z.string()})).optional()}),vy=z.object({exam_id:z.string(),encounter_id:N,observed_on:N,doc_id:N,systems:z.record(z.object({finding_status:N,finding:N})).optional()}),xy=z.object({has_lab_history:z.boolean().optional(),has_vaccination_history:z.boolean().optional(),has_weight_history:z.boolean().optional(),has_vitals_history:z.boolean().optional(),has_physical_exam_history:z.boolean().optional(),has_procedure_history:z.boolean().optional(),has_genetic_history:z.boolean().optional(),has_reproductive_history:z.boolean().optional(),has_parasite_prevention_history:z.boolean().optional(),earliest_record_at:N,latest_record_at:N,documents_ingested:z.number().int().nonnegative().optional(),documents_in_review:z.number().int().nonnegative().optional(),entities_pending_review:z.record(z.number().int().nonnegative()).optional(),held_total:z.number().int().nonnegative().optional()}),wy=z.object({conflict_id:z.string(),entity_type:z.string(),field:N,severity:N,candidates:z.array(z.object({value:z.string(),source_doc_id:N,doc_id:N,collected_at:N})).optional()}),Cy=z.object({lab_results:z.array(by).optional(),encounters:z.array(hy).optional(),clinician_notes:z.array(Ry).optional(),physical_exams:z.array(vy).optional(),completeness:xy.nullish(),conflicts:z.array(wy).optional()}),Ey=z.object({visits:z.array(z.object({visit_id:z.string(),visit_date:N,veterinarian:N,summary:N,doc_id:N})),vaccines:z.array(z.object({vaccine_id:z.string(),product:N,lot:N,administered_on:N,expires_on:N,doc_id:N})),weights:z.array(z.object({weight_id:z.string(),observed_on:N,weight_kg:wn,doc_id:N})),medications:z.array(z.object({medication_id:z.string(),drug_name:N,dose:N,route:N,frequency:N,sig:N,rx_number:N,started_on:N,stopped_on:N,doc_id:N})),disclaimer:z.string().optional()}),Sy=z.object({document:Mo,contributions:z.array(No),contribution_count:z.number().int().nonnegative().optional()});function Gi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Gi,"isObject");function Yi(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Yi,"petOf");function Wi(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(Wi,"emptyDepth");function ky(e,t){let r=Gi(t)?t:{},o=Yi(r,e);if(r.withheld===true)return Wi(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Wi(o,false);let l=Cy.safeParse(r);if(!l.success)return Wi(o,true);let s=l.data,c=i(a=>Object.freeze({at:a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,docId:a.doc_id??null}),"point");return Object.freeze({petRef:o,available:true,withheld:false,labResults:Object.freeze((s.lab_results??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.name,loincCode:a.loinc_code??null,unit:a.unit??null,panel:a.panel??null,meaning:a.meaning??null,latest:Object.freeze({at:a.latest?.at??null,value:a.latest?.value??null,unit:a.latest?.unit??null,qualitativeResult:a.latest?.qualitative_result??null,status:a.latest?.status??null}),trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(c))}))),encounters:Object.freeze((s.encounters??[]).map(a=>Object.freeze({encounterId:a.encounter_id,date:a.date??null,type:a.type??null,clinicName:a.clinic_name??null,veterinarian:a.veterinarian??null,docId:a.doc_id??null}))),clinicianNotes:Object.freeze((s.clinician_notes??[]).map(a=>Object.freeze({noteId:a.note_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,sections:Object.freeze((a.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((s.physical_exams??[]).map(a=>Object.freeze({examId:a.exam_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,docId:a.doc_id??null,systems:Object.freeze(Object.entries(a.systems??{}).map(([d,u])=>Object.freeze({system:d,findingStatus:u.finding_status??null,finding:u.finding??null})))}))),completeness:s.completeness?Object.freeze({hasLabHistory:s.completeness.has_lab_history===true,hasVaccinationHistory:s.completeness.has_vaccination_history===true,hasWeightHistory:s.completeness.has_weight_history===true,hasVitalsHistory:s.completeness.has_vitals_history===true,hasPhysicalExamHistory:s.completeness.has_physical_exam_history===true,hasProcedureHistory:s.completeness.has_procedure_history===true,hasGeneticHistory:s.completeness.has_genetic_history===true,hasReproductiveHistory:s.completeness.has_reproductive_history===true,hasParasitePreventionHistory:s.completeness.has_parasite_prevention_history===true,earliestRecordAt:s.completeness.earliest_record_at??null,latestRecordAt:s.completeness.latest_record_at??null,documentsIngested:s.completeness.documents_ingested??0,documentsInReview:s.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...s.completeness.entities_pending_review??{}}),heldTotal:s.completeness.held_total??0}):null,conflicts:Object.freeze((s.conflicts??[]).map(a=>Object.freeze({conflictId:a.conflict_id,entityType:a.entity_type,field:a.field??null,severity:a.severity??"needs_review",candidates:Object.freeze((a.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(ky,"mapRecordDepth");function sc(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(sc,"withheldTimeline");function Ty(e,t){let r=Gi(t)?t:{},o=Yi(r,e);if(r.withheld===true)return sc(o);let n=Ey.safeParse(r);if(!n.success)return sc(o);let l=n.data,s=l.visits.map(u=>Object.freeze({visitId:u.visit_id,visitDate:u.visit_date??null,veterinarian:u.veterinarian??null,summary:u.summary??null,docId:u.doc_id??null})),c=l.vaccines.map(u=>Object.freeze({vaccineId:u.vaccine_id,product:u.product??null,lot:u.lot??null,administeredOn:u.administered_on??null,expiresOn:u.expires_on??null,docId:u.doc_id??null})),a=l.weights.map(u=>Object.freeze({weightId:u.weight_id,observedOn:u.observed_on??null,weightKg:u.weight_kg??null,docId:u.doc_id??null})),d=l.medications.map(u=>Object.freeze({medicationId:u.medication_id,drugName:u.drug_name??null,dose:u.dose??null,route:u.route??null,frequency:u.frequency??null,sig:u.sig??null,rxNumber:u.rx_number??null,startedOn:u.started_on??null,stoppedOn:u.stopped_on??null,docId:u.doc_id??null}));return Object.freeze({petRef:o,withheld:false,isEmpty:s.length===0&&c.length===0&&a.length===0&&d.length===0,visits:Object.freeze(s),vaccines:Object.freeze(c),weights:Object.freeze(a),medications:Object.freeze(d),disclaimer:l.disclaimer??""})}i(Ty,"mapRecordsTimeline");function _y(e,t){let r=Gi(t)?t:{},o=Yi(r,e),n=i(()=>Object.freeze({petRef:o,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return n();let l=Sy.safeParse(r);if(!l.success)return n();let s=Object.freeze(l.data.contributions.map(Bo));return Object.freeze({petRef:o,withheld:false,document:Ho(l.data.document),contributions:s,contributionCount:l.data.contribution_count??s.length})}i(_y,"mapDocumentContributions");var Py="/widget/v1/records/pets";function lc(e){let t=e.funnel??mr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!yr(a)&&[...a].length<=d,"segment"),o=i(async(a,d,u,p)=>{if(!r(d,mt))return Rr();let f=await t.send(a,{method:"GET",path:u});if(!f.ok)return f;let h=p(f.value);return h.petRef===d?_e(h):B(q("internalError",{retryable:false}))},"read"),n=i(a=>`${Py}/${encodeURIComponent(a)}`,"pet"),l=i(a=>`${n(a)}/everfur_record`,"record"),s=i(async(a,d,u)=>{let p=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!p.ok)return p;let f=u(p.value);return f===null?B(q("internalError",{retryable:false})):_e(f)},"parsed"),c=i((a,d)=>!r(a.entityType,Kl)||!r(a.canonicalKey,Ql)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,tn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:a.entityType,canonical_key:a.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...a.idempotencyKey!==void 0?{idempotency_key:a.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(a=>o("records.depth.record",a,`${n(a)}/record`,d=>ky(a,d)),"getRecordDepth"),getTimeline:i(a=>o("records.depth.timeline",a,`${n(a)}/timeline`,d=>Ty(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?o("records.depth.contributions",a,`${n(a)}/documents/${encodeURIComponent(d)}/contributions`,u=>_y(a,u)):Rr()},getMarkers:i(a=>o("records.depth.markers",a,`${n(a)}/markers`,d=>rc(a,d)),"getMarkers"),createShare(a){return r(a,mt)?s("records.share.create",{method:"POST",path:`${l(a)}/share`},d=>nc(d,e.apiBaseUrl)):Rr()},listShares(a){return r(a,mt)?s("records.share.list",{method:"GET",path:`${l(a)}/shares`},oc):Rr()},async revokeShare(a,d){if(!r(a,mt)||!r(d,64))return Rr();let u=await t.send("records.share.revoke",{method:"DELETE",path:`${l(a)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return u.ok?_e(void 0):u},getPdfLink(a){return r(a,mt)?s("records.pdf.link",{method:"GET",path:`${l(a)}/pdf-link`},ic):Rr()},async editFact(a,d){let u=r(a,mt)?c(d,d.correctedFields):null;if(u===null)return Rr();let p=await t.send("records.fact.edit",{method:"POST",path:`${l(a)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?_e(void 0):p},async removeFact(a,d){let u=r(a,mt)?c(d):null;if(u===null)return Rr();let p=await t.send("records.fact.remove",{method:"POST",path:`${l(a)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?_e(void 0):p},listAuthorizationSignatures:i(()=>s("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},ac),"listAuthorizationSignatures")}}i(lc,"createRecordsDepthClient");function Rr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(Rr,"invalid");function sr(){let{runtime:e,userRef:t,scopeEpoch:r}=ke();return useMemo(()=>{let{services:o}=e.registry;return lc({auth:o.authFor(t),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,t,r])}i(sr,"useEverfurRecordsDepthClient");function Ut(e,t,r,o=""){let n=sr(),{userRef:l}=ke(),s=Mn(e),c=useMemo(()=>({}),[n,e,o,s]),[a,d]=useState({scope:c,value:null,error:null,loading:true}),u=useRef(0),p=useCallback(async()=>{let g=u.current+=1;if(d({scope:c,value:null,error:null,loading:true}),l===null){d({scope:c,value:null,error:null,loading:false});return}let b=await t(n,e);g===u.current&&(b.ok?d({scope:c,value:b.value,error:null,loading:false}):d({scope:c,value:null,error:b.error,loading:false}));},[n,e,t,c,l]);useEffect(()=>(p(),()=>{u.current+=1;}),[p]);let f=a.scope===c?a:{value:null,error:null,loading:true},h=useCallback(()=>{p();},[p]),R=f.error===null||f.error.httpStatus!==404,v=R?f.error:null,y=f.loading?"loading":v!==null?"error":f.value===null?"empty":f.value.withheld?"populated":r(f.value)?"empty":"populated";return useMemo(()=>({status:y,value:f.value,error:v,available:R,refresh:h}),[y,f.value,v,R,h])}i(Ut,"useRecordsDepthRead");function vr(e){return e!==null&&e.httpStatus===404}i(vr,"isDarkRouteError");var Ly=i((e,t)=>e.getMarkers(t),"readMarkers"),Vy=i(e=>e.markers.length===0,"markersEmpty");function Qi(e){let t=Ut(e,Ly,Vy);return useMemo(()=>{let r=t.available&&t.value!==null&&!t.value.withheld?t.value:null;return {status:t.status,markers:r,available:t.available,error:t.error,refresh:t.refresh}},[t])}i(Qi,"useRecordsMarkers");var qy=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function uc(e){let{clinic:t,controller:r,depthClient:o,capture:n,onCreated:l}=e,s=t.clinic?.name??t.freeText??"",c=t.clinic===null,[a,d]=useState(false),[u,p]=useState(e.ownerName),[f,h]=useState(t.email),[R,v]=useState(false),[y,g]=useState(null),[b,w]=useState(null),[x,E]=useState(0),[D,k]=useState(null),[S,I]=useState(false),[Y,z]=useState(null),[$,G]=useState([]),[Z,oe]=useState(null),[Ee,H]=useState(false),C=useRef(false),T=useRef(true),A=useRef(rr()),M=useRef(null);useEffect(()=>(T.current=true,()=>{T.current=false,M.current=null;}),[r]),useEffect(()=>{let Se=true;return g(null),M.current=null,r.getAuthorizationCopy().then(F=>{Se&&(F.ok?(g(F.value),w(null)):w(F.error));}).catch(()=>{Se&&w(q("internalError"));}),()=>{Se=false;}},[r,x]),useEffect(()=>{if(o===void 0)return;let Se=true;return o.listAuthorizationSignatures().then(F=>{Se&&(F.ok?G(F.value):vr(F.error)||G([]));}).catch(()=>{}),()=>{Se=false;}},[o]);let K=fn(t.clinic),ye=f.trim().toLowerCase(),Ve=qy.test(ye),ie=K&&(R||ye.length>0)&&!Ve?se.emailRequired:null,we=y?yn(y,u.trim(),He(e.petName),s):null,vt=e.hostCapture===true||Ee||Z!==null,Xe=!!(a&&y&&we&&u.trim()&&s&&vt&&(!K||Ve)),Vt=useCallback(async()=>{if(!(C.current||Y!==null||!y||!we)){if(!s){k(se.missingDraftError);return}if(K&&!Ve){v(true),k(se.emailRequired);return}if(!(!a||!u.trim())){C.current=true,I(true),k(null);try{if(M.current===null){let F=Z!==null?{signatureId:Z}:await n();if(!T.current)return;if(F===null){k(se.missingSignatureError);return}let Re=t.clinic&&(!K||t.clinic.emailStatus==="none")?{clinicId:t.clinic.id}:{clinicFreeText:s};M.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:y.authorizationVersion,...Re,...K?{clinicEmail:ye}:{},...F.signatureId!==void 0?{signatureId:F.signatureId}:{signaturePngBase64:F.signaturePngBase64},idempotencyKey:A.current()};}let Se=await r.createClinicRequest(M.current);if(!T.current)return;if(!Se.ok){k(Se.error.displayMessage);return}if(Se.value.petRef!==e.petRef){k(q("internalError").displayMessage);return}z(Se.value),M.current=null,l?.(Se.value);}catch{T.current&&k(q("internalError").displayMessage);}finally{C.current=false,T.current&&I(false);}}}},[a,n,t.clinic,s,r,y,Y,e.petRef,K,ye,l,u,Z,we,Ve]),qt=useCallback(()=>{M.current=null,k(null);},[]);return {title:c?se.titleFreeText:se.titleDirectory,clinicName:s,isFreeText:c,authorized:a,ownerName:u,email:f,emailError:ie,needsEmail:K,directoryClinicNoEmail:K&&t.clinic!==null,copy:y,copyError:b,scope:we,error:D,busy:S,created:Y,ready:Xe,signatures:$,reuseSignatureId:Z,hasSignature:vt,setAuthorized(Se){C.current||(qt(),d(Se));},setOwnerName(Se){C.current||(qt(),p(Se));},setEmail(Se){C.current||(qt(),v(false),h(Se));},setSigned(Se){C.current||(qt(),H(Se),Se&&oe(null));},pickReuseSignature(Se){C.current||(qt(),oe(Se));},retryCopy(){w(null),E(Se=>Se+1);},submit:Vt}}i(uc,"useRecordsConsentForm");function Zi(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",style:e.style,...Be(e.onBack,Ze),children:t===null?jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsx(By,{...Fe(e,["onCreated","onNavigate","onBack"])},JSON.stringify([t,r,e.petRef,e.clinic.key]))})}i(Zi,"EverfurRecordsConsent");function By({petRef:e,petName:t,clinic:r,ownerName:o,onCaptureSignature:n,onCreated:l,controller:s,onNavigate:c,onBack:a,style:d}){let u=be(),p=Hy(),f=L(),h=Nt(),R=sr(),[v,y]=useState(null),[g,b]=useState("draw"),w=useCallback(async()=>v===null?null:{signaturePngBase64:v},[v]),x=uc({petRef:e,petName:t,ownerName:o??"",clinic:r,controller:s??h,depthClient:R,capture:n?()=>n({petRef:e,petName:He(t),ownerName:x.ownerName,clinicName:x.clinicName,authorizationVersion:x.copy?.authorizationVersion??"",scopeText:x.scope??"",signal:new AbortController().signal}):w,hostCapture:n!==void 0,onCreated:i(S=>{l?.(S),c?.({name:"dashboard"});},"onCreated")}),E=useRef(x);E.current=x;let D=useCallback(S=>{y(S),E.current.setSigned(S!==null);},[]),k=x.busy;return jsxs(View,{style:[u.root,d],children:[jsx(et,{title:x.title,onBack:a,testID:"records-consent-header"}),jsxs(KeyboardAvoidingView,{behavior:"padding",style:u.body,children:[jsxs(ScrollView,{contentContainerStyle:p.content,keyboardShouldPersistTaps:"handled",testID:"records-consent",children:[jsxs(View,{style:p.scopeCard,accessibilityRole:"summary",children:[jsx(m,{style:p.scopeHeading,accessibilityRole:"header",children:se.scopeHeading}),jsx(m,{style:p.scopeBody,children:se.scopeBody}),jsx(View,{style:p.bullets,children:se.whatWeDo.map(S=>jsxs(View,{style:p.bulletRow,children:[jsx(m,{style:p.check,children:"\u2713"}),jsx(m,{style:p.bulletText,children:S})]},S))}),jsx(View,{style:p.retentionRow,children:jsx(m,{style:p.retentionText,children:se.retentionNote})}),x.copy&&x.scope?jsx(m,{style:p.serverScope,testID:"records-consent-scope",children:x.scope}):x.copyError?jsxs(Fragment,{children:[jsx(m,{style:u.errorText,accessibilityRole:"alert",children:x.copyError.displayMessage}),jsx(re,{label:ce.retry,kind:"outline",onPress:x.retryCopy,testID:"records-consent-copy-retry"})]}):jsx(m,{style:u.muted,accessibilityLiveRegion:"polite",children:ce.loading})]}),jsxs(Pressable,{onPress:()=>x.setAuthorized(!x.authorized),accessibilityRole:"checkbox",accessibilityState:{checked:x.authorized},accessibilityLabel:se.authorizeLabel(t,x.clinicName),hitSlop:6,style:[p.toggle,x.authorized?p.toggleChecked:null],testID:"records-authorize-toggle",children:[jsx(View,{style:[p.box,x.authorized?p.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:x.authorized?jsx(m,{style:p.boxCheck,children:"\u2713"}):null}),jsx(m,{style:p.toggleLabel,children:se.authorizeLabel(t,x.clinicName)})]}),jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:se.fullName}),jsx(qe,{accessibilityLabel:se.fullName,style:u.field,value:x.ownerName,placeholder:se.fullNamePlaceholder,placeholderTextColor:f.color.text.placeholder,maxLength:200,editable:!k,autoComplete:"name",autoCapitalize:"words",onChangeText:x.setOwnerName,testID:"records-consent-owner-name"})]}),x.needsEmail?jsxs(View,{style:p.block,testID:"records-consent-email-block",children:[x.directoryClinicNoEmail?jsx(View,{style:u.cautionNote,testID:"records-consent-no-email-note",children:jsx(m,{style:u.cautionNoteText,children:se.noEmailNote(t,x.clinicName)})}):null,jsx(m,{style:u.fieldLabel,children:se.emailLabel}),jsx(qe,{accessibilityLabel:se.emailLabel,style:u.field,value:x.email,placeholder:se.emailPlaceholder,placeholderTextColor:f.color.text.placeholder,maxLength:320,editable:!k,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:x.setEmail,testID:"records-consent-clinic-email"}),x.emailError?jsx(m,{style:u.errorText,accessibilityRole:"alert",children:x.emailError}):null,jsx(m,{style:u.muted,testID:"records-consent-review-note",children:se.newClinicDirectSendNote})]}):null,n?null:jsxs(View,{style:p.signatureBlock,children:[x.signatures.length>0?jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:se.reuseSignature}),jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:p.gallery,children:x.signatures.map(S=>{let I=x.reuseSignatureId===S.signatureId;return jsx(Pressable,{onPress:()=>x.pickReuseSignature(I?null:S.signatureId),accessibilityRole:"button",accessibilityLabel:I?se.reuseTileSelectedA11y:se.reuseTileA11y,style:[p.tile,I?p.tileSelected:null],testID:`records-consent-reuse-${S.signatureId}`,children:jsx(Image,{source:{uri:S.previewUrl},style:p.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},S.signatureId)})}),jsx(m,{style:u.muted,children:se.reuseHint})]}):null,jsx(View,{style:p.signatureHeader,children:jsx(m,{style:u.fieldLabel,children:g==="type"?se.signType:se.signDraw})}),jsx(Lr,{onChange:D,disabled:k}),jsx(Pressable,{onPress:()=>b(S=>S==="draw"?"type":"draw"),accessibilityRole:"button",accessibilityLabel:g==="draw"?se.toTypeA11y:se.toDraw,style:p.modeToggle,testID:"records-consent-sign-mode-toggle",children:jsx(m,{style:p.modeToggleText,children:g==="draw"?se.toType:se.toDraw})}),jsx(m,{style:u.muted,children:se.signatureHint(x.clinicName)})]}),x.error?jsx(View,{style:u.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:jsx(m,{style:u.errorText,children:x.error})}):null,x.created?jsx(m,{accessibilityLiveRegion:"polite",style:u.bodyText,children:x.created.statusLabel||ce.records}):null]}),jsx(View,{style:p.footer,children:jsx(re,{label:k?se.submitting:se.submit,accessibilityLabel:se.submitA11y,disabled:!x.ready,busy:k,onPress:()=>{x.submit();},style:p.submit,testID:"records-consent-submit"})})]}),jsx(Me,{})]})}i(By,"ConsentBody");function Hy(){let e=L();return useMemo(()=>Uy(e),[e])}i(Hy,"useLocalStyles");function Uy(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=i((c,a,d,u="regular")=>({..._(e,u),fontSize:c,lineHeight:Math.round(c*a),color:d}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xl+r.xs,gap:r.lg+r.xs/2},scopeCard:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md},scopeHeading:{...s(n.size.body+1,n.lineHeight.snug,t.brandInk,"bold")},scopeBody:s(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),bullets:{gap:r.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:r.sm},check:{...s(n.size.body,n.lineHeight.normal,t.brandInk,"bold")},bulletText:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary)},retentionRow:{paddingTop:r.xs,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},retentionText:s(n.size.tiny,n.lineHeight.normal,t.text.muted),serverScope:{...s(n.size.bodyTight,n.lineHeight.relaxed,t.text.secondary),paddingTop:r.xs},toggle:{flexDirection:"row",alignItems:"flex-start",gap:r.md,borderRadius:o.lg-r.xs,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2},toggleChecked:{borderColor:t.brandInk,backgroundColor:t.brandSoft},box:{width:r.xl,height:r.xl,borderRadius:o.xs+1,borderWidth:1.6,borderColor:t.brandInk,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},boxChecked:{backgroundColor:t.brandInk},boxCheck:{...s(n.size.body,n.lineHeight.tight,t.surface,"bold")},toggleLabel:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"bold")},block:{gap:r.sm},signatureBlock:{gap:r.sm},gallery:{gap:r.sm,paddingVertical:r.xs},tile:{width:r.xxl*3+r.lg,height:r.xxl+r.lg+r.sm,borderRadius:o.sm,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,overflow:"hidden"},tileSelected:{borderColor:t.brandInk,borderWidth:2},tileImage:{width:"100%",height:"100%"},signatureHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},modeToggle:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},modeToggleText:{...s(n.size.bodyTight,n.lineHeight.snug,t.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:r.lg,paddingTop:r.md,paddingBottom:r.xxl,borderTopWidth:l,borderTopColor:t.borderHairlineGreen,backgroundColor:t.background},submit:{minHeight:r.xxl+r.lg+r.xs+r.xs/2}})}i(Uy,"makeLocalStyles");function fo(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(fo,"markerStatusTone");function $y(e){switch(e){case "above":return "above the reference range";case "below":return "below the reference range";case "in_range":return "within range";default:return "no reference range on file"}}i($y,"markerStatusSpoken");function Wy(e){return e.refLow!==null&&e.refHigh!==null?`, reference range ${e.refLow} to ${e.refHigh}`:e.refLow!==null?`, reference range at least ${e.refLow}`:e.refHigh!==null?`, reference range up to ${e.refHigh}`:""}i(Wy,"rangePhrase");function go(e,t){let r=t?` ${t}`:"";return e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}${r}`:e.refLow!==null?`\u2265 ${e.refLow}${r}`:e.refHigh!==null?`\u2264 ${e.refHigh}${r}`:"-"}i(go,"formatReferenceRange");function gc(e,t){let r=t.reviewed?", reviewed by our team":"",o=t.sourceClinic?`, from ${t.sourceClinic}`:"";return `${Q(t.at)}: ${Et(t.value,e.unit,t.qualitativeResult)}, ${$y(t.status)}${Wy(t)}${o}${r}`}i(gc,"markerPointSpoken");function Ge(e){return e?.trim()||"my pet"}i(Ge,"lead");function bc(e){let t=e.trim();return /[.!?]$/.test(t)?t:`${t}.`}i(bc,"clause");function hc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Ge(e)}'s ${r}`],n=[t.latestValueText?.trim(),t.statusText?.trim(),t.trajectoryText?.trim()].filter(Boolean).join(", ");return o[0]+=n?`: ${n}.`:".",t.meaningText?.trim()&&o.push(bc(t.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Ge(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:t.markerId,payload:{marker:r,...t.statusText?.trim()?{status:t.statusText.trim()}:{}}}}}i(hc,"buildMarkerAskPrompt");function Rc(e,t,r){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:l,unknownCount:s}=t;if(o===0)return {prompt:`I'm looking at ${Ge(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Ge(e)}?`,entityRef:{type:"marker_summary",id:r,payload:{total:0}}};let c=s>0?`, ${s} without a reference range`:"";return {prompt:`I'm looking at ${Ge(e)}'s lab markers: ${o} total, ${n} in range, ${l} out of range${c}. What should I focus on?`,entityRef:{type:"marker_summary",id:r,payload:{total:o,inRange:n,outOfRange:l,unknown:s}}}}i(Rc,"buildMarkerSummaryAskPrompt");function vc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`${r}: ${t.valueText.trim()}`];t.collectedAt?.trim()&&o.push(`collected ${t.collectedAt.trim()}`),t.sourceClinic?.trim()&&o.push(`from ${t.sourceClinic.trim()}`),t.referenceText?.trim()&&o.push(`reference range ${t.referenceText.trim()}`),t.flagged&&o.push(`flagged ${t.flagged}`);let n={marker:r};return t.flagged&&(n.status=t.flagged),t.reviewed!==void 0&&(n.reviewed=t.reviewed),{prompt:`I'm looking at ${Ge(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:t.entityId,payload:n}}}i(vc,"buildMarkerReadingAskPrompt");function xc(e,t,r){let o=t.clinicName?.trim(),n=t.heldItemCount??0,l=n>0?`, ${n} fact${n===1?"":"s"} being verified`:"";return {prompt:`I'm looking at ${Ge(e)}'s records request${o?` to ${o}`:""}, status: ${t.statusLabel.trim()}${l}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:r,payload:{status:t.status,held:n,...o?{clinic:o}:{}}}}}i(xc,"buildRecordsRequestAskPrompt");var Gy=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function wc(e,t,r,o){let n=t.entityTypeLabel.trim()||"record",l=t.title.trim()||n,s=t.detail?.trim();return {prompt:`I'm looking at ${Ge(e)}'s ${n.toLowerCase()}: ${l}${s?`, ${s}`:""}. What does this mean, and what should I keep on top of for ${Ge(e)}?`,entityRef:{type:Gy[r]??r,id:o,payload:{kind:n,title:l,...s?{detail:s}:{}}}}}i(wc,"buildEntityRowAskPrompt");function Cc(e,t,r){let o=t.filter(s=>s.label.trim()),n={type:"upcoming_care",id:r};if(o.length===0)return {prompt:`I'm looking at ${Ge(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Ge(e)} be on?`,entityRef:n};let l=[...o].sort((s,c)=>(s.tone==="overdue"?0:1)-(c.tone==="overdue"?0:1)).slice(0,4).map(s=>s.relativeText.trim()?`${s.label.trim()} (${s.relativeText.trim().toLowerCase()})`:s.label.trim());return {prompt:`I'm looking at ${Ge(e)}'s upcoming care: ${l.join(", ")}. What should I prioritize for ${Ge(e)}, and how do I stay on top of these?`,entityRef:n}}i(Cc,"buildUpcomingCareAskPrompt");function Ec(e,t,r){let o=[`I'm looking at ${Ge(e)}'s physical exam${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`],n=t.abnormal.filter(l=>l.system.trim());return n.length>0?(o.push(`Abnormal: ${n.slice(0,6).map(l=>`${l.system.trim()}: ${l.finding.trim()}`).join("; ")}.`),o.push(`What do these findings mean, and what should I follow up on for ${Ge(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Ge(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:r}}}i(Ec,"buildPhysicalExamAskPrompt");function Sc(e,t,r){let o=[`I'm looking at ${Ge(e)}'s visit notes${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`];for(let n of t.sections.filter(l=>l.text.trim()).slice(0,3))o.push(`${n.label.trim()||"Note"}: ${bc(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Ge(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:r}}}i(Sc,"buildVisitNoteAskPrompt");function kc(e,t,r){let o=t.scopeLabel.trim()||"a detail",n=t.candidates.filter(s=>s.value.trim()),l=n.slice(0,3).map(s=>`"${s.value.trim()}"${s.clinicName?.trim()?` (${s.clinicName.trim()})`:""}`).join(" vs ");return {prompt:`Two of ${Ge(e)}'s documents disagree on ${o}: ${l}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:r,payload:{field:o,severity:t.severity,values:n.map(s=>s.value.trim()).join(" | ")}}}}i(kc,"buildConflictAskPrompt");function Cn(e){return e!==void 0}i(Cn,"canUploadRecords");function ea(e,t){return e??t?.version??""}i(ea,"resolveConsentVersion");function qr(e,t){return ea(e,t).length>0}i(qr,"canGrantConsent");function xr(e,t){return e.denialReason==="consent_required"?t?{kind:"consent_required"}:{kind:"consent_unavailable"}:e.denialReason==="pet_not_found"?{kind:"pet_not_found",error:q("petNotFound",{retryable:false})}:e.denialReason==="entitlement"?{kind:"error",error:q("accessDenied")}:e.denialReason==="session_required"?{kind:"session_required"}:e.withheld?{kind:"withheld"}:e.error===null?{kind:"withheld"}:{kind:"error",error:e.error}}i(xr,"selectErrorView");function bo(e){let t=e.clinicName?.trim()??"";return t.length>0?t:e.source==="owner_provided"?Tc.ownerUpload:Tc.clinicRequest}i(bo,"selectRequestTitle");var Tc=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function Yy(e){let t=[...e].sort((r,o)=>r.updatedAt!==o.updatedAt?r.updatedAt>o.updatedAt?-1:1:r.createdAt!==o.createdAt?r.createdAt>o.createdAt?-1:1:0);return Object.freeze(t)}i(Yy,"selectRequestList");function En(e){let t=e.actionNeededLabel?.trim()??"";return t.length>0?t:e.statusLabel}i(En,"selectPrimaryLabel");function ho(e){if(e.showClinicPhone!==true)return null;let t=e.clinicPhone?.trim()??"";return t.length===0?null:{phone:t,dial:`tel:${t.replace(/[^+\d]/g,"")}`,clinicName:e.clinicName?.trim()||null}}i(ho,"selectClinicCall");var gt=200,Pc=16;function Qy(e,t){let r=e.inRangeCount+e.outOfRangeCount+e.unknownCount;if(!Number.isFinite(r)||r<=0)return [];let o=[{key:"in_range",color:t.inRange,count:e.inRangeCount},{key:"out_of_range",color:t.outOfRange,count:e.outOfRangeCount},{key:"unknown",color:t.unknown,count:e.unknownCount}],n=0,l=[];for(let s of o){if(!(s.count>0))continue;let c=s.count/r*360;if(!Number.isFinite(c))return null;l.push({key:s.key,color:s.color,startDeg:n,sweepDeg:c}),n+=c;}return l}i(Qy,"buildRingSegments");function Dc({summary:e,onAsk:t,testID:r}){let o=Jy(),n=L(),{totalMarkers:l,inRangeCount:s,outOfRangeCount:c,unknownCount:a}=e,d=useMemo(()=>Qy(e,{inRange:n.color.success,outOfRange:n.color.danger,unknown:n.color.text.muted}),[e,n]),u=d!==null&&d.length>0;return jsxs(View,{style:o.card,accessibilityRole:"summary",testID:r,children:[jsx(m,{style:o.title,children:Mt.title}),jsx(View,{style:o.ringRow,accessible:true,accessibilityRole:"image",accessibilityLabel:Mt.a11y(l,s,c,a),children:jsxs(View,{style:o.ringWrap,children:[jsx(View,{style:o.track}),d===null?null:d.map(p=>jsx(Xy,{segment:p,styles:o},p.key)),jsxs(View,{style:o.center,pointerEvents:"none",children:[jsx(m,{style:o.centerCount,children:l}),jsx(m,{style:o.centerLabel,children:l===1?Mt.marker:Mt.markers})]})]})}),u||d===null?jsxs(View,{style:o.badges,children:[jsx(ta,{count:c,label:Mt.outOfRange,color:n.color.danger,styles:o}),jsx(ta,{count:s,label:Mt.inRange,color:n.color.success,styles:o}),a>0?jsx(ta,{count:a,label:Mt.noRange,color:n.color.text.muted,styles:o}):null]}):null,jsx(m,{style:o.subtitle,children:Mt.subtitle}),t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Mt.askA11y,style:o.ask,testID:"marker-summary-ask",children:jsx(m,{style:o.askLabel,children:Mt.ask})}):null]})}i(Dc,"MarkerSummaryCard");function Xy({segment:e,styles:t}){return (e.sweepDeg<=180?[{start:e.startDeg,sweep:e.sweepDeg}]:[{start:e.startDeg,sweep:180},{start:e.startDeg+180,sweep:e.sweepDeg-180}]).map((o,n)=>jsx(View,{style:[t.piece,{transform:[{rotate:`${o.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${e.key}`,children:jsx(View,{style:t.window,children:jsx(View,{style:[t.halfRing,{borderTopColor:e.color,borderRightColor:e.color,transform:[{rotate:`${o.sweep-135}deg`}]}]})})},n))}i(Xy,"Arc");function ta({count:e,label:t,color:r,styles:o}){return jsx(View,{style:[o.badge,{borderColor:r}],children:jsx(m,{style:[o.badgeText,{color:r}],children:`${e} ${t}`})})}i(ta,"Badge");function Jy(){let e=L();return useMemo(()=>Zy(e),[e])}i(Jy,"useStyles");function Zy(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=StyleSheet.hairlineWidth,c=ot(l.recordCard);return StyleSheet.create({card:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder,padding:r.lg-1,gap:r.sm+r.xs/2,...Je(l.recordCard,s)},title:{..._(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.letterSpacing.headerBrand,...c},ringRow:{alignItems:"center"},ringWrap:{width:gt,height:gt,alignItems:"center",justifyContent:"center"},track:{position:"absolute",width:gt,height:gt,borderRadius:gt/2,borderWidth:Pc,borderColor:t.surfaceSubtle},piece:{position:"absolute",width:gt,height:gt},window:{position:"absolute",left:gt/2,top:0,width:gt/2,height:gt,overflow:"hidden"},halfRing:{position:"absolute",left:-gt/2,top:0,width:gt,height:gt,borderRadius:gt/2,borderWidth:Pc,borderBottomColor:"transparent",borderLeftColor:"transparent"},center:{position:"absolute",alignItems:"center",justifyContent:"center"},centerCount:{..._(e,"medium"),fontSize:n.size.verdict*2,lineHeight:n.size.verdict*2+r.xs,color:t.text.primary,textAlign:"center",...c},centerLabel:{..._(e,"medium"),fontSize:n.size.heading-1,lineHeight:n.size.heading+r.xs/2,color:t.text.primary,textAlign:"center",...c},badges:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:r.sm},badge:{borderWidth:1,borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs},badgeText:{..._(e,"mono"),fontSize:n.size.nano,lineHeight:n.size.tiny,letterSpacing:n.letterSpacing.headerBrand/2,textTransform:"uppercase"},subtitle:{..._(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.relaxed),color:t.text.primary,...c},ask:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.sm,marginTop:r.xs/2,paddingHorizontal:r.lg,borderRadius:o.pill,borderWidth:s,borderColor:t.borderRingCream,backgroundColor:t.surface},askLabel:{..._(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.primary,letterSpacing:n.letterSpacing.tight}})}i(Zy,"makeStyles");function ef(e){return e.value!==null&&Number.isFinite(e.value)}i(ef,"numeric");function Ac(e){let t=e.points.filter(ef);if(t.length===0)return null;let r=e.points[e.points.length-1]??null,o=r?.refLow??null,n=r?.refHigh??null,l=t.map(g=>g.value),s=Math.min(...l,...o!==null?[o]:[],...n!==null?[n]:[]),c=Math.max(...l,...o!==null?[o]:[],...n!==null?[n]:[]);s===c&&(s-=1,c+=1);let a=(c-s)*.18,d=s-a,u=c+a,p=u-d,f=i(g=>(u-g)/p*100,"y"),h=6,R=t.length,v=t.map((g,b)=>({index:b,xPct:R<=1?50:h+b/(R-1)*(100-2*h),yPct:f(g.value),status:g.status,point:g})),y=o!==null||n!==null?{topPct:n!==null?f(n):0,bottomPct:o!==null?f(o):100}:null;return {points:v,band:y,firstDate:t[0]?.at??null,lastDate:t[t.length-1]?.at??null}}i(Ac,"buildMarkerChart");var nf=416,of=140;function vo(e){return `${e}%`}i(vo,"pct");function af({marker:e,width:t,onPointPress:r,onAsk:o}){let n=ra(),l=be(),s=Qt(e.latest?.status??null),c=fo(e.latest?.status??null),a=Hr(e.trajectory,e.points.length),d=useMemo(()=>Ac(e),[e]),u=e.latest?Et(e.latest.value,e.unit,e.latest.qualitativeResult):null;return jsx(View,{style:[n.page,t!==void 0?{width:t}:null],testID:`marker-card-${e.markerId}`,children:jsxs(View,{style:n.card,children:[jsxs(View,{style:n.headerRow,children:[jsxs(View,{style:n.nameColumn,children:[jsx(m,{style:n.markerName,numberOfLines:2,children:e.name}),e.unit?jsx(m,{style:n.unit,children:e.unit}):null]}),jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:or.status(s.label),children:jsx(Kt,{label:s.label,tone:c})})]}),e.latest&&u!==null?jsxs(View,{style:n.latestRow,children:[jsx(m,{style:[n.latestValue,s.outOfRange?n.latestValueDanger:null],accessibilityLabel:or.latestA11y(u,s.label,Q(e.latest.at)),children:u}),jsx(m,{style:n.latestDate,children:Q(e.latest.at)})]}):null,a?jsx(m,{style:n.trajectory,accessibilityRole:"text",children:a}):null,d!==null?jsxs(View,{style:n.chartWrap,children:[jsxs(View,{style:n.plot,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[d.band?jsx(View,{style:[n.band,{top:vo(d.band.topPct),height:vo(Math.max(0,d.band.bottomPct-d.band.topPct))}]}):null,d.points.map(p=>jsx(Pressable,{onPress:()=>r(e,p.point),hitSlop:12,style:[n.point,p.status==="above"||p.status==="below"?n.pointDanger:null,{left:vo(p.xPct),top:vo(p.yPct)}],testID:`marker-point-${e.markerId}-${p.index}`},p.index))]}),jsx(View,{style:n.a11yTable,accessibilityRole:"summary",accessibilityLabel:or.readingsA11y(e.name),children:e.points.map((p,f)=>jsx(View,{accessibilityRole:"text",accessibilityLabel:gc(e,p)},f))}),jsx(m,{style:e.points.length===1?n.singleHint:n.tapHint,children:e.points.length===1?or.singleHint:or.tapHint})]}):jsx(View,{style:n.emptyBody,accessibilityRole:"text",children:jsx(m,{style:n.emptyText,children:or.empty})}),o?jsx(Pressable,{onPress:()=>o(e),accessibilityRole:"button",accessibilityLabel:or.askA11y(e.name),style:[l.pill,l.pillAsk],testID:`marker-ask-${e.markerId}`,children:jsx(m,{style:l.pillAskLabel,children:or.ask})}):null]})})}i(af,"MarkerTrendCard");function qc({markers:e,onPointPress:t,onAsk:r}){let o=ra(),[n,l]=useState(0),[s,c]=useState(0),a=i(p=>l(p.nativeEvent.layout.width),"onLayout"),d=i(p=>{if(n<=0)return;let f=Math.round(p.nativeEvent.contentOffset.x/n);c(Math.max(0,Math.min(f,e.length-1)));},"onMomentumEnd"),u=e[s]??null;return jsxs(View,{style:o.carousel,onLayout:a,testID:"marker-carousel",children:[jsx(ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:d,snapToAlignment:"start",children:e.map(p=>jsx(af,{marker:p,width:n>0?n:void 0,onPointPress:t,onAsk:r},p.markerId))}),jsxs(View,{style:o.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:wi.a11y(u?.name??null,s,e.length),children:[jsx(View,{style:o.dots,children:e.map((p,f)=>jsx(View,{style:[o.dot,f===s?o.dotActive:null]},p.markerId))}),jsx(m,{style:o.counter,children:wi.counter(s,e.length)})]})]})}i(qc,"MarkerTrendCarousel");function Fc({marker:e,point:t,onClose:r,onAsk:o}){let n=ra(),l=be();if(e===null||t===null)return null;let s=i((c,a)=>jsxs(View,{style:n.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${c}: ${a}`,children:[jsx(m,{style:n.detailLabel,children:c}),jsx(m,{style:n.detailValue,children:a})]},c),"row");return jsxs(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:r,children:[jsx(Pressable,{style:n.backdrop,onPress:r,accessibilityRole:"button",accessibilityLabel:Ct.close}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"marker-provenance-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.sheetHeader,children:[jsx(m,{style:n.sheetTitle,accessibilityRole:"header",children:Ct.title}),jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Ct.close,hitSlop:10,style:n.closeButton,testID:"marker-provenance-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsxs(View,{style:n.sheetBody,children:[jsxs(View,{style:n.valueRow,children:[jsx(m,{style:n.sheetName,children:e.name}),jsx(m,{style:n.sheetValue,children:Et(t.value,e.unit,t.qualitativeResult)})]}),t.reviewed?jsx(View,{style:n.reviewed,accessibilityRole:"text",children:jsx(m,{style:n.reviewedText,children:Ct.reviewed})}):null,s(Ct.collected,Q(t.at)),t.sourceClinic?s(Ct.clinic,t.sourceClinic):null,s(Ct.referenceRange,t.refLow!==null||t.refHigh!==null?go(t,e.unit):Ct.noRange),t.docId?s(Ct.sourceDocument,t.docId):null,t.reviewed?null:jsx(m,{style:n.unverified,accessibilityRole:"text",children:Ct.unverified}),o?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Ct.askA11y,style:[l.pill,l.pillAsk],testID:"marker-provenance-ask",children:jsx(m,{style:l.pillAskLabel,children:Ct.ask})}):null]})]})]})}i(Fc,"MarkerProvenanceSheet");function ra(){let e=L();return useMemo(()=>sf(e),[e])}i(ra,"useStyles");function sf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=StyleSheet.hairlineWidth,c=r.md,a=i((f,h,R,v="regular")=>({..._(e,v),fontSize:f,lineHeight:Math.round(f*h),color:R}),"text"),d=ot(l.recordCard),u=a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold"),p=a(n.size.verdict+r.xs,n.lineHeight.tight,t.text.primary,"bold");return StyleSheet.create({page:{paddingHorizontal:r.sm},card:{borderRadius:o.lg-r.xs/2,borderWidth:s,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg,gap:r.md,...Je(l.recordCard,s)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm+r.xs/2},nameColumn:{flex:1,gap:r.xs/2},markerName:{...u,...d},sheetName:u,unit:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted,...d},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},latestValue:{...p,...d},sheetValue:p,latestValueDanger:{color:t.danger},latestDate:{...a(n.size.caption,n.lineHeight.normal,t.text.muted),...d},trajectory:{...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted),...d},chartWrap:{gap:r.sm},plot:{height:of,borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:t.badgeBgPositive},point:{position:"absolute",width:c,height:c,borderRadius:c/2,marginLeft:-c/2,marginTop:-c/2,backgroundColor:t.brand,borderWidth:2,borderColor:t.surface},pointDanger:{backgroundColor:t.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...a(n.size.tiny,n.lineHeight.normal,t.text.placeholder),textAlign:"center",...d},singleHint:{...a(n.size.caption,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},emptyBody:{alignItems:"center",justifyContent:"center",gap:r.sm,paddingVertical:r.xxl+r.xs},emptyText:{...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},carousel:{height:nf},footer:{alignItems:"center",gap:r.sm,paddingTop:r.md},dots:{flexDirection:"row",gap:r.xs+r.xs/2},dot:{width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs-1,backgroundColor:t.borderHairlineGreen},dotActive:{width:r.lg+r.xs/2,backgroundColor:t.brand},counter:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,letterSpacing:n.letterSpacing.eyebrow/3,color:t.text.muted},backdrop:{flex:1,backgroundColor:to},sheet:{backgroundColor:t.surfaceCream,borderTopLeftRadius:o.xl-r.xs,borderTopRightRadius:o.xl-r.xs,paddingHorizontal:r.lg+r.xs,paddingTop:r.sm,paddingBottom:r.xxl+r.xs,maxHeight:"80%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},sheetTitle:{flex:1,...a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},closeButton:{width:r.xxl+r.md,height:r.xxl+r.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...a(n.size.verdict,n.lineHeight.tight,t.text.primary)},sheetBody:{gap:r.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},reviewed:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs,backgroundColor:t.badgeBgPositive},reviewedText:{...a(n.size.tiny,n.lineHeight.normal,t.success,"medium")},detailRow:{gap:r.xs/2},detailLabel:{...a(n.size.caption,n.lineHeight.normal,t.text.muted,"medium")},detailValue:a(n.size.body,n.lineHeight.normal,t.text.primary),unverified:a(n.size.caption,n.lineHeight.normal,t.text.muted)})}i(sf,"makeStyles");var W=Object.freeze({title:"Full medical record",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:i(e=>`${e} ${e===1?"document":"documents"} from your vet ${e===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,"inReview"),needsAttention:"Needs your attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:i(e=>`${e} ${e===1?"document":"documents"} on file`,"documentsOnFile"),inReviewChip:i(e=>`${e} in review`,"inReviewChip"),beingVerified:i(e=>`${e} being verified`,"beingVerified"),beingVerifiedA11y:i(e=>`${e} ${e===1?"fact is":"facts are"} being verified`,"beingVerifiedA11y"),pendingReview:"Pending review: ",dateRange:i((e,t)=>`${Q(e)} to ${Q(t)}`,"dateRange"),documents:"Documents",uploadedDocument:fe.uploadedDocument,documentRowA11y:i(e=>`View what ${e} contributed to this record`,"documentRowA11y"),identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",lastDone:i(e=>`Last done ${e}`,"lastDone"),overdue:"Overdue",due:i(e=>`Due ${e}`,"due"),askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:fe.labResults,visits:fe.visits,physicalExams:fe.physicalExams,visitNotes:fe.visitNotes,document:Object.freeze({title:"Health Record",download:"Download record PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:i(e=>`Generated ${Q(e)}`,"generated"),identity:"Identity",labs:"Blood & Lab Work",ref:i(e=>`Ref ${e}`,"ref"),noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),zc=Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function kn(e){return Object.prototype.hasOwnProperty.call(zc,e)?zc[e]:ir(e)}i(kn,"entityTypeLabel");var Nc=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function Mc(e){let t=Nc.filter(o=>e.includes(o)),r=e.filter(o=>!Nc.includes(o));return [...t,...r]}i(Mc,"orderEntityTypes");function xo(e){switch(e){case "identity_risk":return {label:"Identity mismatch",rank:0,tone:"critical"};case "benign":return {label:"Minor difference",rank:2,tone:"neutral"};default:return {label:"Needs review",rank:1,tone:"warning"}}}i(xo,"conflictSeverityMeta");function Tn(e,t){if(!e)return null;let r=Date.parse(e);if(Number.isNaN(r))return null;let o=r<t-1440*60*1e3;return {label:o?W.overdue:W.due(Q(e)),overdue:o}}i(Tn,"dueBadge");function Bc(e){return e===null?null:e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}`:e.refLow!==null?`\u2265 ${e.refLow}`:e.refHigh!==null?`\u2264 ${e.refHigh}`:null}i(Bc,"formatReferenceBand");var at=Object.freeze({editA11y:i(e=>`Edit ${e}. Correct or remove this record detail.`,"editA11y"),title:i(e=>`Edit ${e}`,"title"),helper:"Corrects your record. Your vet can still review it.",close:"Close",closeEditorA11y:"Close editor",save:"Save changes",saving:"Saving...",remove:"Remove this detail",removeA11y:i(e=>`Remove ${e}`,"removeA11y"),confirmRemove:"Remove this detail from your record? This can't be undone.",removeConfirm:"Remove",removing:"Removing...",keep:"Keep",noChange:"Change a value before saving.",saved:"Saved.",removed:"Removed.",detail:"record detail"});function Hc(e,t){return tr(e)?t==="remove"?"Records access for this pet is off, so this detail cannot be removed.":"Records access for this pet is off, so this detail cannot be changed.":Xl(e)?t==="remove"?"A clinician already reviewed this detail, so it can't be removed here.":"A clinician already reviewed this detail, so it can't be changed here.":t==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}i(Hc,"factEditErrorMessage");var lf=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function na(e,t){if(Object.keys(t.edits).length===0&&t.removed.length===0)return e;let r=[];for(let o of e){let n=o.canonicalKey??null;if(n!==null&&t.removed.includes(n))continue;let l=n!==null?t.edits[n]:void 0;r.push(l===void 0?o:Object.freeze({...o,value:l}));}return Object.freeze(r)}i(na,"applyFactOverlay");function oa(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(oa,"isFactEditable");function cf(){return `records-fact-${Date.now().toString(36)}`}i(cf,"defaultFactKey");function ia(e,t={}){let r=sr(),{userRef:o}=ke(),[n,l]=useState(lf),[s,c]=useState(false),[a,d]=useState(null),u=useMemo(()=>({}),[r,e,o]),[p,f]=useState(null),h=useCallback(()=>f(u),[u]),R=o!==null&&p!==u,v=useRef(false),y=useRef(t.newIdempotencyKey);y.current=t.newIdempotencyKey;let g=useCallback(()=>(y.current??cf)(),[]),b=useCallback((D,k,S)=>{if(c(false),!D.ok){if(k(),vr(D.error)){h();return}d(Hc(D.error,S));}},[h]),w=useCallback(async(D,k)=>{let S=D.canonicalKey??"",I=k.trim();if(v.current||S.length===0||I.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let Y=n;l($=>({...$,edits:{...$.edits,[S]:I}}));let z=await r.editFact(e,{entityType:D.category,canonicalKey:S,correctedFields:$i(D.value,I),idempotencyKey:g()});return v.current=false,b(z,()=>l(Y),"edit"),z},[r,e,n,b,g]),x=useCallback(async D=>{let k=D.canonicalKey??"";if(v.current||k.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let S=n;l(Y=>({...Y,removed:[...Y.removed,k]}));let I=await r.removeFact(e,{entityType:D.category,canonicalKey:k,idempotencyKey:g()});return v.current=false,b(I,()=>l(S),"remove"),I},[r,e,n,b,g]),E=useCallback(()=>d(null),[]);return useMemo(()=>({overlay:n,busy:s,error:a,available:R,edit:w,remove:x,clearError:E}),[n,s,a,R,w,x,E])}i(ia,"useRecordFactEdit");function Wc({entity:e,factEdit:t,children:r}){let o=Gc(),[n,l]=useState(false),s=e.label.trim()||at.detail;return jsxs(View,{style:o.row,children:[jsx(View,{style:o.main,children:r}),jsx(Pressable,{onPress:()=>l(true),accessibilityRole:"button",accessibilityLabel:at.editA11y(s),hitSlop:6,style:o.editButton,testID:`fact-edit-open-${e.canonicalKey??e.key}`,children:jsx(View,{style:o.pencil,accessibilityElementsHidden:true,importantForAccessibility:"no"})}),n?jsx(yf,{entity:e,title:s,factEdit:t,onClose:()=>l(false)}):null]})}i(Wc,"FactEditAffordance");function yf({entity:e,title:t,factEdit:r,onClose:o}){let n=Gc(),l=be(),s=L(),[c,a]=useState(e.value??""),[d,u]=useState(null),[p,f]=useState(false);useEffect(()=>{r.clearError();},[r]);let h=c.trim().length>0&&c.trim()!==(e.value??"").trim(),R=d??r.error,v=r.busy,y=i(()=>{if(!h){u(at.noChange);return}u(null),r.edit(e,c).then(b=>{b.ok&&o();});},"submitEdit"),g=i(()=>{u(null),r.remove(e).then(b=>{b.ok?o():f(false);});},"submitRemove");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:o,children:jsxs(KeyboardAvoidingView,{behavior:"padding",style:n.backdrop,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:at.closeEditorA11y,onPress:o}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"fact-edit-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.header,children:[jsxs(View,{style:n.headerText,children:[jsx(m,{style:n.title,accessibilityRole:"header",children:at.title(t)}),jsx(m,{style:[n.helper,R?n.helperError:null],accessibilityLiveRegion:"polite",children:R??at.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:at.close,onPress:o,hitSlop:12,style:n.closeButton,testID:"fact-edit-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsx(m,{style:l.fieldLabel,children:e.label}),jsx(qe,{accessibilityLabel:e.label,style:l.field,value:c,onChangeText:b=>{a(b),u(null);},editable:!v,maxLength:512,placeholderTextColor:s.color.text.placeholder,testID:"fact-edit-field"}),p?jsxs(View,{style:n.confirmBlock,testID:"fact-edit-confirm-remove",children:[jsx(m,{style:n.confirmText,children:at.confirmRemove}),jsxs(View,{style:n.confirmRow,children:[jsx(re,{label:v?at.removing:at.removeConfirm,kind:"danger",busy:v,onPress:g,style:n.confirmButton,testID:"fact-edit-remove-confirm"}),jsx(re,{label:at.keep,kind:"outline",disabled:v,onPress:()=>f(false),style:n.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):jsxs(View,{style:n.actions,children:[jsx(re,{label:v?at.saving:at.save,busy:v,disabled:!h,onPress:y,testID:"fact-edit-save"}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:at.removeA11y(t),disabled:v,onPress:()=>{u(null),f(true);},style:[n.removeButton,v?n.removeDisabled:null],testID:"fact-edit-remove",children:jsx(m,{style:n.removeText,children:at.remove})})]})]})]})})}i(yf,"FactEditSheet");function Gc(){let e=L();return useMemo(()=>ff(e),[e])}i(Gc,"useStyles");function ff(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,s=e.brightness==="dark"?t.errorRed:t.danger,c=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text");return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:r.sm},main:{flex:1},editButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},pencil:{width:r.md+r.xs/2,height:r.xs/2,backgroundColor:t.brandInk,borderRadius:o.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:to},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),helperError:{color:s},closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),actions:{gap:r.sm},removeButton:{minHeight:l,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...c(n.size.bodyTight,n.lineHeight.snug,t.danger,"bold")},confirmBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.badgeBgCritical},confirmText:c(n.size.bodyTight,n.lineHeight.normal,t.text.primary),confirmRow:{flexDirection:"row",gap:r.sm},confirmButton:{flex:1}})}i(ff,"makeStyles");function So({record:e,depth:t,petName:r,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:s,nowMs:c}){let a=be(),d=gf(),u=c??Date.now(),p=useMemo(()=>s?na(e.entities,s.overlay):e.entities,[e.entities,s]),f=useMemo(()=>{let y=[],g=new Map;for(let b of p){let w=b.category.trim();if(w.length===0)continue;let x=g.get(w);x===void 0?(y.push(w),g.set(w,[b])):x.push(b);}return {order:Mc(y),groups:g}},[p]),h=Object.values(e.documents),R=i((y,g,b)=>l?jsx(Pressable,{onPress:()=>{let w=y();l(w.prompt,w.entityRef);},accessibilityRole:"button",accessibilityLabel:g,style:[a.pill,a.pillAsk,d.ask],testID:b,children:jsx(m,{style:a.pillAskLabel,children:g})}):null,"ask"),v=s!==void 0&&s.available;return jsxs(Fragment,{children:[jsxs(View,{style:d.sections,children:[t&&t.conflicts.length>0?jsxs(View,{style:a.section,testID:"record-section-conflicts",children:[jsx(Bt,{title:W.needsAttention,count:t.conflicts.length}),[...t.conflicts].sort((y,g)=>xo(y.severity).rank-xo(g.severity).rank).map(y=>{let g=xo(y.severity),b=ir(y.field??y.entityType);return jsxs(View,{style:[d.conflictCard,{borderColor:a.chipTones[g.tone].fg.color}],accessibilityRole:"summary",children:[jsxs(View,{style:d.conflictHead,children:[jsx(m,{style:d.conflictTitle,children:g.label}),jsx(Kt,{label:b,tone:g.tone})]}),jsx(m,{style:a.rowDetail,children:W.conflictSub}),y.candidates.map((w,x)=>jsxs(View,{style:d.candidate,children:[jsx(m,{style:a.rowTitle,children:w.value}),jsx(m,{style:a.rowMuted,children:[w.docId?e.documents[w.docId]?.title??W.uploadedDocument:W.uploadedDocument,w.collectedAt?Q(w.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},x)),R(()=>kc(r,{scopeLabel:b,severity:y.severity,candidates:y.candidates.map(w=>({value:w.value,clinicName:w.docId?e.documents[w.docId]?.title??null:null}))},y.conflictId),W.askConflict,`records-ask-conflict-${y.conflictId}`)]},y.conflictId)})]}):null,t?.completeness?jsxs(View,{style:a.section,testID:"record-section-completeness",children:[jsx(Bt,{title:W.whatsOnFile}),jsxs(View,{style:a.card,children:[jsx(View,{style:d.coverageRow,children:[[W.coverage.labs,t.completeness.hasLabHistory],[W.coverage.vaccines,t.completeness.hasVaccinationHistory],[W.coverage.weight,t.completeness.hasWeightHistory],[W.coverage.vitals,t.completeness.hasVitalsHistory],[W.coverage.exams,t.completeness.hasPhysicalExamHistory],[W.coverage.procedures,t.completeness.hasProcedureHistory],[W.coverage.genetics,t.completeness.hasGeneticHistory],[W.coverage.parasite,t.completeness.hasParasitePreventionHistory],[W.coverage.reproductive,t.completeness.hasReproductiveHistory]].map(([y,g])=>jsx(View,{style:[d.coveragePill,g?a.chipTones.positive.bg:a.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${y}: ${g?W.onFile:W.noneOnFile}`,children:jsx(m,{style:[d.coverageText,g?a.chipTones.positive.fg:{color:a.rowMuted.color}],children:y})},y))}),jsxs(View,{style:d.metaRow,children:[jsx(m,{style:d.metaText,children:W.documentsOnFile(t.completeness.documentsIngested)}),t.completeness.documentsInReview>0?jsx(Kt,{label:W.inReviewChip(t.completeness.documentsInReview),tone:"warning"}):null,aa(t.completeness.heldTotal,t.completeness.entitiesPendingReview)>0?jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:W.beingVerifiedA11y(aa(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),children:jsx(Kt,{label:W.beingVerified(aa(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),t.completeness.earliestRecordAt||t.completeness.latestRecordAt?jsx(View,{style:d.metaRow,children:jsx(m,{style:d.metaText,children:W.dateRange(t.completeness.earliestRecordAt,t.completeness.latestRecordAt)})}):null,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).length>0?jsxs(m,{style:d.pendingText,children:[W.pendingReview,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).map(([y,g])=>`${kn(y)} (${g})`).join(", ")]}):null]})]}):null,h.length>0?jsxs(View,{style:a.section,testID:"record-section-documents",children:[jsx(Bt,{title:W.documents,count:h.length}),jsx(View,{style:a.card,children:h.map((y,g)=>{let b=y.title?.trim()||W.uploadedDocument,w=y.receivedAt?Q(y.receivedAt):null,x=jsxs(Fragment,{children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:b}),w?jsx(m,{style:a.rowDetail,children:w}):null]}),n?jsx(Pr,{}):null]});return n?jsx(Pressable,{onPress:()=>n({name:"contributions",docId:y.docId}),accessibilityRole:"button",accessibilityLabel:W.documentRowA11y(b),style:[a.row,g>0?a.rowDivider:null],testID:`records-document-row-${y.docId}`,children:x},y.docId):jsx(View,{style:[a.row,g>0?a.rowDivider:null],children:x},y.docId)})})]}):null,e.identity.length>0?jsxs(View,{style:a.section,testID:"record-section-identity",children:[jsx(Bt,{title:W.identity}),jsx(View,{style:a.card,children:e.identity.map((y,g)=>jsxs(View,{style:[a.row,g>0?a.rowDivider:null],children:[jsx(m,{style:d.identityLabel,children:y.label}),jsx(m,{style:d.identityValue,children:y.value})]},`${g}:${y.label}`))})]}):null,e.forwardLooking.length>0?jsxs(View,{style:a.section,testID:"record-section-upcoming",children:[jsx(Bt,{title:W.upcomingCare,count:e.forwardLooking.length}),jsx(View,{style:a.card,children:e.forwardLooking.map((y,g)=>{let b=Tn(y.dueAt,u);return jsxs(View,{style:[a.row,g>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.title}),y.detail?jsx(m,{style:a.rowDetail,children:y.detail}):null]}),b?jsx(Kt,{label:b.label,tone:b.overdue?"critical":"info"}):null]},`${y.title}-${g}`)})}),R(()=>Cc(r,e.forwardLooking.map(y=>{let g=Tn(y.dueAt,u);return {label:y.title,relativeText:g?.label??"",tone:g?.overdue?"overdue":"upcoming"}}),e.petRef),W.askUpcomingCare,"records-ask-upcoming-care")]}):null,f.order.map(y=>{let g=f.groups.get(y)??[];if(g.length===0)return null;let b=kn(y);return jsxs(View,{style:a.section,testID:`record-section-${y}`,children:[jsx(Bt,{title:b,count:g.length}),jsx(View,{style:a.card,children:g.map((w,x)=>{let D=[Br(w.value,w.unit),w.observedAt?Q(w.observedAt):null].filter(S=>S&&S.length>0).join(" \xB7 "),k=jsxs(View,{style:[a.row,x>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:w.label}),D?jsx(m,{style:a.rowDetail,children:D}):null,R(()=>wc(r,{entityTypeLabel:b,title:w.label,detail:D||null},y,w.key),W.askEverfur,`records-ask-entity-${w.key}`)]}),w.status?jsx(Kt,{label:ir(w.status)}):null]});return v&&oa(w)&&s?jsx(Wc,{entity:w,factEdit:s,children:k},w.key):jsx(View,{children:k},w.key)})})]},y)}),t&&t.physicalExams.length>0?jsxs(View,{style:a.section,testID:"record-section-exams",children:[jsx(Bt,{title:W.physicalExams,count:t.physicalExams.length}),t.physicalExams.map(y=>jsxs(View,{style:a.card,children:[jsx(m,{style:[a.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Q(y.observedOn):fe.exam}),y.systems.map((g,b)=>{let w=g.findingStatus==="abnormal",x=w?fe.abnormal:g.findingStatus==="not_examined"?fe.notExamined:fe.normal;return jsxs(View,{style:[a.row,b>0?a.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[Ir(g.system),x,w?g.finding:null].filter(Boolean).join(", "),children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:Ir(g.system)}),w&&g.finding?jsx(m,{style:a.rowDetail,children:g.finding}):null]}),jsx(Kt,{label:x,tone:w?"warning":g.findingStatus==="not_examined"?"neutral":"positive"})]},g.system)}),R(()=>Ec(r,{observedOn:y.observedOn?Q(y.observedOn):null,abnormal:y.systems.filter(g=>g.findingStatus==="abnormal").map(g=>({system:Ir(g.system),finding:g.finding??""}))},y.examId),W.askExam,`records-ask-exam-${y.examId}`)]},y.examId))]}):null,t&&t.clinicianNotes.length>0?jsxs(View,{style:a.section,testID:"record-section-notes",children:[jsx(Bt,{title:W.visitNotes,count:t.clinicianNotes.length}),t.clinicianNotes.map(y=>jsxs(View,{style:a.card,children:[jsx(m,{style:[a.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Q(y.observedOn):fe.visitNote}),y.sections.map((g,b)=>jsxs(View,{style:[d.noteSection,b>0?a.rowDivider:null],children:[jsx(m,{style:d.noteLabel,children:Ur(g.section)}),jsx(m,{style:g.text?d.noteBody:d.noteBodyMuted,children:g.text||fe.notRecorded})]},`${g.section}:${b}`)),R(()=>Sc(r,{observedOn:y.observedOn?Q(y.observedOn):null,sections:y.sections.map(g=>({label:Ur(g.section),text:g.text}))},y.noteId),W.askVisit,`records-ask-note-${y.noteId}`)]},y.noteId))]}):null,o&&t&&t.labResults.length>0?jsxs(View,{style:a.section,testID:"record-section-labs",children:[jsx(Bt,{title:W.labResults,count:t.labResults.length}),jsx(View,{style:a.card,children:t.labResults.map((y,g)=>{let b=Qt(y.latest.status),w=Ei(y.latest.at,y.trajectory,y.points.length);return jsxs(View,{style:[a.row,g>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.name}),jsx(m,{style:a.rowValue,children:Et(y.latest.value,y.latest.unit,y.latest.qualitativeResult)}),w?jsx(m,{style:a.rowDetail,children:w}):null]}),jsx(Kt,{label:b.label,tone:fo(y.latest.status)})]},y.markerId)})})]}):null,t&&t.encounters.length>0?jsxs(View,{style:a.section,testID:"record-section-visits",children:[jsx(Bt,{title:W.visits,count:t.encounters.length}),jsx(View,{style:a.card,children:t.encounters.map((y,g)=>{let b=[y.date?Q(y.date):null,y.clinicName,y.veterinarian].filter(w=>w&&w!=="-").join(" \xB7 ");return jsx(View,{style:[a.row,g>0?a.rowDivider:null],children:jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.type?ir(y.type):fe.visit}),b?jsx(m,{style:a.rowDetail,children:b}):null]})},y.encounterId)})})]}):null]}),jsx(hr,{disclaimer:e.disclaimer})]})}i(So,"RecordSections");function aa(e,t){return e>0?e:Object.values(t).reduce((r,o)=>r+o,0)}i(aa,"heldCount");function gf(){let e=L();return useMemo(()=>bf(e),[e])}i(gf,"useLocalStyles");function bf(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth;return StyleSheet.create({sections:{gap:r.lg+r.xs},ask:{marginTop:r.lg},conflictCard:{borderRadius:o.md,borderWidth:1,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},conflictHead:{flexDirection:"row",alignItems:"center",gap:r.sm},conflictTitle:{flex:1,..._(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},candidate:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen,paddingTop:r.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,paddingVertical:r.md},coveragePill:{borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs+1},coverageText:{..._(e,"medium"),fontSize:n.size.caption,lineHeight:n.size.caption+r.xs-1},metaRow:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingBottom:r.md},metaText:{flex:1,..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},pendingText:{..._(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.normal),color:t.text.muted,paddingBottom:r.md},identityLabel:{..._(e,"medium"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},identityValue:{flexShrink:1,textAlign:"right",..._(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},cardTitle:{paddingTop:r.sm},noteSection:{paddingVertical:r.md,gap:r.xs},noteLabel:{..._(e,"bold"),fontSize:n.size.bodyTight,color:t.text.secondary,textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},noteBody:{..._(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.primary},noteBodyMuted:{..._(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.muted,fontStyle:"italic"}})}i(bf,"makeLocalStyles");var _n=Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:i(e=>`Call the clinic at ${e}`,"callAt")});var hf=Math.round(ur/(1024*1024)),rt=Object.freeze({title:i(e=>`Upload ${He(e)}\u2019s records`,"title"),subtitle:i(e=>`Already have lab results, a vet summary, or test reports? Add them here and we\u2019ll read them and pull out ${He(e)}\u2019s health markers.`,"subtitle"),noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${hf} MB each. You can pick several at once. We\u2019ll read them and add the results to your records.`,chooseFiles:"Choose files",chooseFilesA11y:"Choose records to upload",uploading:i((e,t)=>`Uploading ${e+1} of ${t}\u2026`,"uploading"),cancel:"Cancel",cancelA11y:"Cancel these uploads",received:i(e=>`${e===1?"Record received.":`${e} records received.`} We\u2019ll read and review ${e===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,"received"),retryFailed:i(e=>`Retry ${e} that didn\u2019t upload`,"retryFailed"),retryFailedA11y:i(e=>`Retry ${e} failed upload${e>1?"s":""}`,"retryFailedA11y"),addMore:"Add more files",addMoreA11y:"Add more records",done:"Done",doneA11y:"Done, view records",errors:Object.freeze({start:"We couldn\u2019t start that upload. Check your connection and try again.",startPlain:"We couldn\u2019t start that upload. Please try again.",upload:"We couldn\u2019t upload that record. Check your connection and try again."})});var Xc=Math.round(ur/(1024*1024)),Fr=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,t)=>`Uploading ${e+1} of ${t} records`,"uploading"),uploaded:i((e,t)=>`${e} of ${t} records uploaded`,"uploaded")});function Jc(e){let t=Math.round(e.progress*100);switch(e.status){case "done":return Fr.done;case "failed":return Fr.failed;case "uploading":return e.progress>=1?Fr.verifying:`${t}%`;case "queued":return Fr.queued;default:return null}}i(Jc,"uploadItemStatusLabel");function Zc(e){if(e.length===0)return null;let t=i(l=>{let s=l.map(c=>c.name??"");return s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} and ${s.length-3} more`},"nameList"),r=e.filter(l=>l.reason==="too_large"),o=e.filter(l=>l.reason==="unsupported"),n=[];return o.length>0&&n.push(`${t(o)} ${o.length>1?"are not PDFs":"is not a PDF"}`),r.length>0&&n.push(`${t(r)} ${r.length>1?"are":"is"} over ${Xc} MB`),`Didn\u2019t upload: ${n.join("; ")}. We can only read PDFs up to ${Xc} MB right now.`}i(Zc,"skippedFilesMessage");function ed(e){let t=[];for(let r of e)r.status==="skipped"&&r.skipReason!==null&&t.push({name:r.name,reason:r.skipReason});return t}i(ed,"skippedOf");var Ot=Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",updateEmailA11y:"Update clinic email and resend request",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep request",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We\u2019ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function td({request:e,onRecovered:t,canUpload:r=false},o){let[n,l]=useState(""),[s,c]=useState(false),[a,d]=useState(null),[u,p]=useState(false),[f,h]=useState(null),R=useRef(false),v=useRef(false),y=useRef(0);useEffect(()=>(v.current=true,()=>{v.current=false,y.current+=1;}),[o]);let g=f!==null&&f.before===e.updatedAt?{...f.value,canRetrySend:e.canRetrySend===true&&f.value.canRetrySend===true,canUpdateClinicEmail:e.canUpdateClinicEmail===true&&f.value.canUpdateClinicEmail===true,canRevoke:e.canRevoke===true&&f.value.canRevoke===true,canConvertToUpload:e.canConvertToUpload===true&&f.value.canConvertToUpload===true}:e,b=n.trim(),w=b.length<=320&&!Array.from(b).some(I=>I.charCodeAt(0)<=32||I.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(b),x=g.canUpdateClinicEmail===true&&b.length>0,E=g.canRetrySend===true&&!s&&!x,D=g.canUpdateClinicEmail===true&&!s&&w,k=g.canConvertToUpload===true&&r,S=i(async I=>{let Y={retry:E,email:D,revoke:g.canRevoke===true&&u,convert:k};if(R.current||!v.current||!Y[I])return;R.current=true,c(true),d(null);let z=y.current,$=i(()=>v.current&&z===y.current,"live");try{let G=I==="retry"?await o.retryRequest(e.id):I==="email"?await o.updateClinicEmail(e.id,b):I==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!$())return;if(!G.ok){d(G.error);return}if(G.value.id!==e.id||G.value.petRef!==e.petRef){d(q("internalError"));return}h({before:e.updatedAt,value:G.value}),l(""),p(!1),t();}catch{$()&&d(q("internalError"));}finally{R.current=false,$()&&c(false);}},"run");return {request:g,email:n,busy:s,error:a,canRetry:E,canUpdateEmail:D,canConvert:k,hasEmailEdit:x,confirmingRevoke:u&&g.canRevoke===true,emailInvalid:b.length>0&&!w,setEmail(I){R.current||(l(I),d(null));},retry:i(()=>S("retry"),"retry"),updateEmail:i(()=>S("email"),"updateEmail"),revoke:i(()=>S("revoke"),"revoke"),convert:i(()=>S("convert"),"convert"),askRevoke(){!R.current&&g.canRevoke===true&&p(true);},keepRequest(){R.current||p(false);}}}i(td,"useRecordsRecovery");var vf=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],xf=["requested","awaiting_upload","records_received","processing","ready"],wf=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],In=Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),kt=Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn\u2019t read this one automatically",manualReview:"Checking these by hand so nothing\u2019s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),Cf=Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),Ef=Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function Sf(e){return e.wireStatus??Ef[e.status]??"sent"}i(Sf,"wireStatusOf");function kf(e,t){return e!=="awaiting_response"||t<=0?null:`${t} ${t===1?"reminder":"reminders"} sent`}i(kf,"reminderProgressLabel");function Tf(e){switch(e){case "submitted":case "sent":return 1;case "awaiting_response":return 2;case "records_received":return 3;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 4;case "published":return 5;default:return -1}}i(Tf,"reachedRailIndex");function _f(e){switch(e.dispatchStatus){case "sent":return kt.delivered;case "preparing":case "queued":case "sending":return kt.emailing;case "failed":return kt.bounced;default:return null}}i(_f,"deliveryDetail");function Pf(e,t){return kf(t,e.reminderCount??0)??kt.waiting}i(Pf,"awaitingDetail");function If(e,t,r){let o=t.source==="owner_provided"||!!t.convertedToUploadAt;switch(e){case "sent_to_clinic":return _f(t);case "awaiting_clinic":return Pf(t,r);case "awaiting_upload":return kt.upload;case "records_received":return o?kt.ownerAdded:kt.clinicSent;case "processing":return kt.preparing;case "ready":return kt.ready;default:return null}}i(If,"railDetail");function Df(e,t){return !!e.reviewStartedAt||t==="parsing_failed"||t==="review_email_failed"}i(Df,"tookReviewBranch");function Af(e,t,r){if(e.key!=="processing"||!Df(t,r))return [e];let o=r==="parsing_failed",n=r==="published",l=n?"done":o?"current":"done",s=n?"done":o?"upcoming":"current";return [{key:"parsing_failed",title:In.parsing_failed,detail:kt.parsingFailed,at:null,state:l},{key:"manual_review",title:In.manual_review,detail:kt.manualReview,at:t.reviewStartedAt??null,state:s}]}i(Af,"expandProcessingPhase");function Of(e){switch(e){case "awaiting_upload":return 3;case "records_received":return 4;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 5;case "published":return 6;default:return 3}}i(Of,"convertedReachedIndex");function rd(e){return {key:"awaiting_clinic",title:kt.switchedTitle,detail:kt.switched,at:e.convertedToUploadAt??null,state:"done"}}i(rd,"convertedClinicSwitchEvent");function Lf(e){switch(e){case "submitted":case "sent":return 0;case "awaiting_upload":return 1;case "records_received":return 2;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 3;case "published":return 4;default:return -1}}i(Lf,"ownerReachedIndex");function Vf(e,t,r){switch(e){case "requested":return t.createdAt||null;case "awaiting_clinic":return t.lastReminderAt??null;case "processing":return t.parsingStartedAt??t.reviewStartedAt??null;case "ready":return r==="published"&&t.updatedAt||null;default:return null}}i(Vf,"railTimestamp");function nd(e,t,r,o){return {key:e,title:In[e],detail:If(e,t,r),at:Vf(e,t,r),state:o}}i(nd,"railEvent");function lr(e,t){return {key:e,title:In[e],detail:Cf[e]??null,at:t.updatedAt||null,state:"failed"}}i(lr,"terminalEvent");function ca(e,t,r,o,n){return e.map((l,s)=>{let c=n?.(l)??null;if(c!==null)return c;let a=o==="published"||s<t?"done":s===t?"current":"upcoming";return nd(l,r,o,a)}).flatMap(l=>Af(l,r,o))}i(ca,"walkRail");function da(e){let t=Sf(e),r=i(n=>nd(n,e,t,"done"),"done");if(t==="revoked")return [r("requested"),lr("revoked",e)];if(e.convertedToUploadAt)return t==="failed"?[r("requested"),r("sent_to_clinic"),rd(e),r("awaiting_upload"),r("records_received"),lr("processing_failed",e)]:ca(wf,Of(t),e,t,n=>n==="awaiting_clinic"?rd(e):null);if(e.source==="owner_provided"){if(t==="failed"||t==="clinic_declined")return [r("requested"),r("awaiting_upload"),r("records_received"),lr("processing_failed",e)];let n=Lf(t);return ca(xf,n<0?1:n,e,t)}if(t==="clinic_declined")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),lr("clinic_declined",e)];if(t==="clinic_responded_no_records")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),lr("clinic_no_records",e)];if(t==="failed"){let n=e.failureCode??null;return n==="no_response"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),lr("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[r("requested"),lr("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),r("records_received"),lr("processing_failed",e)]:[r("requested"),lr("delivery_failed",e)]}let o=Tf(t);return ca(vf,o<0?1:o,e,t)}i(da,"buildRequestTimeline");var zf=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),ko=24,ua=10;function _o({request:e}){let t=Bf(),r=da(e);return jsx(View,{style:t.container,accessibilityRole:"summary",children:r.map((o,n)=>jsx(Nf,{event:o,isLast:n===r.length-1,styles:t},o.key))})}i(_o,"RequestTimeline");function Nf({event:e,isLast:t,styles:r}){let o=e.at?Q(e.at):null,n=[e.title,e.detail,o,zf[e.state]].filter(Boolean);return jsxs(View,{style:r.row,accessible:true,accessibilityRole:"text",accessibilityLabel:n.join(", "),testID:`records-timeline-${e.key}`,children:[jsxs(View,{style:r.railColumn,children:[jsx(Mf,{state:e.state,styles:r}),t?null:jsx(View,{style:[r.connector,e.state==="done"&&r.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),jsxs(View,{style:r.body,children:[jsxs(View,{style:r.titleRow,children:[jsx(m,{style:[r.title,e.state==="current"&&r.titleCurrent,e.state==="failed"&&r.titleFailed,e.state==="upcoming"&&r.titleUpcoming],children:e.title}),o?jsx(m,{style:r.date,children:o}):null]}),e.detail?jsx(m,{style:[r.detail,e.state==="upcoming"&&r.detailUpcoming],children:e.detail}):null]})]})}i(Nf,"TimelineRow");function Mf({state:e,styles:t}){return e==="done"?jsx(View,{style:[t.dot,t.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:[t.glyph,t.glyphOnBrand],children:"\u2713"})}):e==="failed"?jsx(View,{style:[t.dot,t.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:t.glyph,children:"!"})}):e==="current"?jsx(View,{style:[t.dot,t.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(View,{style:t.dotCurrentCore})}):jsx(View,{style:[t.dot,t.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(Mf,"TimelineDot");function Bf(){let e=L();return useMemo(()=>Hf(e),[e])}i(Bf,"useStyles");function Hf(e){let{color:t,type:r}=e,{size:o}=r;return StyleSheet.create({container:{gap:0},row:{flexDirection:"row",alignItems:"flex-start",gap:12},railColumn:{alignItems:"center",width:ko},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},dot:{width:ko,height:ko,borderRadius:ko/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:t.brand},dotFailed:{backgroundColor:t.danger},dotCurrent:{borderWidth:2,borderColor:t.brand,backgroundColor:t.surface},dotCurrentCore:{width:ua,height:ua,borderRadius:ua/2,backgroundColor:t.brand},dotUpcoming:{borderWidth:2,borderColor:t.borderHairlineGreen,backgroundColor:t.surface},glyph:{..._(e,"bold"),fontSize:o.caption,lineHeight:o.caption+2,color:t.surface},glyphOnBrand:{color:t.onPrimary},connector:{width:2,flex:1,minHeight:22,backgroundColor:t.borderHairlineGreen,marginVertical:2},connectorDone:{backgroundColor:t.brand},title:{flex:1,..._(e,"bold"),fontSize:o.body,lineHeight:o.body+4,color:t.text.primary},titleCurrent:{color:t.brandInk},titleFailed:{color:t.danger},titleUpcoming:{color:t.text.muted,..._(e,"regular")},date:{..._(e,"regular"),fontSize:o.caption,lineHeight:o.caption+4,color:t.text.muted},detail:{..._(e,"regular"),fontSize:o.bodyTight,lineHeight:o.bodyTight+4,color:t.text.muted},detailUpcoming:{color:t.text.muted,opacity:.7}})}i(Hf,"makeStyles");function Yr(e,t,r){let o=xr(e,r);switch(o.kind){case "consent_required":return jsx($f,{onGrant:t});case "consent_unavailable":return jsx(Wf,{});case "session_required":return jsx(Gf,{});case "withheld":return jsx(Yf,{});case "pet_not_found":case "error":return jsx(Kf,{error:o.error,onRetry:e.refresh});default:return pr(o)}}i(Yr,"renderErrorFamily");function Kr(e,t){return ()=>{let r=ea(t,e.consent);if(r.length===0)return;let o=`records-consent-${Date.now().toString(36)}`;e.grantConsent(r,o);}}i(Kr,"makeGrantHandler");function ad({records:e}){let t=An(),r=e.uploadQueue;if(r.length===0)return null;let o=r.filter(s=>s.status!=="skipped"),n=o.filter(s=>s.status==="done").length,l=Zc(ed(r));return jsxs(View,{style:t.timeline,testID:"records-upload-queue",children:[l!==null?jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:t.errorText,children:l}):null,o.length>0?jsx(View,{accessibilityLiveRegion:"polite",accessibilityLabel:e.isUploading?Fr.uploading(n,o.length):Fr.uploaded(n,o.length),children:o.map(s=>{let c=Math.round(s.progress*100);return jsxs(View,{style:t.row,testID:`records-upload-file-${s.status}`,children:[jsx(m,{style:t.rowLabel,children:s.name??""}),jsx(m,{style:t.rowValue,children:Jc(s)}),s.status==="uploading"?jsx(View,{style:t.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:c},children:jsx(View,{style:[t.progressFill,{width:`${c}%`}]})}):null,s.status==="failed"&&s.error?jsx(m,{style:t.timelineMeta,children:s.error.displayMessage}):null]},s.key)})}):null]})}i(ad,"UploadQueue");function $f({onGrant:e}){let t=An();return jsx(View,{style:t.centered,accessible:true,accessibilityRole:"alert",accessibilityLabel:ce.consentRequired,children:jsx(Pressable,{onPress:e,accessibilityRole:"button",accessibilityLabel:ce.allow,style:t.primaryButton,children:jsx(m,{style:t.primaryLabel,children:ce.allow})})})}i($f,"ConsentRequiredState");function ya({label:e,glyph:t}){let r=An();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e);},[e]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:e,children:[jsx(View,{style:t==="withheld"?r.withheldGlyph:r.emptyGlyph}),jsx(m,{style:r.errorText,children:e})]})}i(ya,"AlertState");function Wf(){return jsx(ya,{label:ce.consentRequired,glyph:"empty"})}i(Wf,"ConsentUnavailableState");function Gf(){return jsx(ya,{label:ce.sessionRequired,glyph:"empty"})}i(Gf,"SessionRequiredState");function Yf(){return jsx(ya,{label:ce.recordUnavailable,glyph:"withheld"})}i(Yf,"WithheldState");function Kf({error:e,onRetry:t}){let r=An();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e.displayMessage);},[e.displayMessage]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:[jsx(m,{style:r.errorText,children:e.displayMessage}),e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:ce.retry,style:r.primaryButton,children:jsx(m,{style:r.primaryLabel,children:ce.retry})}):null]})}i(Kf,"ErrorState");function sd({call:e,prompt:t}){let r=An(),o=t.trim().length>0?t:_n.fallbackPrompt;return jsxs(View,{style:r.callCard,accessibilityRole:"summary",children:[jsx(m,{style:r.timelineLabel,children:_n.heading}),jsx(m,{style:r.timelineMeta,children:o}),jsx(Pressable,{onPress:()=>{Linking?.openURL?.(e.dial);},accessibilityRole:"button",accessibilityLabel:_n.callAt(e.phone),style:r.linkButton,testID:"records-call-clinic",children:jsx(m,{style:r.linkLabel,children:_n.call})})]})}i(sd,"ClinicCallCard");function An(){let e=L();return useMemo(()=>Qf(e),[e])}i(An,"useStyles");function Qf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c,letterSpacing:a}=n,d=Je(l.recordCard,StyleSheet.hairlineWidth),u=ot(l.recordCard),p=i((b,w)=>Math.round(b*w),"lh"),f=StyleSheet.hairlineWidth,h=r.xxl*3+r.xl,R=r.xxl+r.md,v=r.xxl+r.sm,y=e.brightness==="dark"?t.errorRed:t.danger,g={shadowColor:t.brand,shadowOffset:{width:0,height:r.xs},shadowRadius:r.sm,shadowOpacity:.08,elevation:r.xs};return StyleSheet.create({container:{flex:1,minHeight:h,backgroundColor:t.background},body:{flex:1},centered:{minHeight:h,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:v,height:v,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:f,borderColor:t.brandBorder},withheldGlyph:{width:v,height:v,borderRadius:o.sm,backgroundColor:t.badgeBgCaution,borderWidth:f,borderColor:t.cautionAccent},errorText:{..._(e,"regular"),fontSize:s.subtitle,lineHeight:p(s.subtitle,c.snug),color:y,textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...g,...Je(l.primaryButton)},primaryLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,letterSpacing:a.tight,...ot(l.primaryButton)},linkButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...g,...Je(l.primaryButton)},linkLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,letterSpacing:a.tight,...ot(l.primaryButton)},disabledButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.surfaceSubtle,borderWidth:f,borderColor:t.brandBorder},disabledLabel:{..._(e,"bold"),color:t.text.muted,fontSize:s.body,letterSpacing:a.tight},list:{flex:1},listContent:{padding:r.lg,gap:r.md},timeline:{paddingVertical:r.md,paddingHorizontal:r.lg,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,gap:r.xs,...g,...d},timelineTitle:{..._(e,"bold"),fontSize:s.heading,lineHeight:p(s.heading,c.snug),color:t.text.primary,letterSpacing:a.tight,...u},timelineLabel:{..._(e,"bold"),fontSize:s.subtitle,lineHeight:p(s.subtitle,c.snug),color:t.text.secondary,letterSpacing:a.tight,...u},callCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,...d},timelineMeta:{..._(e,"regular"),fontSize:s.bodyTight,lineHeight:p(s.bodyTight,c.normal),color:t.text.muted,...u},recordBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,...g,...d},row:{flexDirection:"row",justifyContent:"space-between",gap:r.md,paddingVertical:r.xs,borderBottomWidth:f,borderBottomColor:t.borderHairlineGreen},rowLabel:{..._(e,"regular"),fontSize:s.body,lineHeight:p(s.body,c.normal),color:t.text.muted,flexShrink:1,...u},rowValue:{..._(e,"medium"),fontSize:s.body,lineHeight:p(s.body,c.normal),color:t.text.primary,textAlign:"right",flexShrink:1,...u},disclaimer:{..._(e,"regular"),fontSize:s.caption,lineHeight:p(s.caption,c.normal),color:t.text.muted,marginTop:r.md},progressTrack:{height:r.xs,borderRadius:o.pill,backgroundColor:t.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:t.brand}})}i(Qf,"makeStyles");var Zf=i((e,t)=>e.getRecordDepth(t),"readDepth"),eg=i(e=>!e.available,"depthEmpty");function ha(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack","onAsk"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(tg,{...o,style:t})})}i(ha,"EverfurRecordsDashboard");function tg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,style:c}){let a=be(),d=Ra(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=Qi(e),f=Ut(e,Zf,eg),[h,R]=useState(null),v=useCallback((C,T)=>R({marker:C,point:T}),[]),y=useMemo(()=>qr(o,u.consent),[o,u.consent]),g=useMemo(()=>Kr(u,o),[u,o]),b=p.markers?.markers??[],w=b.length>0,x=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,E=Qn(u.requests,e),D=si({hasMarkers:w,requests:u.requests,petRef:e}),k=li({recordLoading:u.status==="loading",hasFullRecord:x,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:w,requestsLoading:u.status==="loading",dashboardState:D,drivingRequest:E}),S=p.markers?.disclaimer??u.record?.disclaimer??"",I=i(()=>{u.refresh(),p.refresh(),f.refresh();},"retryAll"),Y=f.value!==null&&!f.value.withheld&&f.value.available?f.value:null,z=He(t),$=s&&p.markers?.summary?()=>{let C=Rc(t,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);s(C.prompt,C.entityRef);}:void 0,G=s?C=>{let T=hc(t,{canonicalName:C.name,markerId:C.markerId,latestValueText:C.latest?Et(C.latest.value,C.unit,C.latest.qualitativeResult):null,statusText:C.latest?Qt(C.latest.status).label:null,trajectoryText:Hr(C.trajectory,C.points.length),meaningText:C.meaning});s(T.prompt,T.entityRef);}:void 0,Z=s&&h?()=>{let{marker:C,point:T}=h,A=vc(t,{canonicalName:C.name,valueText:Et(T.value,C.unit,T.qualitativeResult),collectedAt:Q(T.at),sourceClinic:T.sourceClinic,referenceText:T.refLow!==null||T.refHigh!==null?go(T,C.unit):null,flagged:T.status==="above"?"above":T.status==="below"?"below":null,reviewed:T.reviewed,entityId:T.docId??C.markerId});R(null),s(A.prompt,A.entityRef);}:void 0,oe=jsxs(Fragment,{children:[p.markers?.summary?jsx(View,{style:a.inset,children:jsx(Dc,{summary:p.markers.summary,onAsk:$,testID:"dashboard-marker-summary"})}):null,jsx(m,{style:a.lead,children:dt.lead(t)}),jsx(qc,{markers:b,onPointPress:v,onAsk:G})]}),Ee=i(C=>n?jsxs(View,{style:[a.inset,d.actions],children:[C?jsx(fa,{label:dt.viewFullRecord,onPress:()=>n({name:"record"}),testID:"dashboard-full-record-action"}):null,jsx(fa,{label:dt.viewTimeline,onPress:()=>n({name:"timeline"}),testID:"dashboard-timeline-action"})]}):null,"actions"),H;if(u.status==="error"){let C=xr(u,y);H=C.kind==="error"||C.kind==="pet_not_found"?jsx(Qe,{variant:wt(C.error),message:C.error.displayMessage,onAction:C.error.retryable?I:void 0,testID:"dashboard-error"}):Yr(u,g,y);}else switch(k){case "loading":H=jsx(io,{testID:"dashboard-loading"});break;case "record":H=jsxs(ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-record",children:[w?oe:p.status==="error"?jsx(View,{style:[a.inset,d.actions],children:jsx(fa,{label:dt.retryMarkers,onPress:I,testID:"dashboard-markers-retry"})}):null,jsx(View,{style:a.inset,children:u.record?jsx(So,{record:u.record,depth:Y,petName:t,showLabs:!w,onNavigate:n,onAsk:s}):null}),Ee(true)]});break;case "error":H=jsx(Qe,{variant:wt(p.error??u.error),message:(p.error??u.error)?.displayMessage,onAction:(p.error??u.error)?.retryable?I:void 0,testID:"dashboard-error"});break;case "in_progress":H=jsxs(ScrollView,{contentContainerStyle:a.content,testID:"dashboard-in-progress",children:[E?jsx(rg,{request:E,petName:z,onOpen:n?()=>n({name:"request",requestId:E.id}):void 0,onAsk:s?()=>{let C=xc(t,{clinicName:E.clinicName??null,statusLabel:En(E),status:E.status,heldItemCount:E.heldItemCount},E.id);s(C.prompt,C.entityRef);}:void 0}):null,jsx(hr,{disclaimer:S})]});break;case "none":H=jsxs(ScrollView,{contentContainerStyle:a.content,testID:"dashboard-request-prompt",children:[jsxs(View,{style:d.promptCard,children:[jsxs(View,{style:d.promptHeader,children:[jsx(View,{style:d.promptGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.promptTitle,children:_r.title(t)})]}),jsx(m,{style:d.promptBody,children:_r.body}),n?jsxs(Fragment,{children:[jsx(re,{label:_r.requestFromClinic,accessibilityLabel:_r.requestFromClinicA11y(t),onPress:()=>n({name:"clinicPicker"}),style:d.promptCta,testID:"dashboard-request-prompt-clinic"}),jsx(re,{label:_r.uploadDocument,kind:"outline",accessibilityLabel:_r.uploadDocumentA11y(t),onPress:()=>n({name:"upload"}),style:d.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),jsx(hr,{disclaimer:S})]});break;case "labs_only":H=jsxs(ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-labs-only",children:[oe,jsx(View,{style:a.inset,children:jsx(hr,{disclaimer:S})}),Ee(false)]});break;default:H=pr(k);}return jsxs(View,{style:[a.root,c],children:[jsx(et,{title:dt.title,onBack:l,testID:"dashboard-header",right:n?jsx(Pressable,{onPress:()=>n({name:"timeline"}),accessibilityRole:"button",accessibilityLabel:dt.openTimeline,hitSlop:12,style:d.headerButton,testID:"dashboard-timeline-link",children:jsx(fl,{})}):void 0}),jsx(View,{style:a.body,children:H}),jsx(Fc,{marker:h?.marker??null,point:h?.point??null,onClose:()=>R(null),onAsk:Z}),jsx(Me,{})]})}i(tg,"DashboardBody");function fa({label:e,onPress:t,testID:r}){let o=Ra();return jsxs(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:e,style:o.actionRow,testID:r,children:[jsxs(View,{style:o.actionLeft,children:[jsx(View,{style:o.actionIcon,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:o.actionLabel,children:e})]}),jsx(Pr,{})]})}i(fa,"ActionRow");function rg({request:e,petName:t,onOpen:r,onAsk:o}){let n=be(),l=Ra(),s=e.clinicName?.trim()||Mr.title(t),c=En(e),a=jsxs(View,{style:l.inProgressInner,children:[jsxs(View,{style:l.inProgressHead,children:[jsx(m,{style:l.inProgressTitle,children:s}),r?jsx(Pr,{}):null]}),jsx(_o,{request:e}),c.length>0?jsx(View,{style:n.statusCard,children:jsx(m,{style:n.statusText,children:c})}):null]});return jsxs(View,{style:l.inProgressCard,testID:"dashboard-in-progress-card",accessibilityRole:"summary",accessible:r?false:void 0,accessibilityLabel:r?void 0:Mr.a11y(t),children:[r?jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Mr.openA11y(t,c),testID:"dashboard-in-progress-open",children:a}):a,o?jsx(re,{label:Mr.ask,kind:"ask",accessibilityLabel:Mr.askA11y,onPress:o,testID:"dashboard-in-progress-ask"}):null]})}i(rg,"InProgressCard");function Ra(){let e=L();return useMemo(()=>ng(e),[e])}i(Ra,"useLocalStyles");function ng(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=r.xxl+r.md;return StyleSheet.create({headerButton:{width:s,height:s,alignItems:"center",justifyContent:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},actionIcon:{width:r.lg+r.xs/2,height:r.lg+r.xs/2,borderRadius:o.xs,backgroundColor:t.brandSoft,borderWidth:l,borderColor:t.brandBorder},actionLabel:{flex:1,..._(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},inProgressCard:{borderRadius:o.lg-r.xs/2,backgroundColor:t.surface,borderWidth:l,borderColor:t.brandBorder,padding:r.lg+r.xs/2,gap:r.lg},inProgressInner:{gap:r.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},inProgressTitle:{flex:1,..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),color:t.text.primary},promptCard:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:l,borderColor:t.borderRingCream,paddingHorizontal:r.lg+r.xs,paddingVertical:r.lg+r.xs/2},promptHeader:{flexDirection:"row",alignItems:"center",gap:r.xs+1},promptGlyph:{width:r.xl+1,height:r.xl+1,borderRadius:o.xs,borderWidth:2,borderColor:t.warningStrong},promptTitle:{flex:1,..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),letterSpacing:n.letterSpacing.headerBrand,color:t.brandInk},promptBody:{marginTop:r.sm-1,..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:r.lg+r.xs,color:t.text.primary},promptCta:{marginTop:r.sm-1,minHeight:r.xxl+r.sm},promptCtaSecondary:{marginTop:r.sm,minHeight:r.xxl+r.sm}})}i(ng,"makeLocalStyles");var Io=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function dd(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(dd,"toMillis");function ud(e){let t=[...e.visits.map((r,o)=>({key:`visit-${o}-${r.visitId}`,kind:"visit",kindLabel:fe.kind.visit,at:r.visitDate,date:Q(r.visitDate),title:r.summary??fe.clinicVisit,detail:r.veterinarian?fe.doctor(r.veterinarian):null,docId:r.docId})),...e.vaccines.map((r,o)=>{let n=[];return r.lot&&n.push(fe.lot(r.lot)),r.expiresOn&&n.push(fe.expires(Q(r.expiresOn))),{key:`vaccine-${o}-${r.vaccineId}`,kind:"vaccine",kindLabel:fe.kind.vaccine,at:r.administeredOn,date:Q(r.administeredOn),title:r.product||fe.kind.vaccine,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}}),...e.weights.map((r,o)=>({key:`weight-${o}-${r.weightId}`,kind:"weight",kindLabel:fe.kind.weight,at:r.observedOn,date:Q(r.observedOn),title:Cl(r.weightKg),detail:null,docId:r.docId})),...e.medications.map((r,o)=>{let n=[r.dose,r.route,r.frequency].filter(l=>!!l);return {key:`medication-${o}-${r.medicationId}`,kind:"medication",kindLabel:fe.kind.medication,at:r.startedOn,date:Q(r.startedOn),title:r.drugName||fe.kind.medication,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}})];return Object.freeze(t.sort((r,o)=>{let n=dd(r.at),l=dd(o.at);return n===null&&l===null?Io[r.kind]-Io[o.kind]:n===null?1:l===null?-1:l!==n?l-n:Io[r.kind]-Io[o.kind]}))}i(ud,"buildTimelineRows");var cg=300,dg=i((e,t)=>e.getTimeline(t),"readTimeline"),ug=i(e=>e.isEmpty,"timelineEmpty");var pg=i(e=>e.contributions.length===0,"contributionsEmpty");function yd({petRef:e,style:t,onBack:r}){let o=Ut(e,dg,ug);return jsx(gd,{state:o,style:t,onBack:r,header:jsx(et,{title:fe.timeline,onBack:an(r),testID:"timeline-header"}),loading:jsx(Pl,{testID:"timeline-loading"}),empty:jsx(Qe,{variant:"no_records",testID:"timeline-empty"}),render:n=>jsx(fg,{timeline:n})})}i(yd,"EverfurRecordsTimeline");function fd({petRef:e,docId:t,style:r,onBack:o}){let n=useCallback((c,a)=>c.getDocumentContributions(a,t),[t]),l=Ut(e,n,pg,t),s=l.value?.document?.title?.trim()||fe.uploadedDocument;return jsx(gd,{state:l,style:r,onBack:o,header:jsx(et,{title:s,onBack:an(o),testID:"contributions-header"}),empty:jsx(Qe,{variant:"no_records",testID:"contributions-empty"}),render:c=>jsx(gg,{view:c})})}i(fd,"EverfurDocumentContributions");function gd({state:e,style:t,header:r,loading:o,empty:n,render:l,onBack:s}){let c=va();return jsx(Ne,{capability:"records",style:t,...Be(an(s),Ze),children:jsxs(View,{style:[c.container,t],children:[r??null,jsx(View,{style:c.body,children:mg(e,l,c,o,n)}),jsx(Me,{})]})})}i(gd,"DepthSurface");function mg(e,t,r,o,n){switch(e.status){case "loading":return o??jsx(yg,{styles:r});case "empty":return n??jsx(View,{style:r.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:ce.empty,children:jsx(View,{style:r.emptyGlyph})});case "error":return e.error?jsx(Qe,{variant:wt(e.error),message:e.error.displayMessage,onAction:e.error.retryable?e.refresh:void 0,testID:"depth-error"}):null;case "populated":return e.value===null||e.value.withheld?null:t(e.value);default:return null}}i(mg,"renderState");function yg({styles:e}){let[t,r]=useState(false);return useEffect(()=>{let o=setTimeout(()=>r(true),cg);return ()=>clearTimeout(o)},[]),jsx(View,{style:e.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:ce.loading,children:t?jsx(ActivityIndicator,{}):null})}i(yg,"LoadingState");function fg({timeline:e}){let t=va(),r=ud(e);return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.timelineContent,accessibilityLabel:fe.timeline,children:[e.disclaimer.length>0?jsx(View,{style:t.timelineBand,accessible:true,accessibilityRole:"text",accessibilityLabel:dt.important(e.disclaimer),children:jsx(m,{style:t.timelineBandText,children:e.disclaimer})}):null,r.map((o,n)=>jsxs(View,{children:[n>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,accessible:true,accessibilityRole:"text",accessibilityLabel:[o.kindLabel,o.date,o.title,o.detail].filter(Boolean).join(", "),testID:`records-timeline-row-${o.kind}`,children:[jsx(View,{style:t.timelineBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.topLine,children:[jsx(m,{style:t.timelineKind,children:o.kindLabel}),jsx(m,{style:t.date,children:o.date})]}),jsx(m,{style:t.timelineTitle,children:o.title}),o.detail?jsx(m,{style:t.rowDetail,children:o.detail}):null]})]})]},o.key))]})}i(fg,"TimelineBody");function gg({view:e}){let t=va();return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.listContent,accessibilityLabel:ce.records,children:[e.document?.receivedAt?jsx(m,{style:t.rowDetail,children:Q(e.document.receivedAt)}):null,jsx(View,{style:t.card,children:e.contributions.map(r=>jsxs(View,{style:t.row,accessible:true,accessibilityRole:"text",children:[jsx(m,{style:t.rowTitle,children:r.label}),jsx(m,{style:t.rowValue,children:Br(r.value,r.unit)}),r.observedAt?jsx(m,{style:t.rowDetail,children:Q(r.observedAt)}):null]},r.key))})]})}i(gg,"ContributionsBody");function va(){let e=L();return useMemo(()=>bg(e),[e])}i(va,"useStyles");function bg(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((y,g)=>Math.round(y*g),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl*3+r.xl,p=r.xxl+r.md,f=e.brightness==="dark"?t.errorRed:t.danger,h=ot(l.recordCard),R=i((y,g,b,w="regular")=>({..._(e,w),fontSize:y,lineHeight:a(y,g),color:b}),"text"),v=i((y,g,b,w="regular")=>({...R(y,g,b,w),...h}),"inCard");return StyleSheet.create({container:{flex:1,minHeight:u,backgroundColor:t.background},body:{flex:1},centered:{minHeight:u,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:r.xxl+r.sm,height:r.xxl+r.sm,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},errorText:{...R(s.subtitle,c.snug,f),textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:p,minWidth:p,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...Je(l.primaryButton)},primaryLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,...ot(l.primaryButton)},list:{flex:1},listContent:{padding:r.lg,gap:r.md},section:{gap:r.sm},heading:{...R(s.heading,c.snug,t.text.primary,"bold")},card:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:d,borderColor:t.brandBorder,...Je(l.recordCard,d)},row:{gap:r.xs,paddingVertical:r.xs,borderBottomWidth:d,borderBottomColor:t.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:r.md},kindLabel:{...v(s.caption,c.normal,t.text.muted,"medium")},date:v(s.caption,c.normal,t.text.muted),rowTitle:{...v(s.body,c.normal,t.text.primary,"bold")},rowValue:{...v(s.body,c.normal,t.text.primary,"medium")},rowDetail:v(s.bodyTight,c.normal,t.text.muted),rowMuted:{...v(s.bodyTight,c.normal,t.text.muted),opacity:.7},chip:{...R(s.caption,c.normal,t.text.primary),alignSelf:"flex-start",paddingHorizontal:r.sm,paddingVertical:r.xs,borderRadius:o.pill},chipNeutral:{backgroundColor:t.badgeBgNeutral},chipCaution:{backgroundColor:t.badgeBgCaution},chipCritical:{backgroundColor:t.badgeBgCritical},disclaimer:{...R(s.caption,c.normal,t.text.muted),marginTop:r.md},timelineContent:{paddingBottom:r.xxl},timelineBand:{flexDirection:"row",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft,marginHorizontal:r.lg,marginTop:r.xs,marginBottom:r.md},timelineBandText:{flex:1,...R(s.caption,c.normal,t.text.secondary)},timelineSeparator:{height:d,backgroundColor:t.brandBorder,marginLeft:Ti},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBubble:{width:r.xxl+r.xs/2,height:r.xxl+r.xs/2,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},timelineBody:{flex:1,gap:r.xs-1},timelineKind:{..._(e,"mono"),fontSize:s.micro,lineHeight:s.bodyTight,letterSpacing:n.letterSpacing.eyebrow/3,textTransform:"uppercase",color:t.text.secondary},timelineTitle:{...R(s.body,c.normal,t.text.primary,"medium")}})}i(bg,"makeStyles");function xa(e,t={}){let r=sr(),{userRef:o}=ke(),n=t.now??Date.now,[l,s]=useState(null),[c,a]=useState(true),[d,u]=useState(null),[p,f]=useState(null),h=p===true,[R,v]=useState({}),[y,g]=useState(false),[b,w]=useState(null),[x,E]=useState(false),[D,k]=useState(false),S=Mn(e),I=useRef(0),Y=useRef(true),z=useCallback(async()=>{let T=I.current+=1;if(a(true),u(null),o===null){s(null),a(false);return}let A=await r.listShares(e);T!==I.current||!Y.current||(A.ok?(s(A.value),f(true)):vr(A.error)?(s(null),f(false)):(s(null),u(A.error),bd(A)&&f(true)),a(false));},[r,e,o]);useEffect(()=>(Y.current=true,z(),()=>{Y.current=false,I.current+=1;}),[z]);let $=useRef(S);useEffect(()=>{$.current!==S&&($.current=S,v({}),k(true),z());},[S,z]);let G=useCallback(async()=>{g(true);let T=await r.createShare(e);return Y.current&&(g(false),T.ok?(v(A=>({...A,[T.value.shareId]:T.value.shareUrl})),z()):vr(T.error)?f(false):tr(T.error)&&k(true)),T},[r,e,z]),Z=useCallback(async T=>{w(T);let A=await r.revokeShare(e,T);return Y.current&&(w(null),z()),A},[r,e,z]),oe=useCallback(async()=>{E(true);let T=await r.getPdfLink(e);return Y.current&&(E(false),!T.ok&&tr(T.error)&&k(true)),T},[r,e]),Ee=useCallback(()=>{k(false),z();},[z]),H=useMemo(()=>El(l??[],R,n()),[l,R,n]),C=c?"loading":d!==null?"error":H.length===0?"empty":"populated";return useMemo(()=>({status:C,rows:H,available:h,consentRequired:D,error:d,creating:y,revokingId:b,preparingPdf:x,createLink:G,revoke:Z,pdfLink:oe,refresh:Ee}),[C,H,h,D,d,y,b,x,G,Z,oe,Ee])}i(xa,"useRecordShares");function bd(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(bd,"answeredBehindGate");function hd(e){return e.available||e.status!=="empty"}i(hd,"sharesListShown");function wa(e){let t=sr(),{userRef:r}=ke(),o=useMemo(()=>({}),[t,e,r]),[n,l]=useState({scope:o,lit:null});useEffect(()=>{if(r===null)return;let c=true;return t.listShares(e).then(a=>{c&&(!a.ok&&vr(a.error)?l({scope:o,lit:false}):bd(a)&&l({scope:o,lit:true}));},()=>{}),()=>{c=false;}},[t,e,r,o]);let s=n.scope===o?n.lit:null;return useMemo(()=>({lit:s}),[s])}i(wa,"useRecordsDepthProbe");function Ca(e){let t=sr(),o=wa(e).lit===true,[n,l]=useState(false),[s,c]=useState(null),a=useRef(true);useEffect(()=>(a.current=true,()=>{a.current=false;}),[]);let d=useCallback(async()=>{l(true),c(null);let u=await t.getPdfLink(e);return a.current&&(l(false),u.ok||c(u.error)),u},[t,e]);return useMemo(()=>({preparing:n,available:o,error:s,pdfLink:d}),[n,o,s,d])}i(Ca,"useRecordPdfLink");var Tt=W.document,xd=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),xg=i((e,t)=>e.getRecordDepth(t),"readDepth"),wg=i(e=>!e.available,"depthEmpty");function Ea(e){let{style:t,renderPending:r,...o}=Fe(e,["onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Eg,{...o,style:t})})}i(Ea,"EverfurRecordDocument");function Cg(e,t){return e.identity.length===0&&e.entities.length===0&&e.forwardLooking.length===0&&(t===null||t.labResults.length===0&&t.physicalExams.length===0&&t.clinicianNotes.length===0)}i(Cg,"documentIsEmpty");function Eg({petRef:e,petName:t,controller:r,consentVersion:o,onBack:n,onOpenUrl:l,style:s}){let c=be(),a=wd(),d=L(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=Ut(e,xg,wg),f=Ca(e),h=useMemo(()=>qr(o,u.consent),[o,u.consent]),R=useMemo(()=>Kr(u,o),[u,o]),v=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,y=u.record,g=i(()=>{f.pdfLink().then(x=>{if(!x.ok)return;kr(l??(D=>Linking.openURL(D)),x.value.downloadUrl,"record_pdf");});},"download"),b,w=false;if(u.status==="loading"||p.status==="loading"&&y!==null)b=jsx(View,{style:a.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:dt.loading,testID:"record-document-loading",children:jsx(ActivityIndicator,{color:d.color.brandInk})});else if(u.status==="error"){let x=xr(u,h);b=x.kind==="error"||x.kind==="pet_not_found"?jsx(Qe,{variant:wt(x.error),message:x.error.displayMessage,onAction:x.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):Yr(u,R,h);}else y===null||Cg(y,v)?b=jsx(View,{style:a.centered,testID:"record-document-empty",children:jsx(m,{style:a.emptyText,children:Tt.empty})}):(w=true,b=jsx(Sg,{record:y,depth:v,petName:t,wordmark:d.meta.displayName}));return jsxs(View,{style:[c.root,a.root,s],children:[jsx(et,{title:Tt.title,variant:"document",onBack:n,testID:"record-document-header",right:f.available&&w?jsx(Pressable,{onPress:g,disabled:f.preparing,accessibilityRole:"button",accessibilityLabel:Tt.download,accessibilityState:{disabled:f.preparing,busy:f.preparing},hitSlop:8,style:a.download,testID:"record-document-download",children:f.preparing?jsx(ActivityIndicator,{size:"small",color:d.color.brandInk}):jsx(hl,{})}):void 0}),f.error?jsx(m,{style:[c.errorText,a.inset],accessibilityRole:"alert",children:f.error.displayMessage}):null,jsx(View,{style:c.body,children:b}),jsx(Me,{})]})}i(Eg,"DocumentBody");function Sg({record:e,depth:t,petName:r,wordmark:o}){let n=wd(),l=useMemo(()=>{let a=[],d=new Map;for(let f of e.entities){let h=f.category.trim();if(h.length===0)continue;let R=d.get(h);R===void 0?(a.push(h),d.set(h,[f])):R.push(f);}let u=xd.filter(f=>a.includes(f)),p=a.filter(f=>!xd.includes(f));return [...u,...p].map(f=>({type:f,rows:d.get(f)??[]}))},[e.entities]),s=Date.now(),c=i((a,d,u)=>jsxs(View,{style:n.section,testID:u,children:[jsxs(View,{style:n.sectionHeader,children:[jsx(m,{style:n.sectionTitle,accessibilityRole:"header",children:a}),jsx(View,{style:n.rule})]}),jsx(View,{children:d})]},u),"section");return jsxs(ScrollView,{contentContainerStyle:n.page,showsVerticalScrollIndicator:false,testID:"record-document",children:[jsxs(View,{style:n.letterhead,children:[jsx(m,{style:n.wordmark,children:o}),jsx(m,{style:n.docTitle,children:Tt.docTitle}),jsx(m,{style:n.petName,children:r?.trim()||Tt.namelessPet}),jsx(m,{style:n.generated,children:Tt.generated(e.generatedAt)})]}),e.identity.length>0?c(Tt.identity,e.identity.map((a,d)=>jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsx(m,{style:n.rowLabel,children:a.label}),jsx(m,{style:n.rowValue,children:a.value})]},`${d}:${a.label}`)),"record-document-identity"):null,t&&t.labResults.length>0?c(Tt.labs,t.labResults.map((a,d)=>{let u=Qt(a.latest.status),p=Bc(a.points[a.points.length-1]??null),f=Et(a.latest.value,a.latest.unit??a.unit,a.latest.qualitativeResult);return jsxs(View,{style:[n.row,u.outOfRange?n.rowFlag:null,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:a.name}),jsxs(m,{style:n.rowMeta,children:[p?Tt.ref(p):Tt.noRange,a.latest.at?` \xB7 ${Q(a.latest.at)}`:""]})]}),jsxs(View,{style:n.rowRight,children:[f!=="-"?jsx(m,{style:[n.rowValue,u.outOfRange?n.rowValueAlert:null],children:f}):null,jsx(m,{style:[n.markerStatus,u.outOfRange?n.rowValueAlert:null],children:u.label})]})]},a.markerId)}),"record-document-labs"):null,l.map(({type:a,rows:d})=>c(kn(a),d.map((u,p)=>{let f=[Br(u.value,u.unit),u.observedAt?Q(u.observedAt):null].filter(h=>h&&h.length>0).join(" \xB7 ");return jsx(View,{style:[n.row,p>0?n.rowDivider:null],children:jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:u.label}),f?jsx(m,{style:n.rowMeta,children:f}):null]})},u.key)}),`record-document-${a}`)),e.forwardLooking.length>0?c(Tt.upcomingCare,e.forwardLooking.map((a,d)=>{let u=Tn(a.dueAt,s);return jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:a.title}),a.detail?jsx(m,{style:n.rowMeta,children:a.detail}):null]}),u?jsx(m,{style:[n.rowValue,u.overdue?n.rowValueAlert:null],children:u.label}):null]},`${a.title}-${d}`)}),"record-document-upcoming"):null,t&&t.physicalExams.length>0?c(Tt.physicalExams,t.physicalExams.map((a,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[a.observedOn?jsx(m,{style:n.blockDate,children:Q(a.observedOn)}):null,a.systems.filter(u=>u.finding).map(u=>jsxs(View,{style:n.fieldRow,children:[jsx(m,{style:n.fieldLabel,children:Ir(u.system)}),jsx(m,{style:n.fieldValue,children:u.finding})]},u.system))]},a.examId)),"record-document-exams"):null,t&&t.clinicianNotes.length>0?c(Tt.clinicianNotes,t.clinicianNotes.map((a,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[a.observedOn?jsx(m,{style:n.blockDate,children:Q(a.observedOn)}):null,a.sections.filter(u=>u.text).map((u,p)=>jsxs(View,{style:n.noteSection,children:[jsx(m,{style:n.noteLabel,children:Ur(u.section)}),jsx(m,{style:n.noteBody,children:u.text})]},`${u.section}-${p}`))]},a.noteId)),"record-document-notes"):null,e.disclaimer.length>0?jsx(View,{style:n.disclaimer,children:jsx(m,{style:n.disclaimerText,children:e.disclaimer})}):null]})}i(Sg,"RecordDocument");function wd(){let e=L();return useMemo(()=>kg(e),[e])}i(wd,"useLocalStyles");function kg(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text"),c=i((a,d)=>({..._(e,"mono"),fontSize:a,lineHeight:a+r.xs-1,color:d,letterSpacing:n.letterSpacing.eyebrow/2,textTransform:"uppercase"}),"mono");return StyleSheet.create({root:{backgroundColor:t.surface},inset:{paddingHorizontal:r.lg},download:{width:r.xxl+r.xs+r.xs/2,height:r.xxl+r.xs+r.xs/2,borderRadius:o.pill,alignItems:"center",justifyContent:"center"},centered:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xxl,minHeight:r.xxl*3+r.xl},emptyText:{...s(n.size.body,n.lineHeight.normal,t.text.muted,"medium"),textAlign:"center"},page:{paddingHorizontal:r.lg+r.xs,paddingBottom:r.xxl+r.lg},letterhead:{alignItems:"center",paddingTop:r.md,paddingBottom:r.lg+r.xs+r.xs/2,borderBottomWidth:2,borderBottomColor:t.brand,gap:r.xs+r.xs/2,marginBottom:r.sm},wordmark:{...s(n.size.heading,n.lineHeight.snug,t.brandInk,"bold"),letterSpacing:n.letterSpacing.headerBrand},docTitle:{...c(n.size.caption,t.brandInk),marginTop:r.sm+r.xs/2,letterSpacing:n.letterSpacing.eyebrow+.4},petName:s(n.size.verdict+r.xs/2,n.lineHeight.tight,t.text.primary),generated:{...c(n.size.tiny,t.text.muted),textTransform:"none"},section:{marginTop:r.lg+r.xs+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2,marginBottom:r.sm},sectionTitle:c(n.size.tiny,t.brandInk),rule:{flex:1,height:l,backgroundColor:t.borderHairlineGreen},row:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.md+r.xs/2,paddingVertical:r.sm+1},rowDivider:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen},rowFlag:{backgroundColor:t.badgeBgCritical,marginHorizontal:-r.sm,paddingHorizontal:r.sm,borderRadius:o.xs},rowMain:{flexShrink:1},rowRight:{alignItems:"flex-end",gap:r.xs/2},rowLabel:{flexShrink:1,...s(n.size.body,n.lineHeight.normal,t.text.primary,"medium")},rowValue:{...s(n.size.body,n.lineHeight.normal,t.text.primary,"bold"),textAlign:"right"},rowValueAlert:{color:t.danger},rowMeta:{marginTop:r.xs/2,..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},markerStatus:c(n.size.micro,t.text.muted),block:{paddingVertical:r.sm+r.xs/2},blockDate:{...c(n.size.tiny,t.text.muted),marginBottom:r.xs+r.xs/2},fieldRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md+r.xs/2,paddingVertical:r.xs-1},fieldLabel:{width:120,...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted,"medium")},fieldValue:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")},noteSection:{marginTop:r.sm},noteLabel:{...c(n.size.tiny,t.brandInk),marginBottom:r.xs/2},noteBody:s(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),disclaimer:{marginTop:o.xl,paddingTop:r.md+r.xs/2,borderTopWidth:l,borderTopColor:t.borderHairlineGreen},disclaimerText:s(n.size.tiny,n.lineHeight.relaxed,t.text.muted)})}i(kg,"makeLocalStyles");function Sd({petRef:e,onClose:t,onNavigate:r,onOpenUrl:o,onCopy:n}){let l=Dg(),s=be(),c=xa(e),[a,d]=useState(null),[u,p]=useState(null),f=c.available&&!c.consentRequired,h=i((b,w)=>{kr(o??(E=>Linking.openURL(E)),b,w).then(E=>{E.ok||d(de.toasts.shareSheet);});},"open"),R=i(()=>{d(null),c.createLink().then(b=>{b.ok?h(b.value.shareUrl,"share_link"):d(ro(b.error,"create"));});},"onCreateLink"),v=i(()=>{d(null),c.pdfLink().then(b=>{b.ok?h(b.value.downloadUrl,"record_pdf"):d(ro(b.error,"download"));});},"onDownload"),y=i(b=>{!n||b.shareUrl===null||kr(n,b.shareUrl).then(w=>d(w.ok?de.toasts.copied:de.toasts.copyFailed));},"onCopyRow"),g=i(b=>{c.revoke(b).then(w=>{p(null),d(w.ok?de.toasts.turnedOff:ro(w.error,"revoke"));});},"onConfirmRevoke");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:t,children:jsxs(View,{style:l.backdrop,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:de.closeSheetA11y,onPress:t}),jsxs(View,{style:l.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[jsx(View,{style:l.handle}),jsxs(View,{style:l.header,children:[jsxs(View,{style:l.headerText,children:[jsx(m,{style:l.title,accessibilityRole:"header",children:de.title}),jsx(m,{style:l.helper,children:de.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:de.close,onPress:t,hitSlop:12,style:l.closeButton,testID:"share-record-close",children:jsx(m,{style:l.closeGlyph,children:"\xD7"})})]}),jsxs(ScrollView,{style:l.scroll,contentContainerStyle:l.body,showsVerticalScrollIndicator:false,children:[jsxs(View,{style:l.actions,children:[r?jsx(re,{label:de.viewDocument,onPress:()=>{t(),r({name:"document"});},testID:"share-view-document"}):null,f?jsx(re,{label:c.creating?de.creatingLink:de.createLink,kind:"outline",busy:c.creating,onPress:R,testID:"share-create-link"}):null,f?jsx(re,{label:c.preparingPdf?de.preparingPdf:de.downloadPdf,kind:"outline",busy:c.preparingPdf,onPress:v,testID:"share-download-pdf"}):null]}),c.consentRequired?jsxs(View,{style:l.stateCard,testID:"share-consent-off",children:[jsx(m,{style:l.stateTitle,accessibilityRole:"header",children:de.consentOffTitle}),jsx(m,{style:l.stateBody,children:de.consentOffBody}),jsx(re,{label:de.retry,kind:"outline",onPress:c.refresh,testID:"share-consent-retry"})]}):null,a?jsx(m,{style:l.notice,accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:"share-notice",children:a}):null,hd(c)?jsxs(View,{style:l.section,children:[jsx(m,{style:l.sectionLabel,accessibilityRole:"header",children:de.activeLinks}),c.status==="loading"?jsx(Dl,{testID:"share-record-loading"}):c.status==="error"?jsxs(View,{style:l.stateCard,testID:"share-record-error",children:[jsx(m,{style:l.stateTitle,children:de.errorTitle}),jsx(m,{style:l.stateBody,children:de.errorBody}),jsx(re,{label:de.retry,kind:"outline",onPress:c.refresh,testID:"share-record-retry"})]}):c.rows.length===0?jsxs(View,{style:l.stateCard,testID:"share-record-empty",children:[jsx(m,{style:l.stateTitle,children:de.emptyTitle}),jsx(m,{style:l.stateBody,children:de.emptyBody})]}):jsx(View,{style:l.list,children:c.rows.map(b=>jsxs(View,{style:l.row,testID:`share-row-${b.shareId}`,children:[jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:b.a11yLabel,children:[jsxs(View,{style:l.statusLine,children:[jsx(View,{style:[l.statusDot,{backgroundColor:b.active?l.active.color:l.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:l.status,children:b.statusLabel}),jsx(m,{style:l.expiry,children:b.expiryLabel})]}),b.createdLabel?jsx(m,{style:l.created,children:b.createdLabel}):null]}),b.shareUrl!==null&&!n?jsx(m,{selectable:true,style:l.url,testID:`share-url-${b.shareId}`,children:b.shareUrl}):null,u===b.shareId?jsxs(View,{style:l.confirm,testID:`share-revoke-confirm-${b.shareId}`,children:[jsx(m,{style:l.confirmText,children:de.confirmTurnOff}),jsxs(View,{style:l.rowActions,children:[jsx(re,{label:c.revokingId===b.shareId?de.turningOff:de.turnOff,kind:"danger",busy:c.revokingId===b.shareId,onPress:()=>g(b.shareId),testID:`share-revoke-do-${b.shareId}`}),jsx(re,{label:de.keep,kind:"outline",disabled:c.revokingId===b.shareId,onPress:()=>p(null),testID:`share-revoke-cancel-${b.shareId}`})]})]}):jsxs(View,{style:l.rowActions,children:[n?jsx(re,{label:de.copyLink,kind:"outline",disabled:b.shareUrl===null,accessibilityLabel:de.copyLinkA11y(b.actionContext),onPress:()=>y(b),testID:`share-copy-${b.shareId}`}):null,jsx(re,{label:de.turnOff,kind:"danger",accessibilityLabel:de.turnOffA11y(b.actionContext),onPress:()=>p(b.shareId),testID:`share-ask-revoke-${b.shareId}`})]})]},b.shareId))})]}):null]}),jsx(View,{style:s.inset})]})]})})}i(Sd,"ShareSheet");function Dg(){let e=L();return useMemo(()=>Ag(e),[e])}i(Dg,"useStyles");function Ag(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,s=StyleSheet.hairlineWidth,c=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text");return StyleSheet.create({active:{color:t.success},inactive:{color:t.text.muted},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:"rgba(0,0,0,0.4)"},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),scroll:{flexGrow:0},body:{gap:r.lg,paddingBottom:r.sm},actions:{gap:r.sm},notice:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.secondary),padding:r.md,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft},section:{gap:r.sm},sectionLabel:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},stateCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder},stateTitle:{...c(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},stateBody:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),list:{gap:r.md},row:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder},statusLine:{flexDirection:"row",alignItems:"center",gap:r.sm},statusDot:{width:r.sm,height:r.sm,borderRadius:r.xs},status:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.primary,"bold")},expiry:{...c(n.size.caption,n.lineHeight.normal,t.text.muted)},created:c(n.size.tiny,n.lineHeight.normal,t.text.muted),url:{...c(n.size.caption,n.lineHeight.normal,t.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},confirm:{gap:r.sm},confirmText:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")}})}i(Ag,"makeStyles");var Vg=i((e,t)=>e.getRecordDepth(t),"readDepth"),qg=i(e=>!e.available,"depthEmpty");function _a(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack","onAsk"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Fg,{...o,style:t})})}i(_a,"EverfurRecordDetail");function Fg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,onOpenUrl:c,onCopy:a,style:d}){let u=be(),p=zg(),f=yt(r?{petRef:e,controller:r}:{petRef:e}),h=Ut(e,Vg,qg),R=ia(e),v=wa(e),[y,g]=useState(false),b=useMemo(()=>qr(o,f.consent),[o,f.consent]),w=useMemo(()=>Kr(f,o),[f,o]),x=h.value!==null&&!h.value.withheld&&h.value.available?h.value:null,E=f.record,D=i(()=>{f.refresh(),h.refresh();},"retry"),k=n!==void 0||v.lit===true,S;if(f.status==="loading"||h.status==="loading"&&E!==null&&!E.isEmpty)S=jsx(io,{testID:"everfur-record-loading"});else if(f.status==="error"){let I=xr(f,b);S=I.kind==="error"||I.kind==="pet_not_found"?jsx(Qe,{variant:wt(I.error),message:I.error.displayMessage,onAction:I.error.retryable?D:void 0,testID:"everfur-record-error"}):Yr(f,w,b);}else if(E===null||E.isEmpty){let I=x?.completeness?.documentsInReview??0;S=jsxs(ScrollView,{contentContainerStyle:u.content,testID:"everfur-record-empty",children:[jsx(Qe,{variant:"no_records",message:I>0?W.inReview(I):void 0}),jsx(hr,{disclaimer:E?.disclaimer??""})]});}else S=jsx(ScrollView,{contentContainerStyle:p.content,testID:"everfur-record",children:jsx(So,{record:E,depth:x,petName:t,onNavigate:n,onAsk:s,factEdit:R})});return jsxs(View,{style:[u.root,d],children:[jsx(et,{title:W.title,onBack:l,testID:"everfur-record-header",right:k||n?jsxs(Fragment,{children:[n?jsx(Pressable,{onPress:()=>n({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:W.requestClinicsA11y,hitSlop:8,style:p.share,testID:"everfur-record-request-clinics",children:jsx(bl,{})}):null,k?jsx(Pressable,{onPress:()=>g(true),accessibilityRole:"button",accessibilityLabel:W.shareA11y,hitSlop:8,style:p.share,testID:"everfur-record-share",children:jsx(gl,{})}):null]}):void 0}),jsx(View,{style:u.body,children:S}),y?jsx(Sd,{petRef:e,onClose:()=>g(false),onNavigate:n,...c?{onOpenUrl:c}:{},...a?{onCopy:a}:{}}):null,jsx(Me,{})]})}i(Fg,"RecordBody");function zg(){let e=L();return useMemo(()=>Ng(e),[e])}i(zg,"useLocalStyles");function Ng(e){let{space:t,radius:r}=e;return StyleSheet.create({content:{paddingHorizontal:t.lg,paddingBottom:t.xxl+t.sm,gap:t.lg+t.xs},share:{width:t.xxl+t.sm,height:t.xxl+t.sm,borderRadius:r.pill,alignItems:"center",justifyContent:"center"}})}i(Ng,"makeLocalStyles");function Ia(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Ug,{...o,style:t})})}i(Ia,"EverfurRecordsUpload");function Ug({petRef:e,petName:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:s,style:c}){let a=be(),d=Ad(),{runtime:u}=ke(),p=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),f=Cn(o)&&(r!==void 0||n!==void 0||Fn(u.registry.services.uploadTransport));return jsxs(View,{style:[a.root,c],children:[jsx(et,{title:"",onBack:s,testID:"upload-header"}),jsxs(ScrollView,{contentContainerStyle:d.content,testID:"upload-screen",children:[jsxs(View,{style:d.header,children:[jsx(View,{style:d.iconBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.title,accessibilityRole:"header",children:rt.title(t)}),jsx(m,{style:d.subtitle,children:rt.subtitle(t)})]}),jsx(Da,{records:p,requestId:null,onPickDocument:o,canUpload:f,onDone:l?h=>l({name:"request",requestId:h}):void 0})]}),jsx(Me,{})]})}i(Ug,"UploadBody");function Da({records:e,requestId:t,onPickDocument:r,canUpload:o,onDone:n}){let l=be(),s=Ad(),[c,a]=useState(null),[d,u]=useState(0),p=useRef(t),f=useRef([]),h=e.uploadQueue.filter(x=>x.status!=="skipped"),R=h.filter(x=>x.status==="done").length,v=h.filter(x=>x.status==="failed").length,y=!e.isUploading&&d>0,g=useCallback(async x=>{if(x.length===0)return;a(null);let E=p.current;if(E===null){let k=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!k.ok){a(rt.errors.start);return}E=k.value.id,p.current=E;}u(k=>k+1);let D=await e.uploadDocuments(E,x);f.current=D.flatMap((k,S)=>k.status==="failed"&&x[S]!==void 0?[x[S]]:[]);},[e]),b=useCallback(()=>{!r||!o||kr(r).then(x=>{if(!x.ok){a(rt.errors.startPlain);return}let E=x.value;E!==null&&g(Array.isArray(E)?E:[E]);});},[r,o,g]),w=useCallback(()=>{g(f.current);},[g]);return jsxs(View,{style:s.card,testID:"records-upload-card",children:[jsx(m,{style:s.cardTitle,accessibilityRole:"header",children:rt.cardTitle}),jsx(m,{style:s.cardSubtitle,children:rt.cardSubtitle}),c?jsx(View,{style:l.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:l.errorText,children:c})}):null,jsx(ad,{records:e}),e.isUploading?jsx(View,{style:s.uploadingRow,children:jsx(m,{style:s.progressText,children:rt.uploading(R,h.length)})}):y?jsxs(View,{style:s.settled,children:[R>0?jsx(m,{style:s.success,accessibilityRole:"alert",children:rt.received(R)}):null,v>0?jsx(re,{label:rt.retryFailed(v),kind:"link",accessibilityLabel:rt.retryFailedA11y(v),onPress:w,testID:"records-upload-retry-failed"}):null,jsxs(View,{style:s.settledActions,children:[jsx(re,{label:rt.addMore,kind:"link",accessibilityLabel:rt.addMoreA11y,disabled:!o,onPress:b,testID:"records-upload-another"}),n&&p.current!==null&&R>0?jsx(re,{label:rt.done,accessibilityLabel:rt.doneA11y,onPress:()=>n(p.current),testID:"records-upload-done"}):null]})]}):jsx(re,{label:rt.chooseFiles,accessibilityLabel:rt.chooseFilesA11y,disabled:!o,onPress:b,testID:"records-upload-choose"})]})}i(Da,"UploadRecordCard");function Ad(){let e=L();return useMemo(()=>jg(e),[e])}i(Ad,"useLocalStyles");function jg(e){let{color:t,space:r,radius:o,type:n}=e,l=i((s,c,a,d="regular")=>({..._(e,d),fontSize:s,lineHeight:Math.round(s*c),color:a}),"text");return StyleSheet.create({content:{padding:r.lg+r.xs,gap:r.lg+r.xs},header:{gap:r.sm,alignItems:"center"},iconBubble:{width:r.xxl+r.lg+r.xs,height:r.xxl+r.lg+r.xs,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{...l(n.size.heading+r.xs/2,n.lineHeight.snug,t.brandInk,"bold"),textAlign:"center"},subtitle:{...l(n.size.body,n.lineHeight.normal,t.text.muted),textAlign:"center",maxWidth:340},card:{borderRadius:o.md,backgroundColor:t.surface,borderWidth:1,borderColor:t.brandSoft,padding:r.lg,gap:r.md},cardTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},cardSubtitle:l(n.size.bodyTight,n.lineHeight.normal,t.text.muted),uploadingRow:{flexDirection:"row",alignItems:"center",gap:r.sm},progressText:{flex:1,...l(n.size.bodyTight,n.lineHeight.normal,t.text.secondary)},settled:{gap:r.sm},success:l(n.size.bodyTight,n.lineHeight.normal,t.text.primary),settledActions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:r.sm}})}i(jg,"makeLocalStyles");function Oa(e){let{style:t,renderPending:r,...o}=Fe(e,["onNavigate","onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Xg,{...o,style:t})})}i(Oa,"EverfurRecordsRequest");function Xg({petRef:e,requestId:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:s,style:c,nowMs:a}){let d=be(),{runtime:u,userRef:p,scopeEpoch:f}=ke(),h=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),R=h.requests.find(b=>b.id===t)??null,v=Cn(o)&&(r!==void 0||n!==void 0||Fn(u.registry.services.uploadTransport)),y=R?bo(R):"",g;return h.status==="loading"?g=jsx(_l,{testID:"records-request-loading"}):h.status==="error"&&h.error?g=jsx(Qe,{variant:wt(h.error),message:h.error.displayMessage,onAction:h.error.retryable?h.refresh:void 0,testID:"records-request-error"}):R===null?g=jsx(Qe,{variant:"no_requests",testID:"records-request-missing"}):p===null?g=jsx(Qe,{variant:"error",testID:"records-request-error"}):g=jsx(Jg,{request:R,records:h,canUpload:v,onPickDocument:o,onNavigate:l,nowMs:a},JSON.stringify([p,f,R.id])),jsxs(View,{style:[d.root,c],children:[jsx(et,{title:y,onBack:s,testID:"records-request-header"}),jsx(KeyboardAvoidingView,{behavior:"padding",style:d.body,children:g}),jsx(Me,{})]})}i(Xg,"RequestBody");function Jg({request:e,records:t,canUpload:r,onPickDocument:o,onNavigate:n,nowMs:l}){let s=be(),c=Zg(),a=L(),d=td({request:e,onRecovered:t.refresh,canUpload:r},Nt()),[u,p]=useState(null),[f,h]=useState(false),[R,v]=useState(null),y=useRef(true);useEffect(()=>(y.current=true,()=>{y.current=false;}),[]);let g=d.request,b=l??Date.now(),w=g.status==="published",x=g.status==="published"||g.status==="failed"||g.status==="revoked",E=di(g),D=g.wireStatus==="clinic_responded_no_records",k=zs(g,b),S=ci(g,b),I=x?null:g.waitingExpectation?.trim()||null,Y=ho(g),z=Ns(g),$=d.canConvert,G=x&&!w,Z=d.error!==null&&u!==null&&u!=="start"?u==="revoke"?ge.errors.cancel:ge.errors[u]:null,oe=i((H,C)=>{p(H),C();},"run"),Ee=i(()=>{f||(h(true),v(null),t.createRequest(`records-upload-${Date.now().toString(36)}`).then(H=>{if(y.current){if(h(false),!H.ok){v(ge.errors.start);return}n?.({name:"request",requestId:H.value.id});}}));},"startFresh");return jsxs(ScrollView,{contentContainerStyle:c.content,keyboardShouldPersistTaps:"handled",testID:`records-request-${g.id}`,children:[jsx(_o,{request:g}),g.status==="awaiting_upload"?jsx(Da,{records:t,requestId:g.id,onPickDocument:o,canUpload:r}):null,g.statusLabel.length>0?jsx(View,{style:s.statusCard,accessibilityRole:"summary",children:jsx(m,{style:s.statusText,children:g.statusLabel})}):null,I&&!k?jsx(View,{style:s.infoNote,accessibilityRole:"summary",children:jsx(m,{style:s.infoNoteText,children:I})}):g.wireStatus==="awaiting_response"&&!k?jsx(View,{style:s.infoNote,accessibilityRole:"summary",children:jsx(m,{style:s.infoNoteText,children:ge.awaitingNote})}):null,k?jsx(View,{style:s.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:jsx(m,{style:s.cautionNoteText,children:ge.waitingBanner(S)})}):null,w&&n?jsx(re,{label:ge.viewRecords,onPress:()=>n({name:"dashboard"}),style:c.readyCta,testID:"records-request-view-dashboard"}):null,z?jsxs(View,{style:[c.failureCard,E?c.failureCritical:c.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[jsx(m,{style:[c.failureTitle,E?c.failureTitleCritical:c.failureTitleCaution],children:Fs(g)}),g.canUpdateClinicEmail!==true&&g.canRetrySend!==true?jsx(m,{style:s.rowDetail,children:ge.nextStep}):null,g.canUpdateClinicEmail===true?jsxs(View,{style:c.emailBlock,children:[jsx(m,{style:s.fieldLabel,children:Ot.email}),jsx(qe,{style:s.field,accessibilityLabel:Ot.email,placeholder:Ot.emailPlaceholder,placeholderTextColor:a.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,value:d.email,editable:!d.busy,onChangeText:d.setEmail,testID:"records-failure-clinic-email"}),d.emailInvalid?jsx(m,{style:s.errorText,accessibilityRole:"alert",children:ge.errors.invalidEmail}):null,jsx(re,{label:Ot.updateEmail,accessibilityLabel:Ot.updateEmailA11y,disabled:!d.canUpdateEmail,busy:d.busy&&u==="email",onPress:()=>oe("email",d.updateEmail),testID:"records-failure-update-email"})]}):null,g.canRetrySend===true?jsx(re,{label:Ot.retry,kind:"outline",accessibilityLabel:Ot.retryA11y,disabled:!d.canRetry,busy:d.busy&&u==="retry",onPress:()=>oe("retry",d.retry),testID:"records-failure-retry-send"}):null,g.canRetrySend===true&&d.hasEmailEdit?jsx(m,{style:s.rowDetail,children:Ot.retryHint}):null,Z&&(u==="email"||u==="retry")?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null]}):null,(E||D)&&n?jsx(re,{label:ge.tryAnotherClinic,kind:"outline",accessibilityLabel:ge.tryAnotherClinicA11y,onPress:()=>n({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,Y!==null?jsxs(View,{style:c.callBlock,children:[jsx(sd,{call:Y,prompt:g.statusLabel}),g.canRetrySend===true?jsx(re,{label:d.busy&&u==="retry"?ge.resending:ge.resend,kind:"outline",accessibilityLabel:d.busy&&u==="retry"?ge.resendingA11y:ge.resendA11y,disabled:!d.canRetry,onPress:()=>oe("retry",d.retry),testID:"records-resend-authorization"}):null]}):null,$?jsxs(View,{style:c.block,children:[jsx(re,{label:d.busy&&u==="convert"?ge.converting:ge.convert,busy:d.busy&&u==="convert",onPress:()=>oe("convert",d.convert),testID:"records-convert-upload"}),jsx(m,{style:s.muted,children:ge.convertHint}),Z&&u==="convert"?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null]}):null,G?jsxs(View,{style:c.block,children:[jsx(re,{label:f?ge.freshUploadStarting:ge.freshUpload,kind:E||D?"outline":"primary",busy:f,onPress:Ee,testID:"records-upload-own-fresh"}),R?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:R})}):null]}):null,Z&&u==="revoke"?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null,g.canRevoke===true?d.confirmingRevoke?jsxs(View,{style:c.block,testID:"records-revoke-confirm",children:[jsx(m,{style:c.confirmTitle,accessibilityRole:"header",children:Ot.cancelQuestion}),jsx(m,{style:s.bodyText,children:Ot.cancelConsequence}),jsx(re,{label:d.busy&&u==="revoke"?ge.cancelling:ge.cancel,kind:"danger",accessibilityLabel:d.busy&&u==="revoke"?ge.cancellingA11y:ge.cancelA11y,busy:d.busy&&u==="revoke",onPress:()=>oe("revoke",d.revoke),testID:"records-revoke-do"}),jsx(re,{label:Ot.keepRequest,kind:"outline",disabled:d.busy,onPress:d.keepRequest,testID:"records-revoke-keep"})]}):jsx(re,{label:ge.cancel,kind:"danger",accessibilityLabel:ge.cancelA11y,disabled:d.busy,onPress:d.askRevoke,testID:"records-revoke"}):null]})}i(Jg,"RequestDetail");function Zg(){let e=L();return useMemo(()=>eb(e),[e])}i(Zg,"useLocalStyles");function eb(e){let{color:t,space:r,radius:o,type:n}=e,l=i((s,c,a,d="regular")=>({..._(e,d),fontSize:s,lineHeight:Math.round(s*c),color:a}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg+r.xs/2},readyCta:{minHeight:r.xxl+r.lg+r.xs/2},failureCard:{borderRadius:o.lg-r.xs,borderWidth:1,padding:r.md+r.xs/2,gap:r.md},failureCritical:{borderColor:t.badgeBgCritical,backgroundColor:t.badgeBgCritical},failureCaution:{borderColor:t.badgeBgCaution,backgroundColor:t.badgeBgCaution},failureTitle:{...l(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},failureTitleCritical:{color:t.danger},failureTitleCaution:{color:t.warningStrong},emailBlock:{gap:r.sm},callBlock:{gap:r.sm},block:{gap:r.sm},confirmTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")}})}i(eb,"makeLocalStyles");function Od(e){let{petRef:t,petName:r,controller:o,clinicController:n,onPickDocument:l,uploadTransport:s,consentVersion:c,ownerName:a,onCaptureSignature:d,initialScreen:u,onExit:p,style:f,renderPending:h,onOpenUrl:R,onCopy:v,onAsk:y,location:g}=Fe(e,["onExit"]),[b,w]=useReducer(ti,u,$n),x=Wn(b),E=b.stack.length;useEffect(()=>{let $=i(()=>E<=1?false:(w({type:"pop"}),true),"onBackPress"),G=BackHandler.addEventListener("hardwareBackPress",$);return ()=>{G.remove();}},[E]);let D=useCallback($=>w({type:"navigate",screen:$}),[]),k=useMemo(()=>Gn(b).handled?()=>w({type:"pop"}):p,[b,p]),S={onNavigate:D,...k?{onBack:k}:{},...r!==void 0?{petName:r}:{},...R?{onOpenUrl:R}:{},...v?{onCopy:v}:{},...y?{onAsk:y}:{},...g?{location:g}:{}},I={...o?{controller:o}:{},...c!==void 0?{consentVersion:c}:{}},Y={...l?{onPickDocument:l}:{},...s?{uploadTransport:s}:{}},z=h?{renderPending:h}:{};switch(x.name){case "dashboard":return jsx(ha,{petRef:t,...S,...I,...z,style:f});case "request":return jsx(Oa,{petRef:t,requestId:x.requestId,...S,...I,...Y,...z,style:f});case "timeline":return jsx(yd,{petRef:t,...S,style:f});case "record":return jsx(_a,{petRef:t,...S,...I,...z,style:f});case "document":return jsx(Ea,{petRef:t,...S,...I,...z,style:f});case "contributions":return jsx(fd,{petRef:t,docId:x.docId,...S,style:f});case "clinicPicker":return jsx(_i,{petRef:t,...S,...n?{controller:n}:{},...o?{recordsController:o}:{},style:f});case "clinicBatch":return jsx(ji,{petRef:t,petName:r??"",ownerName:a??"",...k?{onClose:k}:{},onCreated:()=>w({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:f});case "consent":return jsx(Zi,{petRef:t,clinic:x.clinic,...S,...a!==void 0?{ownerName:a}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:f});case "upload":return jsx(Ia,{petRef:t,...S,...o?{controller:o}:{},...Y,...z,style:f});default:return pr(x)}}i(Od,"EverfurRecordsFlow");var ab=Od;function db(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,U.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:ce.sessionRequired}):jsx(ub,{...Fe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(db,"EverfurClinicRequest");function ub(e){let t=Nt(),[r,o]=useState(null),n=useCallback(async()=>r===null?null:{signaturePngBase64:r},[r]),l=Ol(e,e.controller??t,e.onCaptureSignature??n),s=e.onCaptureSignature!==void 0||r!==null,c=L(),a={minHeight:44,padding:c.space.sm,borderWidth:1,borderColor:c.color.borderHairlineGreen,borderRadius:c.radius.sm,color:c.color.text.primary,backgroundColor:c.color.surface},d={color:c.color.text.primary,fontSize:c.type.size.body},u=i((p,f,h=false)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:p,accessibilityState:{disabled:h},disabled:h,onPress:f,style:[a,{justifyContent:"center",opacity:h?.5:1}],children:jsx(m,{style:d,children:p})}),"button");return jsxs(View,{accessibilityLabel:U.title,style:[{backgroundColor:c.color.surface,padding:c.space.lg,gap:c.space.md,borderRadius:c.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[d,{..._(c,"bold"),fontSize:c.type.size.heading}],children:U.title}),jsx(m,{style:d,children:e.petName}),l.created?jsx(m,{accessibilityLiveRegion:"polite",style:d,children:l.created.statusLabel||ce.records}):jsxs(Fragment,{children:[jsx(m,{style:d,children:U.ownerName}),jsx(qe,{accessibilityLabel:U.ownerName,style:a,value:l.ownerName,maxLength:200,editable:!l.busy,autoComplete:"name",onChangeText:l.setOwnerName}),jsx(m,{style:d,children:U.clinic}),jsx(qe,{accessibilityLabel:U.clinic,style:a,value:l.query,placeholder:U.placeholder,placeholderTextColor:c.color.text.placeholder,maxLength:200,editable:!l.busy,onChangeText:l.setQuery}),u(U.search,()=>{l.search();},l.busy||l.searching||l.query.trim().length<2),l.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:ce.loading}),l.recent.length>0&&jsx(m,{accessibilityRole:"header",style:d,testID:"records-clinic-recent-label",children:U.recentlyUsed}),l.recent.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},`recent-${p.id}`)),l.clinics.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},p.id)),l.needsEmail&&jsxs(Fragment,{children:[jsx(m,{style:d,children:U.email}),jsx(qe,{accessibilityLabel:U.email,style:a,value:l.email,placeholder:U.emailPlaceholder,placeholderTextColor:c.color.text.placeholder,maxLength:320,editable:!l.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:l.setEmail})]}),jsx(m,{accessibilityRole:"header",style:d,children:U.scopeHeading}),l.copy?jsx(m,{style:d,children:l.query.trim()&&l.ownerName.trim()?l.scope??q("internalError").displayMessage:ce.consentRequired}):!l.error&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:ce.loading}),!e.onCaptureSignature&&jsx(Lr,{onChange:o,disabled:l.busy}),!s&&jsx(m,{accessibilityRole:"alert",style:d,children:U.missingSignature}),l.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:d,children:l.error.displayMessage}),!l.copy&&l.error&&u(ce.retry,l.retryCopy),u(l.busy?U.sending:U.send,()=>{l.submit();},l.busy||!l.ready||!s)]}),e.onClose&&u(U.cancel,e.onClose,l.busy),jsx(Me,{})]})}i(ub,"ClinicRequestBody");
4
- export{_i as EverfurClinicPicker,db as EverfurClinicRequest,ji as EverfurClinicRequestBatch,_a as EverfurRecordDetail,Ea as EverfurRecordDocument,ab as EverfurRecords,Zi as EverfurRecordsConsent,ha as EverfurRecordsDashboard,Od as EverfurRecordsFlow,Oa as EverfurRecordsRequest,Ia as EverfurRecordsUpload,Nr as RECORDS_CLINIC_BATCH_MAX,es as RECORDS_TERMINAL,In as REQUEST_TIMELINE_TITLES,Lr as SignaturePad,na as applyFactOverlay,da as buildRequestTimeline,Wn as currentRecordsScreen,si as deriveRecordsDashboardState,$n as initialRecordsNav,oa as isFactEditable,zr as isTerminalStatus,Qn as pickPetRecordsRequest,Gn as popRecordsNav,Jo as pushRecordsNav,dr as recordsDenialReasonOf,ti as recordsNavReducer,Di as registerRnSignature,Zo as replaceRecordsNav,ei as resetRecordsNav,ho as selectClinicCall,li as selectDashboardView,En as selectPrimaryLabel,Yy as selectRequestList,bo as selectRequestTitle,xs as transitionRecordsNav,yt as useEverfurRecords,Nt as useEverfurRecordsClinic,mi as useEverfurRecordsClinicBatch,ia as useRecordFactEdit,Ca as useRecordPdfLink,xa as useRecordShares,Qi as useRecordsMarkers};
3
+ `):null,Ve=h.length>0&&h.every(F=>!hn(F)||zm.test(F.email.trim())),ie=h.length>=Br,we=!!(v&&ye&&l.trim()&&e.petName.trim()&&Ve&&o)&&S===null,vt=i(async()=>{if(Z.current)return;let F=++oe.current;D(true);try{let Re=await t.searchClinics({query:c.trim(),limit:100});if(!H.current||F!==oe.current)return;Re.ok?(u(Re.value.clinics),f(null)):f(Re.error);}catch{H.current&&F===oe.current&&f(q("internalError"));}finally{H.current&&F===oe.current&&D(false);}},"search"),Xe=i(F=>{Z.current||ie||S!==null||F.clinic!==null&&h.some(Re=>Re.clinic?.id===F.clinic?.id)||(O(),R(Re=>[...Re,{...F,key:U.current(),idempotencyKey:U.current()}]),u([]),a(""));},"add"),qt=i(async()=>{if(Z.current||S!==null||!we||!v||!ye||!o)return;Z.current=true;let F=Ee.current,Re=i(()=>H.current&&Ee.current===F,"current");b(true),f(null);try{if(w.current===null){T.current=new AbortController;let xt=await o({petRef:e.petRef,petName:e.petName,ownerName:l.trim(),clinicName:M.join(", "),authorizationVersion:v.authorizationVersion,scopeText:ye,signal:T.current.signal});if(!Re()||xt===null)return;if(w.current=xt,xt.signaturePngBase64!==void 0&&n!==void 0){let Hd=await n(xt.signaturePngBase64,T.current.signal);if(!Re())return;w.current={signatureId:Hd.signatureId};}}let Ft=w.current,en=h.map(xt=>({...xt.clinic!==null&&(!hn(xt)||xt.clinic.emailStatus==="none")?{clinicId:xt.clinic.id}:{clinicFreeText:Rn(xt)},...hn(xt)?{clinicEmail:xt.email.trim().toLowerCase()}:{},...Ft.signatureId!==void 0?{signatureId:Ft.signatureId}:{signaturePngBase64:Ft.signaturePngBase64},idempotencyKey:xt.idempotencyKey})),tn=await r.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:v.authorizationVersion,clinics:en});if(!Re())return;if(!tn.ok){f(tn.error);return}k(tn.value),e.onCreated?.(tn.value),zt(tn.value.requestGroupId,F);}catch{Re()&&f(q("internalError"));}finally{Z.current=false,Re()&&b(false);}},"submit"),zt=i(async(F,Re)=>{try{let Ft=await t.getRequestGroup(F);if(!H.current||Ee.current!==Re)return;Ft.ok&&Ft.value.petRef===e.petRef&&G(Ft.value);}catch{}},"loadGroup"),Se=i(async()=>{S===null||Z.current||await zt(S.requestGroupId,Ee.current);},"refreshGroup");return {ownerName:l,query:c,clinics:d,copy:v,scopeText:ye,error:y,busy:E,searching:C,drafts:h,outcome:S,group:I,ready:we,atCap:ie,recent:d.length===0?p.filter(F=>!h.some(Re=>Re.clinic?.id===F.id)):[],setOwnerName(F){Z.current||(O(),s(F));},setQuery(F){Z.current||(oe.current+=1,D(false),u([]),a(F));},search:vt,addClinic(F){Xe({clinic:F,freeText:null,email:""});},addFreeText(){let F=c.trim();F.length!==0&&Xe({clinic:null,freeText:F,email:""});},setDraftEmail(F,Re){Z.current||(O(),R(Ft=>Ft.map(en=>en.key===F?{...en,email:Re}:en)));},removeDraft(F){Z.current||S!==null||(O(),R(Re=>Re.filter(Ft=>Ft.key!==F)));},submit:qt,refreshGroup:Se,retryCopy(){f(null),Y(F=>F+1);}}}i(Ml,"useClinicBatchForm");function Bl(e){try{let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.port&&t.port!=="443")return !1;let r=t.hostname.toLowerCase();return r==="s3.amazonaws.com"||r.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(r)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(r)||r==="s3-accelerate.amazonaws.com"||r.endsWith(".s3-accelerate.amazonaws.com")||r==="s3-accelerate.dualstack.amazonaws.com"||r.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}i(Bl,"trustedSignatureUploadUrl");var Fm="Signature upload failed",Nm=3e4;function Mm(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}i(Mm,"base64ByteLength");async function qi(e,t,r,o){let n=i(()=>new Error(Fm),"fail"),l=Mm(e);if(l<=0||r.aborted)throw n();let s=await t.initiateSignatureUpload(l);if(!s.ok||r.aborted||!Bl(s.value.uploadUrl))throw n();let c=new FormData;for(let[g,h]of Object.entries(s.value.uploadFields))c.append(g,h);c.append("file",{uri:`data:image/png;base64,${e}`,name:"signature.png",type:"image/png"});let a=new AbortController,d=i(()=>a.abort(),"onAbort");r.addEventListener("abort",d,{once:true});let u=setTimeout(d,Nm);try{if(!(await(o??fetch)(s.value.uploadUrl,{method:"POST",body:c,credentials:"omit",signal:a.signal})).ok||r.aborted)throw n()}catch{throw n()}finally{clearTimeout(u),r.removeEventListener("abort",d);}let p=await t.completeSignatureUpload(s.value.uploadId);if(!p.ok||r.aborted)throw n();return {signatureId:p.value}}i(qi,"registerRnSignature");var Wr=Object.freeze({width:360,height:120});function $l(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i($l,"blank");function Wl(e,t,r,o){for(let n=-o;n<=o;n+=1)for(let l=-o;l<=o;l+=1){if(l*l+n*n>o*o+o)continue;let s=t+l,c=r+n;s<0||c<0||s>=e.width||c>=e.height||(e.pixels[c*e.width+s]=1);}}i(Wl,"stamp");var Bm=16384;function Hm(e,t){let[r,o]=e;if(!Number.isFinite(r)||!Number.isFinite(o))return null;let n=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),l=Math.min(2*t.height,Math.max(-t.height,Math.round(o)));return [n,l]}i(Hm,"padPoint");function Um(e,t,r,o,n){let[l,s]=t,[c,a]=r,d=Math.abs(c-l),u=-Math.abs(a-s),p=l<c?1:-1,g=s<a?1:-1,h=d+u,R=0;for(;R<n&&(Wl(e,l,s,o),R+=1,!(l===c&&s===a));){let v=2*h;v>=u&&(h+=u,l+=p),v<=d&&(h+=d,s+=g);}return R}i(Um,"line");function Gl(e,t=1){let r=$l(Wr.width,Wr.height);for(let o of e){let n=[];for(let s of o){let c=Hm(s,r);c!==null&&n.push(c);}if(n.length===0)continue;if(n.length===1){let[s,c]=n[0];Wl(r,s,c,t);continue}let l=Bm;for(let s=1;s<n.length&&l>0;s+=1)l-=Um(r,n[s-1],n[s],t,l);}return r}i(Gl,"rasterizeStrokes");var jm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",$m="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",Wm="0123456789abcdefghijklmnopqrstuv",Hi=5,Ui=7,zi=Hi+1;function Gm(e,t){let r=jm.indexOf(e);return r<0?0:Wm.indexOf($m.charAt(r*Ui+t))}i(Gm,"glyphRow");function Yl(e){let t=$l(Wr.width,Wr.height),r=e.trim();if(r.length===0)return t;let o=[...r],n=4;for(;n>1&&(o.length*zi-1)*n>t.width-8;)n-=1;let l=(o.length*zi-1)*n,s=Math.max(0,Math.floor((t.width-l)/2)),c=Math.floor((t.height-Ui*n)/2);return o.forEach((a,d)=>{let u=s+d*zi*n;for(let p=0;p<Ui;p+=1){let g=Gm(a,p);for(let h=0;h<Hi;h+=1)if((g>>Hi-1-h&1)!==0)for(let R=0;R<n;R+=1)for(let v=0;v<n;v+=1){let x=u+h*n+v,y=c+p*n+R;x<t.width&&y<t.height&&(t.pixels[y*t.width+x]=1);}}}),t}i(Yl,"rasterizeTypedName");var Gi=class Gi{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let o=0;for(let n=0;n<r;n+=1)o=o<<1|t>>n&1;this.writeBits(o,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(Gi,"BitWriter");var ji=Gi;function $i(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i($i,"writeLiteral");var Fi=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Hl=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Ni=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Ul=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function Ym(e,t,r){let o=Fi.length-1;for(;Fi[o]>t;)o-=1;$i(e,257+o),Hl[o]>0&&e.writeBits(t-Fi[o],Hl[o]);let n=Ni.length-1;for(;Ni[n]>r;)n-=1;e.writeCode(n,5),Ul[n]>0&&e.writeBits(r-Ni[n],Ul[n]);}i(Ym,"writeMatch");var Km=32768,Mi=3,Qm=258,jl=15,Xm=64;function Jm(e){let t=new ji;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<jl).fill(-1),o=new Int32Array(e.length).fill(-1),n=i(c=>(e[c]<<10^e[c+1]<<5^e[c+2])&(1<<jl)-1,"hashAt"),l=i(c=>{if(c+Mi>e.length)return;let a=n(c);o[c]=r[a],r[a]=c;},"insert"),s=0;for(;s<e.length;){let c=0,a=0;if(s+Mi<=e.length){let d=r[n(s)],u=0,p=Math.min(Qm,e.length-s);for(;d>=0&&u<Xm&&s-d<=Km;){let g=0;for(;g<p&&e[d+g]===e[s+g];)g+=1;if(g>c&&(c=g,a=s-d,g===p))break;d=o[d],u+=1;}}if(c>=Mi){Ym(t,c,a);for(let d=0;d<c;d+=1)l(s+d);s+=c;}else $i(t,e[s]),l(s),s+=1;}return $i(t,256),t.finish()}i(Jm,"deflate");function Zm(e){let t=1,r=0;for(let o of e)t=(t+o)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i(Zm,"adler32");var lo=null;function ey(e){if(lo===null){lo=new Uint32Array(256);for(let r=0;r<256;r+=1){let o=r;for(let n=0;n<8;n+=1)o=o&1?3988292384^o>>>1:o>>>1;lo[r]=o>>>0;}}let t=4294967295;for(let r of e)t=lo[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(ey,"crc32");function vn(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(vn,"u32");function Bi(e,t){let r=Uint8Array.from([...e].map(n=>n.charCodeAt(0))),o=new Uint8Array(r.length+t.length);return o.set(r,0),o.set(t,r.length),[...vn(t.length),...o,...vn(ey(o))]}i(Bi,"chunk");var co="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function ty(e){let t="";for(let r=0;r<e.length;r+=3){let o=e[r],n=r+1<e.length?e[r+1]:0,l=r+2<e.length?e[r+2]:0,s=o<<16|n<<8|l;t+=co.charAt(s>>18&63)+co.charAt(s>>12&63),t+=r+1<e.length?co.charAt(s>>6&63):"=",t+=r+2<e.length?co.charAt(s&63):"=";}return t}i(ty,"toBase64");function Wi(e){let{width:t,height:r,pixels:o}=e,n=Math.ceil(t/8)+1,l=new Uint8Array(n*r);for(let u=0;u<r;u+=1){let p=u*n;l[p]=0,l.fill(255,p+1,p+n);for(let g=0;g<t;g+=1)if(o[u*t+g]===1){let h=p+1+(g>>3);l[h]=l[h]&~(128>>(g&7));}}let s=Jm(l),c=new Uint8Array(2+s.length+4);c[0]=120,c[1]=1,c.set(s,2),c.set(vn(Zm(l)),2+s.length);let a=Uint8Array.from([...vn(t),...vn(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...Bi("IHDR",a),...Bi("IDAT",c),...Bi("IEND",new Uint8Array(0))]);return ty(d)}i(Wi,"encodeSignaturePng");var iy=8,Xl=2,xn=3;function Vr({onChange:e,disabled:t=false}){let r=ay(),[o,n]=useState("draw"),[l,s]=useState(""),[c,a]=useState([]),[d,u]=useState(0),p=useRef([]),g=useRef(null),h=d>0?Wr.width/d:1,R=useRef(h);R.current=h;let v=useRef(t);v.current=t,useEffect(()=>{if(o==="type"){$n(e,l.trim().length>0?Wi(Yl(l)):null);return}let C=c.reduce((D,S)=>D+S.length,0);$n(e,C>=iy?Wi(Gl(c)):null);},[o,l,c,e]);let x=i(C=>{let{locationX:D,locationY:S}=C.nativeEvent;return [D*R.current,S*R.current]},"point"),y=useMemo(()=>PanResponder.create({onStartShouldSetPanResponder:i(()=>!v.current,"onStartShouldSetPanResponder"),onMoveShouldSetPanResponder:i(()=>!v.current,"onMoveShouldSetPanResponder"),onPanResponderTerminationRequest:i(()=>false,"onPanResponderTerminationRequest"),onPanResponderGrant:i(C=>{p.current=[x(C)];},"onPanResponderGrant"),onPanResponderMove:i(C=>{let D=x(C),S=p.current[p.current.length-1];S!==void 0&&Math.abs(S[0]-D[0])<Xl&&Math.abs(S[1]-D[1])<Xl||(p.current=[...p.current,D],a(k=>[...k.filter(I=>I!==g.current),g.current=p.current]));},"onPanResponderMove"),onPanResponderRelease:i(()=>{let C=p.current;p.current=[],a(D=>[...D.filter(S=>S!==g.current),C]),g.current=null;},"onPanResponderRelease"),onPanResponderTerminate:i(()=>{let C=p.current;p.current=[],a(D=>[...D.filter(S=>S!==g.current),C]),g.current=null;},"onPanResponderTerminate")}),[]),f=useCallback(()=>{v.current||(p.current=[],g.current=null,a([]),s(""));},[]),E=useCallback(()=>{f(),n(C=>C==="draw"?"type":"draw");},[f]),b=i(C=>u(C.nativeEvent.layout.width),"onLayout");return jsxs(View,{style:r.container,testID:"records-signature-pad",children:[jsx(m,{style:r.label,children:o==="draw"?$.draw:$.type}),o==="type"?jsx(qe,{accessibilityLabel:$.type,style:r.input,value:l,maxLength:100,editable:!t,autoComplete:"off",autoCorrect:false,onChangeText:C=>{v.current||s(C);}}):null,jsx(View,{onLayout:b,style:[r.canvas,{height:d>0?d/3:120}],accessible:true,accessibilityLabel:$.sign,accessibilityRole:"image",testID:"records-signature-canvas",...o==="draw"?y.panHandlers:{},children:o==="type"?jsx(m,{style:r.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:l.trim()}):c.map((C,D)=>C.map(([S,k],I)=>jsx(View,{pointerEvents:"none",style:[r.dot,{left:S/h-xn/2,top:k/h-xn/2}]},`${D}-${I}`)))}),jsxs(View,{style:r.actions,children:[jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:$.clear,accessibilityState:{disabled:t},disabled:t,onPress:f,style:r.button,children:jsx(m,{style:r.buttonLabel,children:$.clear})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:o==="draw"?$.toType:$.toDraw,accessibilityState:{disabled:t},disabled:t,onPress:E,style:r.button,children:jsx(m,{style:r.buttonLabel,children:o==="draw"?$.toType:$.toDraw})})]})]})}i(Vr,"SignaturePad");function ay(){let e=V();return useMemo(()=>sy(e),[e])}i(ay,"useStyles");function sy(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({container:{gap:r.sm},label:{..._(e,"regular"),fontSize:n.size.body,color:t.text.primary},input:{minHeight:44,padding:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,..._(e,"regular"),fontSize:n.size.body},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,overflow:"hidden",justifyContent:"center"},dot:{position:"absolute",width:xn,height:xn,borderRadius:xn/2,backgroundColor:"#111111"},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:"#111111",paddingHorizontal:r.md},actions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},button:{minHeight:44,paddingHorizontal:r.md,justifyContent:"center",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,backgroundColor:t.surface},buttonLabel:{..._(e,"regular"),fontSize:n.size.body,color:t.text.primary}})}i(sy,"makeStyles");function Ki(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,$.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:de.sessionRequired}):jsx(dy,{...ze(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(Ki,"EverfurClinicRequestBatch");function dy(e){let t=Mt(),r=hi(),o=e.controller??t,[n,l]=useState(null),s=useCallback(async()=>n===null?null:{signaturePngBase64:n},[n]),c=useCallback((x,y)=>qi(x,o,y),[o]),a=Ml(e,o,e.batchClient??r,e.onCaptureSignature??s,e.onCaptureSignature?void 0:c),d=e.onCaptureSignature!==void 0||n!==null,u=V(),p={minHeight:44,padding:u.space.sm,borderWidth:1,borderColor:u.color.borderHairlineGreen,borderRadius:u.radius.sm,color:u.color.text.primary,backgroundColor:u.color.surface},g={color:u.color.text.primary,fontSize:u.type.size.body},h={color:u.color.text.muted,fontSize:u.type.size.bodyTight},R=i((x,y,f=false,E=x)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:E,accessibilityState:{disabled:f},disabled:f,onPress:y,style:[p,{justifyContent:"center",opacity:f?.5:1}],children:jsx(m,{style:g,children:x})}),"button"),v=a.busy?Oe.sending:a.drafts.length===0?Oe.addToContinue:a.error?Oe.tryAgain:Oe.send(a.drafts.length);return jsxs(View,{accessibilityLabel:a.outcome?Oe.resultTitle:Oe.title,style:[{backgroundColor:u.color.surface,padding:u.space.lg,gap:u.space.md,borderRadius:u.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[g,{..._(u,"bold"),fontSize:u.type.size.heading}],children:a.outcome?Oe.resultTitle:Oe.title}),jsx(m,{style:g,children:e.petName}),a.outcome?jsxs(View,{style:{gap:u.space.sm},testID:"records-batch-result",children:[jsx(m,{accessibilityRole:"summary",accessibilityLiveRegion:"polite",style:g,children:a.outcome.createdCount===0?Oe.allFailed:a.outcome.failedCount>0?Oe.partial(a.outcome.createdCount,a.outcome.results.length,a.outcome.failedCount):Oe.allSent(a.outcome.createdCount)}),jsx(m,{accessibilityRole:"header",style:g,children:Oe.perClinic}),a.outcome.results.map((x,y)=>{let f=x.request?.clinicName??a.drafts[y]?.clinic?.name??x.clinicFreeText??"",E=x.created?Oe.sent:Oe.notSent;return jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:[`${f}. ${E}.`,x.created?x.request?.statusLabel:x.failureReason].filter(Boolean).join(" "),testID:`records-batch-row-${x.created?"created":"failed"}`,children:[jsx(m,{style:g,children:f}),jsx(m,{style:h,children:E}),x.created&&x.request?.statusLabel?jsx(m,{style:h,children:x.request.statusLabel}):null,!x.created&&x.failureReason?jsx(m,{style:h,children:x.failureReason}):null]},x.idempotencyKey)}),a.group?jsx(m,{accessibilityLiveRegion:"polite",style:g,children:Oe.responded(a.group.responded,a.group.total)}):null,a.group?.members.map(x=>x.statusLabel?jsx(m,{style:h,children:[x.clinicName,x.statusLabel].filter(Boolean).join(": ")},x.id):null)]}):jsxs(Fragment,{children:[jsx(m,{style:g,children:$.ownerName}),jsx(qe,{accessibilityLabel:$.ownerName,style:p,value:a.ownerName,maxLength:200,editable:!a.busy,autoComplete:"name",onChangeText:a.setOwnerName}),a.drafts.map(x=>jsxs(View,{style:{gap:u.space.xs},testID:`records-batch-draft-${x.key}`,children:[jsx(m,{style:g,children:Rn(x)}),hn(x)?jsxs(Fragment,{children:[jsx(m,{style:h,children:x.email.trim()?x.email:Oe.emailToAdd}),jsx(qe,{accessibilityLabel:$.email,style:p,value:x.email,placeholder:$.emailPlaceholder,placeholderTextColor:u.color.text.placeholder,maxLength:320,editable:!a.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:y=>a.setDraftEmail(x.key,y)})]}):null,R(Oe.remove(Rn(x)),()=>a.removeDraft(x.key),a.busy)]},x.key)),jsx(m,{style:g,children:a.atCap?Oe.atCap:Oe.addClinic}),!a.atCap&&jsxs(Fragment,{children:[jsx(qe,{accessibilityLabel:$.clinic,style:p,value:a.query,placeholder:$.placeholder,placeholderTextColor:u.color.text.placeholder,maxLength:200,editable:!a.busy,onChangeText:a.setQuery}),R($.search,()=>{a.search();},a.busy||a.searching||a.query.trim().length<2),a.query.trim().length>0&&a.clinics.length===0&&!a.searching&&R(Oe.addClinic,a.addFreeText,a.busy),a.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:g,children:de.loading}),a.recent.length>0&&jsx(m,{accessibilityRole:"header",style:g,children:$.recentlyUsed}),a.recent.map(x=>jsx(View,{children:R([x.name,x.address,x.phone].filter(Boolean).join(", "),()=>a.addClinic(x),a.busy)},`recent-${x.id}`)),a.clinics.map(x=>jsx(View,{children:R([x.name,x.address,x.phone].filter(Boolean).join(", "),()=>a.addClinic(x),a.busy)},x.id))]}),jsx(m,{accessibilityRole:"header",style:g,children:$.scopeHeading}),a.copy?jsx(m,{style:g,children:a.drafts.length>0&&a.ownerName.trim()?a.scopeText??q("internalError").displayMessage:de.consentRequired}):!a.error&&jsx(m,{accessibilityLiveRegion:"polite",style:g,children:de.loading}),!e.onCaptureSignature&&jsx(Vr,{onChange:l,disabled:a.busy}),!d&&jsx(m,{accessibilityRole:"alert",style:g,children:$.missingSignature}),a.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:g,children:a.error.displayMessage}),!a.copy&&a.error&&R(de.retry,a.retryCopy),R(v,()=>{a.submit();},a.busy||!a.ready||!d,Oe.sendA11y(a.drafts.length))]}),e.onClose&&R($.cancel,e.onClose,a.busy),jsx(Me,{})]})}i(dy,"BatchBody");var le=Object.freeze({scopeHeading:"What you\u2019re authorizing",scopeBody:"You\u2019re asking your pet\u2019s clinic to release their medical records to Everfur, on your behalf, so we can organize them for you.",whatWeDo:Object.freeze(["We email the clinic a signed copy of this authorization.","When records arrive, our team reviews them before they appear in your app.","You can revoke this request at any time."]),retentionNote:"We keep the records you receive so you always have them. See our Privacy Policy for how records are stored and used.",authorizeLabel:i((e,t)=>`I authorize ${t} to release ${He(e)}\u2019s records to Everfur.`,"authorizeLabel"),missingSignatureError:"Please add your signature before submitting.",missingDraftError:"Something went wrong with your selection. Please go back and pick the clinic again.",newClinicDirectSendNote:"We\u2019ll email this clinic directly to request your pet\u2019s medical records. Clinics usually reply within a week.",titleFreeText:"Confirm your request",titleDirectory:"Authorize records release",noEmailNote:i((e,t)=>`We don\u2019t have an email on file for ${t}. Add it so we can request ${He(e)}\u2019s records.`,"noEmailNote"),emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",emailRequired:"Enter the clinic email before sending the request.",reuseSignature:"Reuse a previous signature",reuseHint:"\u2026or sign again below",reuseTileA11y:"Use this earlier signature",reuseTileSelectedA11y:"Earlier signature, selected",signType:"Type your name to sign",signDraw:"Sign with your finger",clear:"Clear",clearA11y:"Clear signature",fullName:"Your full name",fullNamePlaceholder:"Jane Doe",toType:"Can\u2019t draw? Type your name instead",toTypeA11y:"Can\u2019t draw? Type your name to sign instead",toDraw:"Draw your signature instead",signatureHint:i(e=>`Your signature is added to the authorization sent to ${e}.`,"signatureHint"),submit:"Authorize & send request",submitting:"Submitting\u2026",submitA11y:"Submit authorization"});var uy="value_text",tc=64,rc=512;function nc(e){return e!==null&&e.httpStatus===409&&!rr(e)}i(nc,"isFactReviewerLocked");var wn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:uy}),oc=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,ic=/^\d{4}-\d{2}-\d{2}$/;function ac(e){if(e==null)return "text";let t=e.trim();return oc.test(t)?"num":ic.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(ac,"inferFactValueKind");function Qi(e,t){let r=t.trim(),o=ac(e);if(o==="num"&&oc.test(r)){let n=Number(r);if(Number.isFinite(n))return Object.freeze({[wn.num]:n})}return o==="date"&&ic.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[wn.date]:r}):Object.freeze(o==="bool"&&(r==="true"||r==="false")?{[wn.bool]:r==="true"}:{[wn.text]:r})}i(Qi,"factCorrectionFor");var Ie=z.string().nullish(),yo=z.number().nullish(),py=z.object({collected_at:Ie,at:Ie,value:yo,unit:Ie,qualitative_result:Ie,ref_low:yo,ref_high:yo,status:Ie,source_clinic:Ie,source_doc_id:Ie,doc_id:Ie,reviewed:z.boolean().nullish()}),my=z.object({collected_at:Ie,at:Ie,value:yo,unit:Ie,qualitative_result:Ie,status:Ie}),yy=z.object({marker_id:z.string().min(1),canonical_name:Ie,name:Ie,loinc_code:Ie,canonical_unit:Ie,unit:Ie,panel_name:Ie,panel:Ie,meaning_text:Ie,meaning:Ie,latest:my.nullish(),trajectory:Ie,points:z.array(py).optional()}),fy=z.object({total_markers:z.number().int().nonnegative(),in_range_count:z.number().int().nonnegative(),out_of_range_count:z.number().int().nonnegative(),unknown_count:z.number().int().nonnegative()}),gy=z.object({markers:z.array(yy).optional(),summary:fy.nullish(),disclaimer:z.string().optional(),featured_marker_id:Ie});function by(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(by,"isObject");function sc(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(sc,"withheldMarkers");function lc(e,t){let r=by(t)?t:{},o=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return sc(o);let n=gy.safeParse(r);if(!n.success)return sc(o);let l=n.data,s=i(a=>Object.freeze({at:a.collected_at??a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,sourceClinic:a.source_clinic??null,docId:a.source_doc_id??a.doc_id??null,reviewed:a.reviewed===true}),"point"),c=(l.markers??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.canonical_name??a.name??a.marker_id,loincCode:a.loinc_code??null,unit:a.canonical_unit??a.unit??null,panel:a.panel_name??a.panel??null,meaning:a.meaning_text??a.meaning??null,latest:a.latest?Object.freeze({at:a.latest.collected_at??a.latest.at??null,value:a.latest.value??null,unit:a.latest.unit??null,qualitativeResult:a.latest.qualitative_result??null,status:a.latest.status??null}):null,trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(s))}));return Object.freeze({petRef:o,withheld:false,markers:Object.freeze(c),summary:l.summary?Object.freeze({totalMarkers:l.summary.total_markers,inRangeCount:l.summary.in_range_count,outOfRangeCount:l.summary.out_of_range_count,unknownCount:l.summary.unknown_count}):null,disclaimer:l.disclaimer??"",featuredMarkerId:l.featured_marker_id??null})}i(lc,"mapRecordMarkers");var hy=z.string().min(1).refine(e=>e.startsWith("https://")),Ry=z.object({source_doc_id:z.string().min(1),file_name:z.string().nullish(),doc_format:z.string().nullish(),byte_size:z.number().int().nonnegative().nullish(),received_at:z.string().nullish(),download_url:hy,expires_in_seconds:z.number().int().nonnegative().nullish()}),vy=z.object({items:z.array(z.unknown()).optional()});function cc(e){let t=vy.safeParse(e);if(!t.success)return null;let r=[];for(let o of t.data.items??[]){let n=Ry.safeParse(o);n.success&&r.push(Object.freeze({sourceDocId:n.data.source_doc_id,fileName:n.data.file_name??null,docFormat:n.data.doc_format??null,byteSize:n.data.byte_size??null,receivedAt:n.data.received_at??null,downloadUrl:n.data.download_url,expiresInSeconds:n.data.expires_in_seconds??0}));}return Object.freeze(r)}i(cc,"mapRequestDocuments");var xy=z.string().min(1).refine(e=>e.startsWith("https://")),Cn=z.string().nullish(),wy=z.object({share_id:z.string().min(1),share_url:z.string().min(1),expires_at:Cn}),Cy=z.object({shares:z.array(z.object({share_id:z.string().min(1),expires_at:Cn,created_at:Cn,view_count:z.number().int().nonnegative().nullish(),last_viewed_at:Cn})).optional()}),Ey=z.object({download_url:xy,expires_at:Cn});function Sy(e,t){let r=e.trim();if(r.length===0)return null;try{let o=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return o===null||o.protocol!=="https:"?null:o.toString()}catch{return null}}i(Sy,"resolveShareUrl");function dc(e,t){let r=wy.safeParse(e);if(!r.success)return null;let o=Sy(r.data.share_url,t);return o===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:o,expiresAt:r.data.expires_at??null})}i(dc,"mapRecordShareLink");function uc(e){let t=Cy.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null}))):null}i(uc,"mapRecordShareList");function pc(e){let t=Ey.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(pc,"mapRecordPdfLink");var ky=z.object({signatures:z.array(z.object({signature_id:z.string().min(1),preview_url:z.string().min(1).refine(e=>e.startsWith("https://")),created_at:z.string().nullish()})).optional()});function mc(e){let t=ky.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(mc,"mapSignatureSuggestions");var N=z.string().nullish(),En=z.number().nullish(),Ty=z.object({at:N,value:En,unit:N,qualitative_result:N,ref_low:En,ref_high:En,status:N,doc_id:N}),_y=z.object({marker_id:z.string(),name:z.string(),loinc_code:N,unit:N,panel:N,meaning:N,latest:z.object({at:N,value:En,unit:N,qualitative_result:N,status:N}).nullish(),trajectory:N,points:z.array(Ty).optional()}),Py=z.object({encounter_id:z.string(),date:N,type:N,clinic_name:N,veterinarian:N,doc_id:N}),Iy=z.object({note_id:z.string(),encounter_id:N,observed_on:N,sections:z.array(z.object({section:z.string(),text:z.string()})).optional()}),Dy=z.object({exam_id:z.string(),encounter_id:N,observed_on:N,doc_id:N,systems:z.record(z.object({finding_status:N,finding:N})).optional()}),Ay=z.object({has_lab_history:z.boolean().optional(),has_vaccination_history:z.boolean().optional(),has_weight_history:z.boolean().optional(),has_vitals_history:z.boolean().optional(),has_physical_exam_history:z.boolean().optional(),has_procedure_history:z.boolean().optional(),has_genetic_history:z.boolean().optional(),has_reproductive_history:z.boolean().optional(),has_parasite_prevention_history:z.boolean().optional(),earliest_record_at:N,latest_record_at:N,documents_ingested:z.number().int().nonnegative().optional(),documents_in_review:z.number().int().nonnegative().optional(),entities_pending_review:z.record(z.number().int().nonnegative()).optional(),held_total:z.number().int().nonnegative().optional()}),Oy=z.object({conflict_id:z.string(),entity_type:z.string(),field:N,severity:N,candidates:z.array(z.object({value:z.string(),source_doc_id:N,doc_id:N,collected_at:N})).optional()}),Ly=z.object({lab_results:z.array(_y).optional(),encounters:z.array(Py).optional(),clinician_notes:z.array(Iy).optional(),physical_exams:z.array(Dy).optional(),completeness:Ay.nullish(),conflicts:z.array(Oy).optional()}),Vy=z.object({visits:z.array(z.object({visit_id:z.string(),visit_date:N,veterinarian:N,summary:N,doc_id:N})),vaccines:z.array(z.object({vaccine_id:z.string(),product:N,lot:N,administered_on:N,expires_on:N,doc_id:N})),weights:z.array(z.object({weight_id:z.string(),observed_on:N,weight_kg:En,doc_id:N})),medications:z.array(z.object({medication_id:z.string(),drug_name:N,dose:N,route:N,frequency:N,sig:N,rx_number:N,started_on:N,stopped_on:N,doc_id:N})),disclaimer:z.string().optional()}),qy=z.object({document:$o,contributions:z.array(jo),contribution_count:z.number().int().nonnegative().optional()});function Ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Ji,"isObject");function Zi(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(Zi,"petOf");function Xi(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(Xi,"emptyDepth");function zy(e,t){let r=Ji(t)?t:{},o=Zi(r,e);if(r.withheld===true)return Xi(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(a=>a in r))return Xi(o,false);let l=Ly.safeParse(r);if(!l.success)return Xi(o,true);let s=l.data,c=i(a=>Object.freeze({at:a.at??null,value:a.value??null,unit:a.unit??null,qualitativeResult:a.qualitative_result??null,refLow:a.ref_low??null,refHigh:a.ref_high??null,status:a.status??null,docId:a.doc_id??null}),"point");return Object.freeze({petRef:o,available:true,withheld:false,labResults:Object.freeze((s.lab_results??[]).map(a=>Object.freeze({markerId:a.marker_id,name:a.name,loincCode:a.loinc_code??null,unit:a.unit??null,panel:a.panel??null,meaning:a.meaning??null,latest:Object.freeze({at:a.latest?.at??null,value:a.latest?.value??null,unit:a.latest?.unit??null,qualitativeResult:a.latest?.qualitative_result??null,status:a.latest?.status??null}),trajectory:a.trajectory??null,points:Object.freeze((a.points??[]).map(c))}))),encounters:Object.freeze((s.encounters??[]).map(a=>Object.freeze({encounterId:a.encounter_id,date:a.date??null,type:a.type??null,clinicName:a.clinic_name??null,veterinarian:a.veterinarian??null,docId:a.doc_id??null}))),clinicianNotes:Object.freeze((s.clinician_notes??[]).map(a=>Object.freeze({noteId:a.note_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,sections:Object.freeze((a.sections??[]).map(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((s.physical_exams??[]).map(a=>Object.freeze({examId:a.exam_id,encounterId:a.encounter_id??null,observedOn:a.observed_on??null,docId:a.doc_id??null,systems:Object.freeze(Object.entries(a.systems??{}).map(([d,u])=>Object.freeze({system:d,findingStatus:u.finding_status??null,finding:u.finding??null})))}))),completeness:s.completeness?Object.freeze({hasLabHistory:s.completeness.has_lab_history===true,hasVaccinationHistory:s.completeness.has_vaccination_history===true,hasWeightHistory:s.completeness.has_weight_history===true,hasVitalsHistory:s.completeness.has_vitals_history===true,hasPhysicalExamHistory:s.completeness.has_physical_exam_history===true,hasProcedureHistory:s.completeness.has_procedure_history===true,hasGeneticHistory:s.completeness.has_genetic_history===true,hasReproductiveHistory:s.completeness.has_reproductive_history===true,hasParasitePreventionHistory:s.completeness.has_parasite_prevention_history===true,earliestRecordAt:s.completeness.earliest_record_at??null,latestRecordAt:s.completeness.latest_record_at??null,documentsIngested:s.completeness.documents_ingested??0,documentsInReview:s.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...s.completeness.entities_pending_review??{}}),heldTotal:s.completeness.held_total??0}):null,conflicts:Object.freeze((s.conflicts??[]).map(a=>Object.freeze({conflictId:a.conflict_id,entityType:a.entity_type,field:a.field??null,severity:a.severity??"needs_review",candidates:Object.freeze((a.candidates??[]).map(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(zy,"mapRecordDepth");function yc(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(yc,"withheldTimeline");function Fy(e,t){let r=Ji(t)?t:{},o=Zi(r,e);if(r.withheld===true)return yc(o);let n=Vy.safeParse(r);if(!n.success)return yc(o);let l=n.data,s=l.visits.map(u=>Object.freeze({visitId:u.visit_id,visitDate:u.visit_date??null,veterinarian:u.veterinarian??null,summary:u.summary??null,docId:u.doc_id??null})),c=l.vaccines.map(u=>Object.freeze({vaccineId:u.vaccine_id,product:u.product??null,lot:u.lot??null,administeredOn:u.administered_on??null,expiresOn:u.expires_on??null,docId:u.doc_id??null})),a=l.weights.map(u=>Object.freeze({weightId:u.weight_id,observedOn:u.observed_on??null,weightKg:u.weight_kg??null,docId:u.doc_id??null})),d=l.medications.map(u=>Object.freeze({medicationId:u.medication_id,drugName:u.drug_name??null,dose:u.dose??null,route:u.route??null,frequency:u.frequency??null,sig:u.sig??null,rxNumber:u.rx_number??null,startedOn:u.started_on??null,stoppedOn:u.stopped_on??null,docId:u.doc_id??null}));return Object.freeze({petRef:o,withheld:false,isEmpty:s.length===0&&c.length===0&&a.length===0&&d.length===0,visits:Object.freeze(s),vaccines:Object.freeze(c),weights:Object.freeze(a),medications:Object.freeze(d),disclaimer:l.disclaimer??""})}i(Fy,"mapRecordsTimeline");function Ny(e,t){let r=Ji(t)?t:{},o=Zi(r,e),n=i(()=>Object.freeze({petRef:o,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return n();let l=qy.safeParse(r);if(!l.success)return n();let s=Object.freeze(l.data.contributions.map(Wo));return Object.freeze({petRef:o,withheld:false,document:Go(l.data.document),contributions:s,contributionCount:l.data.contribution_count??s.length})}i(Ny,"mapDocumentContributions");var My="/widget/v1/records/pets";function fc(e){let t=e.funnel??fr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((a,d)=>typeof a=="string"&&a.length>0&&!gr(a)&&[...a].length<=d,"segment"),o=i(async(a,d,u,p)=>{if(!r(d,mt))return lr();let g=await t.send(a,{method:"GET",path:u});if(!g.ok)return g;let h=p(g.value);return h.petRef===d?_e(h):B(q("internalError",{retryable:false}))},"read"),n=i(a=>`${My}/${encodeURIComponent(a)}`,"pet"),l=i(a=>`${n(a)}/everfur_record`,"record"),s=i(async(a,d,u)=>{let p=await t.send(a,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!p.ok)return p;let g=u(p.value);return g===null?B(q("internalError",{retryable:false})):_e(g)},"parsed"),c=i((a,d)=>!r(a.entityType,tc)||!r(a.canonicalKey,rc)||a.idempotencyKey!==void 0&&!r(a.idempotencyKey,nn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:a.entityType,canonical_key:a.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...a.idempotencyKey!==void 0?{idempotency_key:a.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(a=>o("records.depth.record",a,`${n(a)}/record`,d=>zy(a,d)),"getRecordDepth"),getTimeline:i(a=>o("records.depth.timeline",a,`${n(a)}/timeline`,d=>Fy(a,d)),"getTimeline"),getDocumentContributions(a,d){return r(d,64)?o("records.depth.contributions",a,`${n(a)}/documents/${encodeURIComponent(d)}/contributions`,u=>Ny(a,u)):lr()},getMarkers:i(a=>o("records.depth.markers",a,`${n(a)}/markers`,d=>lc(a,d)),"getMarkers"),createShare(a){return r(a,mt)?s("records.share.create",{method:"POST",path:`${l(a)}/share`},d=>dc(d,e.apiBaseUrl)):lr()},listShares(a){return r(a,mt)?s("records.share.list",{method:"GET",path:`${l(a)}/shares`},uc):lr()},async revokeShare(a,d){if(!r(a,mt)||!r(d,64))return lr();let u=await t.send("records.share.revoke",{method:"DELETE",path:`${l(a)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return u.ok?_e(void 0):u},getPdfLink(a){return r(a,mt)?s("records.pdf.link",{method:"GET",path:`${l(a)}/pdf-link`},pc):lr()},async editFact(a,d){let u=r(a,mt)?c(d,d.correctedFields):null;if(u===null)return lr();let p=await t.send("records.fact.edit",{method:"POST",path:`${l(a)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?_e(void 0):p},async removeFact(a,d){let u=r(a,mt)?c(d):null;if(u===null)return lr();let p=await t.send("records.fact.remove",{method:"POST",path:`${l(a)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?_e(void 0):p},listRequestDocuments(a){return r(a,64)?s("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(a)}/documents`},cc):lr()},listAuthorizationSignatures:i(()=>s("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},mc),"listAuthorizationSignatures")}}i(fc,"createRecordsDepthClient");function lr(){return Promise.resolve(B(q("validationFailed",{retryable:false})))}i(lr,"invalid");function cr(){let{runtime:e,userRef:t,scopeEpoch:r}=ke();return useMemo(()=>{let{services:o}=e.registry;return fc({auth:o.authFor(t),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,t,r])}i(cr,"useEverfurRecordsDepthClient");function $t(e,t,r,o=""){let n=cr(),{userRef:l}=ke(),s=Bn(e),c=useMemo(()=>({}),[n,e,o,s]),[a,d]=useState({scope:c,value:null,error:null,loading:true}),u=useRef(0),p=useCallback(async()=>{let y=u.current+=1;if(d({scope:c,value:null,error:null,loading:true}),l===null){d({scope:c,value:null,error:null,loading:false});return}let f=await t(n,e);y===u.current&&(f.ok?d({scope:c,value:f.value,error:null,loading:false}):d({scope:c,value:null,error:f.error,loading:false}));},[n,e,t,c,l]);useEffect(()=>(p(),()=>{u.current+=1;}),[p]);let g=a.scope===c?a:{value:null,error:null,loading:true},h=useCallback(()=>{p();},[p]),R=g.error===null||g.error.httpStatus!==404,v=R?g.error:null,x=g.loading?"loading":v!==null?"error":g.value===null?"empty":g.value.withheld?"populated":r(g.value)?"empty":"populated";return useMemo(()=>({status:x,value:g.value,error:v,available:R,refresh:h}),[x,g.value,v,R,h])}i($t,"useRecordsDepthRead");function xr(e){return e!==null&&e.httpStatus===404}i(xr,"isDarkRouteError");var $y=i((e,t)=>e.getMarkers(t),"readMarkers"),Wy=i(e=>e.markers.length===0,"markersEmpty");function ta(e){let t=$t(e,$y,Wy);return useMemo(()=>{let r=t.available&&t.value!==null&&!t.value.withheld?t.value:null;return {status:t.status,markers:r,available:t.available,error:t.error,refresh:t.refresh}},[t])}i(ta,"useRecordsMarkers");var Gy=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function hc(e){let{clinic:t,controller:r,depthClient:o,capture:n,onCreated:l}=e,s=t.clinic?.name??t.freeText??"",c=t.clinic===null,[a,d]=useState(false),[u,p]=useState(e.ownerName),[g,h]=useState(t.email),[R,v]=useState(false),[x,y]=useState(null),[f,E]=useState(null),[b,C]=useState(0),[D,S]=useState(null),[k,I]=useState(false),[G,z]=useState(null),[Y,H]=useState([]),[Z,oe]=useState(null),[Ee,U]=useState(false),w=useRef(false),T=useRef(true),O=useRef(nr()),M=useRef(null);useEffect(()=>(T.current=true,()=>{T.current=false,M.current=null;}),[r]),useEffect(()=>{let Se=true;return y(null),M.current=null,r.getAuthorizationCopy().then(F=>{Se&&(F.ok?(y(F.value),E(null)):E(F.error));}).catch(()=>{Se&&E(q("internalError"));}),()=>{Se=false;}},[r,b]),useEffect(()=>{if(o===void 0)return;let Se=true;return o.listAuthorizationSignatures().then(F=>{Se&&(F.ok?H(F.value):xr(F.error)||H([]));}).catch(()=>{}),()=>{Se=false;}},[o]);let X=bn(t.clinic),ye=g.trim().toLowerCase(),Ve=Gy.test(ye),ie=X&&(R||ye.length>0)&&!Ve?le.emailRequired:null,we=x?gn(x,u.trim(),He(e.petName),s):null,vt=e.hostCapture===true||Ee||Z!==null,Xe=!!(a&&x&&we&&u.trim()&&s&&vt&&(!X||Ve)),qt=useCallback(async()=>{if(!(w.current||G!==null||!x||!we)){if(!s){S(le.missingDraftError);return}if(X&&!Ve){v(true),S(le.emailRequired);return}if(!(!a||!u.trim())){w.current=true,I(true),S(null);try{if(M.current===null){let F=Z!==null?{signatureId:Z}:await n();if(!T.current)return;if(F===null){S(le.missingSignatureError);return}let Re=t.clinic&&(!X||t.clinic.emailStatus==="none")?{clinicId:t.clinic.id}:{clinicFreeText:s};M.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:x.authorizationVersion,...Re,...X?{clinicEmail:ye}:{},...F.signatureId!==void 0?{signatureId:F.signatureId}:{signaturePngBase64:F.signaturePngBase64},idempotencyKey:O.current()};}let Se=await r.createClinicRequest(M.current);if(!T.current)return;if(!Se.ok){S(Se.error.displayMessage);return}if(Se.value.petRef!==e.petRef){S(q("internalError").displayMessage);return}z(Se.value),M.current=null,l?.(Se.value);}catch{T.current&&S(q("internalError").displayMessage);}finally{w.current=false,T.current&&I(false);}}}},[a,n,t.clinic,s,r,x,G,e.petRef,X,ye,l,u,Z,we,Ve]),zt=useCallback(()=>{M.current=null,S(null);},[]);return {title:c?le.titleFreeText:le.titleDirectory,clinicName:s,isFreeText:c,authorized:a,ownerName:u,email:g,emailError:ie,needsEmail:X,directoryClinicNoEmail:X&&t.clinic!==null,copy:x,copyError:f,scope:we,error:D,busy:k,created:G,ready:Xe,signatures:Y,reuseSignatureId:Z,hasSignature:vt,setAuthorized(Se){w.current||(zt(),d(Se));},setOwnerName(Se){w.current||(zt(),p(Se));},setEmail(Se){w.current||(zt(),v(false),h(Se));},setSigned(Se){w.current||(zt(),U(Se),Se&&oe(null));},pickReuseSignature(Se){w.current||(zt(),oe(Se));},retryCopy(){E(null),C(Se=>Se+1);},submit:qt}}i(hc,"useRecordsConsentForm");function oa(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",style:e.style,...Be(e.onBack,Ze),children:t===null?jsx(m,{accessibilityRole:"alert",children:de.sessionRequired}):jsx(Jy,{...ze(e,["onCreated","onNavigate","onBack"])},JSON.stringify([t,r,e.petRef,e.clinic.key]))})}i(oa,"EverfurRecordsConsent");function Jy({petRef:e,petName:t,clinic:r,ownerName:o,onCaptureSignature:n,onCreated:l,controller:s,onNavigate:c,onBack:a,style:d}){let u=be(),p=Zy(),g=V(),h=Mt(),R=cr(),[v,x]=useState(null),[y,f]=useState("draw"),E=useCallback(async()=>v===null?null:{signaturePngBase64:v},[v]),b=hc({petRef:e,petName:t,ownerName:o??"",clinic:r,controller:s??h,depthClient:R,capture:n?()=>n({petRef:e,petName:He(t),ownerName:b.ownerName,clinicName:b.clinicName,authorizationVersion:b.copy?.authorizationVersion??"",scopeText:b.scope??"",signal:new AbortController().signal}):E,hostCapture:n!==void 0,onCreated:i(k=>{l?.(k),c?.({name:"dashboard"});},"onCreated")}),C=useRef(b);C.current=b;let D=useCallback(k=>{x(k),C.current.setSigned(k!==null);},[]),S=b.busy;return jsxs(View,{style:[u.root,d],children:[jsx(et,{title:b.title,onBack:a,testID:"records-consent-header"}),jsxs(KeyboardAvoidingView,{behavior:"padding",style:u.body,children:[jsxs(ScrollView,{contentContainerStyle:p.content,keyboardShouldPersistTaps:"handled",testID:"records-consent",children:[jsxs(View,{style:p.scopeCard,accessibilityRole:"summary",children:[jsx(m,{style:p.scopeHeading,accessibilityRole:"header",children:le.scopeHeading}),jsx(m,{style:p.scopeBody,children:le.scopeBody}),jsx(View,{style:p.bullets,children:le.whatWeDo.map(k=>jsxs(View,{style:p.bulletRow,children:[jsx(m,{style:p.check,children:"\u2713"}),jsx(m,{style:p.bulletText,children:k})]},k))}),jsx(View,{style:p.retentionRow,children:jsx(m,{style:p.retentionText,children:le.retentionNote})}),b.copy&&b.scope?jsx(m,{style:p.serverScope,testID:"records-consent-scope",children:b.scope}):b.copyError?jsxs(Fragment,{children:[jsx(m,{style:u.errorText,accessibilityRole:"alert",children:b.copyError.displayMessage}),jsx(re,{label:de.retry,kind:"outline",onPress:b.retryCopy,testID:"records-consent-copy-retry"})]}):jsx(m,{style:u.muted,accessibilityLiveRegion:"polite",children:de.loading})]}),jsxs(Pressable,{onPress:()=>b.setAuthorized(!b.authorized),accessibilityRole:"checkbox",accessibilityState:{checked:b.authorized},accessibilityLabel:le.authorizeLabel(t,b.clinicName),hitSlop:6,style:[p.toggle,b.authorized?p.toggleChecked:null],testID:"records-authorize-toggle",children:[jsx(View,{style:[p.box,b.authorized?p.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:b.authorized?jsx(m,{style:p.boxCheck,children:"\u2713"}):null}),jsx(m,{style:p.toggleLabel,children:le.authorizeLabel(t,b.clinicName)})]}),jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:le.fullName}),jsx(qe,{accessibilityLabel:le.fullName,style:u.field,value:b.ownerName,placeholder:le.fullNamePlaceholder,placeholderTextColor:g.color.text.placeholder,maxLength:200,editable:!S,autoComplete:"name",autoCapitalize:"words",onChangeText:b.setOwnerName,testID:"records-consent-owner-name"})]}),b.needsEmail?jsxs(View,{style:p.block,testID:"records-consent-email-block",children:[b.directoryClinicNoEmail?jsx(View,{style:u.cautionNote,testID:"records-consent-no-email-note",children:jsx(m,{style:u.cautionNoteText,children:le.noEmailNote(t,b.clinicName)})}):null,jsx(m,{style:u.fieldLabel,children:le.emailLabel}),jsx(qe,{accessibilityLabel:le.emailLabel,style:u.field,value:b.email,placeholder:le.emailPlaceholder,placeholderTextColor:g.color.text.placeholder,maxLength:320,editable:!S,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:b.setEmail,testID:"records-consent-clinic-email"}),b.emailError?jsx(m,{style:u.errorText,accessibilityRole:"alert",children:b.emailError}):null,jsx(m,{style:u.muted,testID:"records-consent-review-note",children:le.newClinicDirectSendNote})]}):null,n?null:jsxs(View,{style:p.signatureBlock,children:[b.signatures.length>0?jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:le.reuseSignature}),jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:p.gallery,children:b.signatures.map(k=>{let I=b.reuseSignatureId===k.signatureId;return jsx(Pressable,{onPress:()=>b.pickReuseSignature(I?null:k.signatureId),accessibilityRole:"button",accessibilityLabel:I?le.reuseTileSelectedA11y:le.reuseTileA11y,style:[p.tile,I?p.tileSelected:null],testID:`records-consent-reuse-${k.signatureId}`,children:jsx(Image,{source:{uri:k.previewUrl},style:p.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},k.signatureId)})}),jsx(m,{style:u.muted,children:le.reuseHint})]}):null,jsx(View,{style:p.signatureHeader,children:jsx(m,{style:u.fieldLabel,children:y==="type"?le.signType:le.signDraw})}),jsx(Vr,{onChange:D,disabled:S}),jsx(Pressable,{onPress:()=>f(k=>k==="draw"?"type":"draw"),accessibilityRole:"button",accessibilityLabel:y==="draw"?le.toTypeA11y:le.toDraw,style:p.modeToggle,testID:"records-consent-sign-mode-toggle",children:jsx(m,{style:p.modeToggleText,children:y==="draw"?le.toType:le.toDraw})}),jsx(m,{style:u.muted,children:le.signatureHint(b.clinicName)})]}),b.error?jsx(View,{style:u.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:jsx(m,{style:u.errorText,children:b.error})}):null,b.created?jsx(m,{accessibilityLiveRegion:"polite",style:u.bodyText,children:b.created.statusLabel||de.records}):null]}),jsx(View,{style:p.footer,children:jsx(re,{label:S?le.submitting:le.submit,accessibilityLabel:le.submitA11y,disabled:!b.ready,busy:S,onPress:()=>{b.submit();},style:p.submit,testID:"records-consent-submit"})})]}),jsx(Me,{})]})}i(Jy,"ConsentBody");function Zy(){let e=V();return useMemo(()=>ef(e),[e])}i(Zy,"useLocalStyles");function ef(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=i((c,a,d,u="regular")=>({..._(e,u),fontSize:c,lineHeight:Math.round(c*a),color:d}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xl+r.xs,gap:r.lg+r.xs/2},scopeCard:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md},scopeHeading:{...s(n.size.body+1,n.lineHeight.snug,t.brandInk,"bold")},scopeBody:s(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),bullets:{gap:r.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:r.sm},check:{...s(n.size.body,n.lineHeight.normal,t.brandInk,"bold")},bulletText:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary)},retentionRow:{paddingTop:r.xs,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},retentionText:s(n.size.tiny,n.lineHeight.normal,t.text.muted),serverScope:{...s(n.size.bodyTight,n.lineHeight.relaxed,t.text.secondary),paddingTop:r.xs},toggle:{flexDirection:"row",alignItems:"flex-start",gap:r.md,borderRadius:o.lg-r.xs,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2},toggleChecked:{borderColor:t.brandInk,backgroundColor:t.brandSoft},box:{width:r.xl,height:r.xl,borderRadius:o.xs+1,borderWidth:1.6,borderColor:t.brandInk,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},boxChecked:{backgroundColor:t.brandInk},boxCheck:{...s(n.size.body,n.lineHeight.tight,t.surface,"bold")},toggleLabel:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"bold")},block:{gap:r.sm},signatureBlock:{gap:r.sm},gallery:{gap:r.sm,paddingVertical:r.xs},tile:{width:r.xxl*3+r.lg,height:r.xxl+r.lg+r.sm,borderRadius:o.sm,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,overflow:"hidden"},tileSelected:{borderColor:t.brandInk,borderWidth:2},tileImage:{width:"100%",height:"100%"},signatureHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},modeToggle:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},modeToggleText:{...s(n.size.bodyTight,n.lineHeight.snug,t.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:r.lg,paddingTop:r.md,paddingBottom:r.xxl,borderTopWidth:l,borderTopColor:t.borderHairlineGreen,backgroundColor:t.background},submit:{minHeight:r.xxl+r.lg+r.xs+r.xs/2}})}i(ef,"makeLocalStyles");function go(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(go,"markerStatusTone");function rf(e){switch(e){case "above":return "above the reference range";case "below":return "below the reference range";case "in_range":return "within range";default:return "no reference range on file"}}i(rf,"markerStatusSpoken");function nf(e){return e.refLow!==null&&e.refHigh!==null?`, reference range ${e.refLow} to ${e.refHigh}`:e.refLow!==null?`, reference range at least ${e.refLow}`:e.refHigh!==null?`, reference range up to ${e.refHigh}`:""}i(nf,"rangePhrase");function bo(e,t){let r=t?` ${t}`:"";return e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}${r}`:e.refLow!==null?`\u2265 ${e.refLow}${r}`:e.refHigh!==null?`\u2264 ${e.refHigh}${r}`:"-"}i(bo,"formatReferenceRange");function Cc(e,t){let r=t.reviewed?", reviewed by our team":"",o=t.sourceClinic?`, from ${t.sourceClinic}`:"";return `${Q(t.at)}: ${Et(t.value,e.unit,t.qualitativeResult)}, ${rf(t.status)}${nf(t)}${o}${r}`}i(Cc,"markerPointSpoken");function Ge(e){return e?.trim()||"my pet"}i(Ge,"lead");function Ec(e){let t=e.trim();return /[.!?]$/.test(t)?t:`${t}.`}i(Ec,"clause");function Sc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Ge(e)}'s ${r}`],n=[t.latestValueText?.trim(),t.statusText?.trim(),t.trajectoryText?.trim()].filter(Boolean).join(", ");return o[0]+=n?`: ${n}.`:".",t.meaningText?.trim()&&o.push(Ec(t.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Ge(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:t.markerId,payload:{marker:r,...t.statusText?.trim()?{status:t.statusText.trim()}:{}}}}}i(Sc,"buildMarkerAskPrompt");function kc(e,t,r){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:l,unknownCount:s}=t;if(o===0)return {prompt:`I'm looking at ${Ge(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Ge(e)}?`,entityRef:{type:"marker_summary",id:r,payload:{total:0}}};let c=s>0?`, ${s} without a reference range`:"";return {prompt:`I'm looking at ${Ge(e)}'s lab markers: ${o} total, ${n} in range, ${l} out of range${c}. What should I focus on?`,entityRef:{type:"marker_summary",id:r,payload:{total:o,inRange:n,outOfRange:l,unknown:s}}}}i(kc,"buildMarkerSummaryAskPrompt");function Tc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`${r}: ${t.valueText.trim()}`];t.collectedAt?.trim()&&o.push(`collected ${t.collectedAt.trim()}`),t.sourceClinic?.trim()&&o.push(`from ${t.sourceClinic.trim()}`),t.referenceText?.trim()&&o.push(`reference range ${t.referenceText.trim()}`),t.flagged&&o.push(`flagged ${t.flagged}`);let n={marker:r};return t.flagged&&(n.status=t.flagged),t.reviewed!==void 0&&(n.reviewed=t.reviewed),{prompt:`I'm looking at ${Ge(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:t.entityId,payload:n}}}i(Tc,"buildMarkerReadingAskPrompt");function _c(e,t,r){let o=t.clinicName?.trim(),n=t.heldItemCount??0,l=n>0?`, ${n} fact${n===1?"":"s"} being verified`:"";return {prompt:`I'm looking at ${Ge(e)}'s records request${o?` to ${o}`:""}, status: ${t.statusLabel.trim()}${l}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:r,payload:{status:t.status,held:n,...o?{clinic:o}:{}}}}}i(_c,"buildRecordsRequestAskPrompt");var of=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function ia(e,t,r,o){let n=t.entityTypeLabel.trim()||"record",l=t.title.trim()||n,s=t.detail?.trim();return {prompt:`I'm looking at ${Ge(e)}'s ${n.toLowerCase()}: ${l}${s?`, ${s}`:""}. What does this mean, and what should I keep on top of for ${Ge(e)}?`,entityRef:{type:of[r]??r,id:o,payload:{kind:n,title:l,...s?{detail:s}:{}}}}}i(ia,"buildEntityRowAskPrompt");function Pc(e,t,r){let o=t.filter(s=>s.label.trim()),n={type:"upcoming_care",id:r};if(o.length===0)return {prompt:`I'm looking at ${Ge(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Ge(e)} be on?`,entityRef:n};let l=[...o].sort((s,c)=>(s.tone==="overdue"?0:1)-(c.tone==="overdue"?0:1)).slice(0,4).map(s=>s.relativeText.trim()?`${s.label.trim()} (${s.relativeText.trim().toLowerCase()})`:s.label.trim());return {prompt:`I'm looking at ${Ge(e)}'s upcoming care: ${l.join(", ")}. What should I prioritize for ${Ge(e)}, and how do I stay on top of these?`,entityRef:n}}i(Pc,"buildUpcomingCareAskPrompt");function Ic(e,t,r){let o=[`I'm looking at ${Ge(e)}'s physical exam${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`],n=t.abnormal.filter(l=>l.system.trim());return n.length>0?(o.push(`Abnormal: ${n.slice(0,6).map(l=>`${l.system.trim()}: ${l.finding.trim()}`).join("; ")}.`),o.push(`What do these findings mean, and what should I follow up on for ${Ge(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Ge(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:r}}}i(Ic,"buildPhysicalExamAskPrompt");function Dc(e,t,r){let o=[`I'm looking at ${Ge(e)}'s visit notes${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`];for(let n of t.sections.filter(l=>l.text.trim()).slice(0,3))o.push(`${n.label.trim()||"Note"}: ${Ec(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Ge(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:r}}}i(Dc,"buildVisitNoteAskPrompt");function Ac(e,t,r){let o=t.scopeLabel.trim()||"a detail",n=t.candidates.filter(s=>s.value.trim()),l=n.slice(0,3).map(s=>`"${s.value.trim()}"${s.clinicName?.trim()?` (${s.clinicName.trim()})`:""}`).join(" vs ");return {prompt:`Two of ${Ge(e)}'s documents disagree on ${o}: ${l}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:r,payload:{field:o,severity:t.severity,values:n.map(s=>s.value.trim()).join(" | ")}}}}i(Ac,"buildConflictAskPrompt");function Sn(e){return e!==void 0}i(Sn,"canUploadRecords");function aa(e,t){return e??t?.version??""}i(aa,"resolveConsentVersion");function zr(e,t){return aa(e,t).length>0}i(zr,"canGrantConsent");function wr(e,t){return e.denialReason==="consent_required"?t?{kind:"consent_required"}:{kind:"consent_unavailable"}:e.denialReason==="pet_not_found"?{kind:"pet_not_found",error:q("petNotFound",{retryable:false})}:e.denialReason==="entitlement"?{kind:"error",error:q("accessDenied")}:e.denialReason==="session_required"?{kind:"session_required"}:e.withheld?{kind:"withheld"}:e.error===null?{kind:"withheld"}:{kind:"error",error:e.error}}i(wr,"selectErrorView");function ho(e){let t=e.clinicName?.trim()??"";return t.length>0?t:e.source==="owner_provided"?Oc.ownerUpload:Oc.clinicRequest}i(ho,"selectRequestTitle");var Oc=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function af(e){let t=[...e].sort((r,o)=>r.updatedAt!==o.updatedAt?r.updatedAt>o.updatedAt?-1:1:r.createdAt!==o.createdAt?r.createdAt>o.createdAt?-1:1:0);return Object.freeze(t)}i(af,"selectRequestList");function kn(e){let t=e.actionNeededLabel?.trim()??"";return t.length>0?t:e.statusLabel}i(kn,"selectPrimaryLabel");function Ro(e){if(e.showClinicPhone!==true)return null;let t=e.clinicPhone?.trim()??"";return t.length===0?null:{phone:t,dial:`tel:${t.replace(/[^+\d]/g,"")}`,clinicName:e.clinicName?.trim()||null}}i(Ro,"selectClinicCall");var gt=200,Vc=16;function lf(e,t){let r=e.inRangeCount+e.outOfRangeCount+e.unknownCount;if(!Number.isFinite(r)||r<=0)return [];let o=[{key:"in_range",color:t.inRange,count:e.inRangeCount},{key:"out_of_range",color:t.outOfRange,count:e.outOfRangeCount},{key:"unknown",color:t.unknown,count:e.unknownCount}],n=0,l=[];for(let s of o){if(!(s.count>0))continue;let c=s.count/r*360;if(!Number.isFinite(c))return null;l.push({key:s.key,color:s.color,startDeg:n,sweepDeg:c}),n+=c;}return l}i(lf,"buildRingSegments");function zc({summary:e,onAsk:t,testID:r}){let o=df(),n=V(),{totalMarkers:l,inRangeCount:s,outOfRangeCount:c,unknownCount:a}=e,d=useMemo(()=>lf(e,{inRange:n.color.success,outOfRange:n.color.danger,unknown:n.color.text.muted}),[e,n]),u=d!==null&&d.length>0;return jsxs(View,{style:o.card,accessibilityRole:"summary",testID:r,children:[jsx(m,{style:o.title,children:Bt.title}),jsx(View,{style:o.ringRow,accessible:true,accessibilityRole:"image",accessibilityLabel:Bt.a11y(l,s,c,a),children:jsxs(View,{style:o.ringWrap,children:[jsx(View,{style:o.track}),d===null?null:d.map(p=>jsx(cf,{segment:p,styles:o},p.key)),jsxs(View,{style:o.center,pointerEvents:"none",children:[jsx(m,{style:o.centerCount,children:l}),jsx(m,{style:o.centerLabel,children:l===1?Bt.marker:Bt.markers})]})]})}),u||d===null?jsxs(View,{style:o.badges,children:[jsx(sa,{count:c,label:Bt.outOfRange,color:n.color.danger,styles:o}),jsx(sa,{count:s,label:Bt.inRange,color:n.color.success,styles:o}),a>0?jsx(sa,{count:a,label:Bt.noRange,color:n.color.text.muted,styles:o}):null]}):null,jsx(m,{style:o.subtitle,children:Bt.subtitle}),t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Bt.askA11y,style:o.ask,testID:"marker-summary-ask",children:jsx(m,{style:o.askLabel,children:Bt.ask})}):null]})}i(zc,"MarkerSummaryCard");function cf({segment:e,styles:t}){return (e.sweepDeg<=180?[{start:e.startDeg,sweep:e.sweepDeg}]:[{start:e.startDeg,sweep:180},{start:e.startDeg+180,sweep:e.sweepDeg-180}]).map((o,n)=>jsx(View,{style:[t.piece,{transform:[{rotate:`${o.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${e.key}`,children:jsx(View,{style:t.window,children:jsx(View,{style:[t.halfRing,{borderTopColor:e.color,borderRightColor:e.color,transform:[{rotate:`${o.sweep-135}deg`}]}]})})},n))}i(cf,"Arc");function sa({count:e,label:t,color:r,styles:o}){return jsx(View,{style:[o.badge,{borderColor:r}],children:jsx(m,{style:[o.badgeText,{color:r}],children:`${e} ${t}`})})}i(sa,"Badge");function df(){let e=V();return useMemo(()=>uf(e),[e])}i(df,"useStyles");function uf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=StyleSheet.hairlineWidth,c=ot(l.recordCard);return StyleSheet.create({card:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder,padding:r.lg-1,gap:r.sm+r.xs/2,...Je(l.recordCard,s)},title:{..._(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.letterSpacing.headerBrand,...c},ringRow:{alignItems:"center"},ringWrap:{width:gt,height:gt,alignItems:"center",justifyContent:"center"},track:{position:"absolute",width:gt,height:gt,borderRadius:gt/2,borderWidth:Vc,borderColor:t.surfaceSubtle},piece:{position:"absolute",width:gt,height:gt},window:{position:"absolute",left:gt/2,top:0,width:gt/2,height:gt,overflow:"hidden"},halfRing:{position:"absolute",left:-gt/2,top:0,width:gt,height:gt,borderRadius:gt/2,borderWidth:Vc,borderBottomColor:"transparent",borderLeftColor:"transparent"},center:{position:"absolute",alignItems:"center",justifyContent:"center"},centerCount:{..._(e,"medium"),fontSize:n.size.verdict*2,lineHeight:n.size.verdict*2+r.xs,color:t.text.primary,textAlign:"center",...c},centerLabel:{..._(e,"medium"),fontSize:n.size.heading-1,lineHeight:n.size.heading+r.xs/2,color:t.text.primary,textAlign:"center",...c},badges:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:r.sm},badge:{borderWidth:1,borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs},badgeText:{..._(e,"mono"),fontSize:n.size.nano,lineHeight:n.size.tiny,letterSpacing:n.letterSpacing.headerBrand/2,textTransform:"uppercase"},subtitle:{..._(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.relaxed),color:t.text.primary,...c},ask:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.sm,marginTop:r.xs/2,paddingHorizontal:r.lg,borderRadius:o.pill,borderWidth:s,borderColor:t.borderRingCream,backgroundColor:t.surface},askLabel:{..._(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.primary,letterSpacing:n.letterSpacing.tight}})}i(uf,"makeStyles");function pf(e){return e.value!==null&&Number.isFinite(e.value)}i(pf,"numeric");function Fc(e){let t=e.points.filter(pf);if(t.length===0)return null;let r=e.points[e.points.length-1]??null,o=r?.refLow??null,n=r?.refHigh??null,l=t.map(y=>y.value),s=Math.min(...l,...o!==null?[o]:[],...n!==null?[n]:[]),c=Math.max(...l,...o!==null?[o]:[],...n!==null?[n]:[]);s===c&&(s-=1,c+=1);let a=(c-s)*.18,d=s-a,u=c+a,p=u-d,g=i(y=>(u-y)/p*100,"y"),h=6,R=t.length,v=t.map((y,f)=>({index:f,xPct:R<=1?50:h+f/(R-1)*(100-2*h),yPct:g(y.value),status:y.status,point:y})),x=o!==null||n!==null?{topPct:n!==null?g(n):0,bottomPct:o!==null?g(o):100}:null;return {points:v,band:x,firstDate:t[0]?.at??null,lastDate:t[t.length-1]?.at??null}}i(Fc,"buildMarkerChart");var ff=416,gf=140;function xo(e){return `${e}%`}i(xo,"pct");function bf({marker:e,width:t,onPointPress:r,onAsk:o}){let n=la(),l=be(),s=Xt(e.latest?.status??null),c=go(e.latest?.status??null),a=jr(e.trajectory,e.points.length),d=useMemo(()=>Fc(e),[e]),u=e.latest?Et(e.latest.value,e.unit,e.latest.qualitativeResult):null;return jsx(View,{style:[n.page,t!==void 0?{width:t}:null],testID:`marker-card-${e.markerId}`,children:jsxs(View,{style:n.card,children:[jsxs(View,{style:n.headerRow,children:[jsxs(View,{style:n.nameColumn,children:[jsx(m,{style:n.markerName,numberOfLines:2,children:e.name}),e.unit?jsx(m,{style:n.unit,children:e.unit}):null]}),jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:ir.status(s.label),children:jsx(Ht,{label:s.label,tone:c})})]}),e.latest&&u!==null?jsxs(View,{style:n.latestRow,children:[jsx(m,{style:[n.latestValue,s.outOfRange?n.latestValueDanger:null],accessibilityLabel:ir.latestA11y(u,s.label,Q(e.latest.at)),children:u}),jsx(m,{style:n.latestDate,children:Q(e.latest.at)})]}):null,a?jsx(m,{style:n.trajectory,accessibilityRole:"text",children:a}):null,d!==null?jsxs(View,{style:n.chartWrap,children:[jsxs(View,{style:n.plot,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[d.band?jsx(View,{style:[n.band,{top:xo(d.band.topPct),height:xo(Math.max(0,d.band.bottomPct-d.band.topPct))}]}):null,d.points.map(p=>jsx(Pressable,{onPress:()=>r(e,p.point),hitSlop:12,style:[n.point,p.status==="above"||p.status==="below"?n.pointDanger:null,{left:xo(p.xPct),top:xo(p.yPct)}],testID:`marker-point-${e.markerId}-${p.index}`},p.index))]}),jsx(View,{style:n.a11yTable,accessibilityRole:"summary",accessibilityLabel:ir.readingsA11y(e.name),children:e.points.map((p,g)=>jsx(View,{accessibilityRole:"text",accessibilityLabel:Cc(e,p)},g))}),jsx(m,{style:e.points.length===1?n.singleHint:n.tapHint,children:e.points.length===1?ir.singleHint:ir.tapHint})]}):jsx(View,{style:n.emptyBody,accessibilityRole:"text",children:jsx(m,{style:n.emptyText,children:ir.empty})}),o?jsx(Pressable,{onPress:()=>o(e),accessibilityRole:"button",accessibilityLabel:ir.askA11y(e.name),style:[l.pill,l.pillAsk],testID:`marker-ask-${e.markerId}`,children:jsx(m,{style:l.pillAskLabel,children:ir.ask})}):null]})})}i(bf,"MarkerTrendCard");function Hc({markers:e,onPointPress:t,onAsk:r}){let o=la(),[n,l]=useState(0),[s,c]=useState(0),a=i(p=>l(p.nativeEvent.layout.width),"onLayout"),d=i(p=>{if(n<=0)return;let g=Math.round(p.nativeEvent.contentOffset.x/n);c(Math.max(0,Math.min(g,e.length-1)));},"onMomentumEnd"),u=e[s]??null;return jsxs(View,{style:o.carousel,onLayout:a,testID:"marker-carousel",children:[jsx(ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:d,snapToAlignment:"start",children:e.map(p=>jsx(bf,{marker:p,width:n>0?n:void 0,onPointPress:t,onAsk:r},p.markerId))}),jsxs(View,{style:o.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:Ti.a11y(u?.name??null,s,e.length),children:[jsx(View,{style:o.dots,children:e.map((p,g)=>jsx(View,{style:[o.dot,g===s?o.dotActive:null]},p.markerId))}),jsx(m,{style:o.counter,children:Ti.counter(s,e.length)})]})]})}i(Hc,"MarkerTrendCarousel");function Uc({marker:e,point:t,onClose:r,onAsk:o}){let n=la(),l=be();if(e===null||t===null)return null;let s=i((c,a)=>jsxs(View,{style:n.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${c}: ${a}`,children:[jsx(m,{style:n.detailLabel,children:c}),jsx(m,{style:n.detailValue,children:a})]},c),"row");return jsxs(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:r,children:[jsx(Pressable,{style:n.backdrop,onPress:r,accessibilityRole:"button",accessibilityLabel:Ct.close}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"marker-provenance-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.sheetHeader,children:[jsx(m,{style:n.sheetTitle,accessibilityRole:"header",children:Ct.title}),jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Ct.close,hitSlop:10,style:n.closeButton,testID:"marker-provenance-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsxs(View,{style:n.sheetBody,children:[jsxs(View,{style:n.valueRow,children:[jsx(m,{style:n.sheetName,children:e.name}),jsx(m,{style:n.sheetValue,children:Et(t.value,e.unit,t.qualitativeResult)})]}),t.reviewed?jsx(View,{style:n.reviewed,accessibilityRole:"text",children:jsx(m,{style:n.reviewedText,children:Ct.reviewed})}):null,s(Ct.collected,Q(t.at)),t.sourceClinic?s(Ct.clinic,t.sourceClinic):null,s(Ct.referenceRange,t.refLow!==null||t.refHigh!==null?bo(t,e.unit):Ct.noRange),t.docId?s(Ct.sourceDocument,t.docId):null,t.reviewed?null:jsx(m,{style:n.unverified,accessibilityRole:"text",children:Ct.unverified}),o?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Ct.askA11y,style:[l.pill,l.pillAsk],testID:"marker-provenance-ask",children:jsx(m,{style:l.pillAskLabel,children:Ct.ask})}):null]})]})]})}i(Uc,"MarkerProvenanceSheet");function la(){let e=V();return useMemo(()=>hf(e),[e])}i(la,"useStyles");function hf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,s=StyleSheet.hairlineWidth,c=r.md,a=i((g,h,R,v="regular")=>({..._(e,v),fontSize:g,lineHeight:Math.round(g*h),color:R}),"text"),d=ot(l.recordCard),u=a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold"),p=a(n.size.verdict+r.xs,n.lineHeight.tight,t.text.primary,"bold");return StyleSheet.create({page:{paddingHorizontal:r.sm},card:{borderRadius:o.lg-r.xs/2,borderWidth:s,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg,gap:r.md,...Je(l.recordCard,s)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm+r.xs/2},nameColumn:{flex:1,gap:r.xs/2},markerName:{...u,...d},sheetName:u,unit:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted,...d},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},latestValue:{...p,...d},sheetValue:p,latestValueDanger:{color:t.danger},latestDate:{...a(n.size.caption,n.lineHeight.normal,t.text.muted),...d},trajectory:{...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted),...d},chartWrap:{gap:r.sm},plot:{height:gf,borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:t.badgeBgPositive},point:{position:"absolute",width:c,height:c,borderRadius:c/2,marginLeft:-c/2,marginTop:-c/2,backgroundColor:t.brand,borderWidth:2,borderColor:t.surface},pointDanger:{backgroundColor:t.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...a(n.size.tiny,n.lineHeight.normal,t.text.placeholder),textAlign:"center",...d},singleHint:{...a(n.size.caption,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},emptyBody:{alignItems:"center",justifyContent:"center",gap:r.sm,paddingVertical:r.xxl+r.xs},emptyText:{...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},carousel:{height:ff},footer:{alignItems:"center",gap:r.sm,paddingTop:r.md},dots:{flexDirection:"row",gap:r.xs+r.xs/2},dot:{width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs-1,backgroundColor:t.borderHairlineGreen},dotActive:{width:r.lg+r.xs/2,backgroundColor:t.brand},counter:{..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,letterSpacing:n.letterSpacing.eyebrow/3,color:t.text.muted},backdrop:{flex:1,backgroundColor:ro},sheet:{backgroundColor:t.surfaceCream,borderTopLeftRadius:o.xl-r.xs,borderTopRightRadius:o.xl-r.xs,paddingHorizontal:r.lg+r.xs,paddingTop:r.sm,paddingBottom:r.xxl+r.xs,maxHeight:"80%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},sheetTitle:{flex:1,...a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},closeButton:{width:r.xxl+r.md,height:r.xxl+r.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...a(n.size.verdict,n.lineHeight.tight,t.text.primary)},sheetBody:{gap:r.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},reviewed:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs,backgroundColor:t.badgeBgPositive},reviewedText:{...a(n.size.tiny,n.lineHeight.normal,t.success,"medium")},detailRow:{gap:r.xs/2},detailLabel:{...a(n.size.caption,n.lineHeight.normal,t.text.muted,"medium")},detailValue:a(n.size.body,n.lineHeight.normal,t.text.primary),unverified:a(n.size.caption,n.lineHeight.normal,t.text.muted)})}i(hf,"makeStyles");var K=Object.freeze({title:"Full medical record",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:i(e=>`${e} ${e===1?"document":"documents"} from your vet ${e===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,"inReview"),needsAttention:"Needs your attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:i(e=>`${e} ${e===1?"document":"documents"} on file`,"documentsOnFile"),inReviewChip:i(e=>`${e} in review`,"inReviewChip"),beingVerified:i(e=>`${e} being verified`,"beingVerified"),beingVerifiedA11y:i(e=>`${e} ${e===1?"fact is":"facts are"} being verified`,"beingVerifiedA11y"),pendingReview:"Pending review: ",dateRange:i((e,t)=>`${Q(e)} to ${Q(t)}`,"dateRange"),documents:"Documents",uploadedDocument:fe.uploadedDocument,documentRowA11y:i(e=>`View what ${e} contributed to this record`,"documentRowA11y"),identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:i(e=>`Last done ${e}`,"lastDone"),overdue:"Overdue",due:i(e=>`Due ${e}`,"due"),askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:fe.labResults,visits:fe.visits,physicalExams:fe.physicalExams,visitNotes:fe.visitNotes,document:Object.freeze({title:"Health Record",download:"Download record PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:i(e=>`Generated ${Q(e)}`,"generated"),identity:"Identity",labs:"Blood & Lab Work",ref:i(e=>`Ref ${e}`,"ref"),noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),jc=Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function Fr(e){return Object.prototype.hasOwnProperty.call(jc,e)?jc[e]:ar(e)}i(Fr,"entityTypeLabel");var $c=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function Wc(e){let t=$c.filter(o=>e.includes(o)),r=e.filter(o=>!$c.includes(o));return [...t,...r]}i(Wc,"orderEntityTypes");function wo(e){switch(e){case "identity_risk":return {label:"Identity mismatch",rank:0,tone:"critical"};case "benign":return {label:"Minor difference",rank:2,tone:"neutral"};default:return {label:"Needs review",rank:1,tone:"warning"}}}i(wo,"conflictSeverityMeta");function _n(e,t){if(!e)return null;let r=Date.parse(e);if(Number.isNaN(r))return null;let o=r<t-1440*60*1e3;return {label:o?K.overdue:K.due(Q(e)),overdue:o}}i(_n,"dueBadge");function Gc(e){return e===null?null:e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}`:e.refLow!==null?`\u2265 ${e.refLow}`:e.refHigh!==null?`\u2264 ${e.refHigh}`:null}i(Gc,"formatReferenceBand");var at=Object.freeze({editA11y:i(e=>`Edit ${e}. Correct or remove this record detail.`,"editA11y"),title:i(e=>`Edit ${e}`,"title"),helper:"Corrects your record. Your vet can still review it.",close:"Close",closeEditorA11y:"Close editor",save:"Save changes",saving:"Saving...",remove:"Remove this detail",removeA11y:i(e=>`Remove ${e}`,"removeA11y"),confirmRemove:"Remove this detail from your record? This can't be undone.",removeConfirm:"Remove",removing:"Removing...",keep:"Keep",noChange:"Change a value before saving.",saved:"Saved.",removed:"Removed.",detail:"record detail"});function Yc(e,t){return rr(e)?t==="remove"?"Records access for this pet is off, so this detail cannot be removed.":"Records access for this pet is off, so this detail cannot be changed.":nc(e)?t==="remove"?"A clinician already reviewed this detail, so it can't be removed here.":"A clinician already reviewed this detail, so it can't be changed here.":t==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}i(Yc,"factEditErrorMessage");var Rf=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function ca(e,t){if(Object.keys(t.edits).length===0&&t.removed.length===0)return e;let r=[];for(let o of e){let n=o.canonicalKey??null;if(n!==null&&t.removed.includes(n))continue;let l=n!==null?t.edits[n]:void 0;r.push(l===void 0?o:Object.freeze({...o,value:l}));}return Object.freeze(r)}i(ca,"applyFactOverlay");function Eo(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(Eo,"isFactEditable");function vf(){return `records-fact-${Date.now().toString(36)}`}i(vf,"defaultFactKey");function da(e,t={}){let r=cr(),{userRef:o}=ke(),[n,l]=useState(Rf),[s,c]=useState(false),[a,d]=useState(null),u=useMemo(()=>({}),[r,e,o]),[p,g]=useState(null),h=useCallback(()=>g(u),[u]),R=o!==null&&p!==u,v=useRef(false),x=useRef(t.newIdempotencyKey);x.current=t.newIdempotencyKey;let y=useCallback(()=>(x.current??vf)(),[]),f=useCallback((D,S,k)=>{if(c(false),!D.ok){if(S(),xr(D.error)){h();return}d(Yc(D.error,k));}},[h]),E=useCallback(async(D,S)=>{let k=D.canonicalKey??"",I=S.trim();if(v.current||k.length===0||I.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let G=n;l(Y=>({...Y,edits:{...Y.edits,[k]:I}}));let z=await r.editFact(e,{entityType:D.category,canonicalKey:k,correctedFields:Qi(D.value,I),idempotencyKey:y()});return v.current=false,f(z,()=>l(G),"edit"),z},[r,e,n,f,y]),b=useCallback(async D=>{let S=D.canonicalKey??"";if(v.current||S.length===0)return B(q("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let k=n;l(G=>({...G,removed:[...G.removed,S]}));let I=await r.removeFact(e,{entityType:D.category,canonicalKey:S,idempotencyKey:y()});return v.current=false,f(I,()=>l(k),"remove"),I},[r,e,n,f,y]),C=useCallback(()=>d(null),[]);return useMemo(()=>({overlay:n,busy:s,error:a,available:R,edit:E,remove:b,clearError:C}),[n,s,a,R,E,b,C])}i(da,"useRecordFactEdit");var ua=Object.freeze(["vaccination","parasite_prevention"]),So="Undated",xf=Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),Xc=Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function ko(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(ko,"toMillis");function wf(e){let t=e.status?.toLowerCase()??"";return /overdue|lapsed|expired/.test(t)}i(wf,"isLapsed");function Cf(e){return e.category==="parasite_prevention"?"prevention":ko(e.observedAt)===null?"noDate":wf(e)?"overdue":"given"}i(Cf,"vaccineTone");function Ef(e){let t=ko(e);return t===null?So:String(new Date(t).getUTCFullYear())}i(Ef,"yearOf");function Sf(e){let t=Cf(e),r=[e.value!==null&&e.value.length>0?e.value:null,e.observedAt!==null?Q(e.observedAt):null].filter(o=>o!==null&&o.length>0);return {key:e.key,name:e.label,detail:r.length>0?r.join(" \xB7 "):null,statusLabel:xf[t],tone:t,entity:e}}i(Sf,"buildRow");function Jc(e){let t=new Map;for(let o of e){if(!ua.includes(o.category))continue;let n=Ef(o.observedAt),l=t.get(n),s={row:Sf(o),at:o.observedAt};l===void 0?t.set(n,[s]):l.push(s);}let r=[...t.keys()].sort((o,n)=>o===So?1:n===So?-1:Number(n)-Number(o));return Object.freeze(r.map(o=>{let n=t.get(o)??[],l=o===So?n:[...n].sort((s,c)=>(ko(c.at)??0)-(ko(s.at)??0));return Object.freeze({year:o,items:Object.freeze(l.map(s=>s.row))})}))}i(Jc,"selectVaccineGroups");function pa({entity:e,factEdit:t,children:r}){let o=ed(),[n,l]=useState(false),s=e.label.trim()||at.detail;return jsxs(View,{style:o.row,children:[jsx(View,{style:o.main,children:r}),jsx(Pressable,{onPress:()=>l(true),accessibilityRole:"button",accessibilityLabel:at.editA11y(s),hitSlop:6,style:o.editButton,testID:`fact-edit-open-${e.canonicalKey??e.key}`,children:jsx(View,{style:o.pencil,accessibilityElementsHidden:true,importantForAccessibility:"no"})}),n?jsx(If,{entity:e,title:s,factEdit:t,onClose:()=>l(false)}):null]})}i(pa,"FactEditAffordance");function If({entity:e,title:t,factEdit:r,onClose:o}){let n=ed(),l=be(),s=V(),[c,a]=useState(e.value??""),[d,u]=useState(null),[p,g]=useState(false);useEffect(()=>{r.clearError();},[r]);let h=c.trim().length>0&&c.trim()!==(e.value??"").trim(),R=d??r.error,v=r.busy,x=i(()=>{if(!h){u(at.noChange);return}u(null),r.edit(e,c).then(f=>{f.ok&&o();});},"submitEdit"),y=i(()=>{u(null),r.remove(e).then(f=>{f.ok?o():g(false);});},"submitRemove");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:o,children:jsxs(KeyboardAvoidingView,{behavior:"padding",style:n.backdrop,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:at.closeEditorA11y,onPress:o}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"fact-edit-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.header,children:[jsxs(View,{style:n.headerText,children:[jsx(m,{style:n.title,accessibilityRole:"header",children:at.title(t)}),jsx(m,{style:[n.helper,R?n.helperError:null],accessibilityLiveRegion:"polite",children:R??at.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:at.close,onPress:o,hitSlop:12,style:n.closeButton,testID:"fact-edit-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsx(m,{style:l.fieldLabel,children:e.label}),jsx(qe,{accessibilityLabel:e.label,style:l.field,value:c,onChangeText:f=>{a(f),u(null);},editable:!v,maxLength:512,placeholderTextColor:s.color.text.placeholder,testID:"fact-edit-field"}),p?jsxs(View,{style:n.confirmBlock,testID:"fact-edit-confirm-remove",children:[jsx(m,{style:n.confirmText,children:at.confirmRemove}),jsxs(View,{style:n.confirmRow,children:[jsx(re,{label:v?at.removing:at.removeConfirm,kind:"danger",busy:v,onPress:y,style:n.confirmButton,testID:"fact-edit-remove-confirm"}),jsx(re,{label:at.keep,kind:"outline",disabled:v,onPress:()=>g(false),style:n.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):jsxs(View,{style:n.actions,children:[jsx(re,{label:v?at.saving:at.save,busy:v,disabled:!h,onPress:x,testID:"fact-edit-save"}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:at.removeA11y(t),disabled:v,onPress:()=>{u(null),g(true);},style:[n.removeButton,v?n.removeDisabled:null],testID:"fact-edit-remove",children:jsx(m,{style:n.removeText,children:at.remove})})]})]})]})})}i(If,"FactEditSheet");function ed(){let e=V();return useMemo(()=>Df(e),[e])}i(ed,"useStyles");function Df(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,s=e.brightness==="dark"?t.errorRed:t.danger,c=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text");return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:r.sm},main:{flex:1},editButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},pencil:{width:r.md+r.xs/2,height:r.xs/2,backgroundColor:t.brandInk,borderRadius:o.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:ro},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),helperError:{color:s},closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),actions:{gap:r.sm},removeButton:{minHeight:l,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...c(n.size.bodyTight,n.lineHeight.snug,t.danger,"bold")},confirmBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.badgeBgCritical},confirmText:c(n.size.bodyTight,n.lineHeight.normal,t.text.primary),confirmRow:{flexDirection:"row",gap:r.sm},confirmButton:{flex:1}})}i(Df,"makeStyles");function Io({record:e,depth:t,petName:r,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:s,nowMs:c}){let a=be(),d=Af(),u=c??Date.now(),p=useMemo(()=>s?ca(e.entities,s.overlay):e.entities,[e.entities,s]),g=useMemo(()=>{let y=[],f=new Map;for(let E of p){let b=E.category.trim();if(b.length===0||ua.includes(b))continue;let C=f.get(b);C===void 0?(y.push(b),f.set(b,[E])):C.push(E);}return {order:Wc(y),groups:f}},[p]),h=useMemo(()=>Jc(p),[p]),R=Object.values(e.documents),v=i((y,f,E)=>l?jsx(Pressable,{onPress:()=>{let b=y();l(b.prompt,b.entityRef);},accessibilityRole:"button",accessibilityLabel:f,style:[a.pill,a.pillAsk,d.ask],testID:E,children:jsx(m,{style:a.pillAskLabel,children:f})}):null,"ask"),x=s!==void 0&&s.available;return jsxs(Fragment,{children:[jsxs(View,{style:d.sections,children:[t&&t.conflicts.length>0?jsxs(View,{style:a.section,testID:"record-section-conflicts",children:[jsx(Pt,{title:K.needsAttention,count:t.conflicts.length}),[...t.conflicts].sort((y,f)=>wo(y.severity).rank-wo(f.severity).rank).map(y=>{let f=wo(y.severity),E=ar(y.field??y.entityType);return jsxs(View,{style:[d.conflictCard,{borderColor:a.chipTones[f.tone].fg.color}],accessibilityRole:"summary",children:[jsxs(View,{style:d.conflictHead,children:[jsx(m,{style:d.conflictTitle,children:f.label}),jsx(Ht,{label:E,tone:f.tone})]}),jsx(m,{style:a.rowDetail,children:K.conflictSub}),y.candidates.map((b,C)=>jsxs(View,{style:d.candidate,children:[jsx(m,{style:a.rowTitle,children:b.value}),jsx(m,{style:a.rowMuted,children:[b.docId?e.documents[b.docId]?.title??K.uploadedDocument:K.uploadedDocument,b.collectedAt?Q(b.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},C)),v(()=>Ac(r,{scopeLabel:E,severity:y.severity,candidates:y.candidates.map(b=>({value:b.value,clinicName:b.docId?e.documents[b.docId]?.title??null:null}))},y.conflictId),K.askConflict,`records-ask-conflict-${y.conflictId}`)]},y.conflictId)})]}):null,t?.completeness?jsxs(View,{style:a.section,testID:"record-section-completeness",children:[jsx(Pt,{title:K.whatsOnFile}),jsxs(View,{style:a.card,children:[jsx(View,{style:d.coverageRow,children:[[K.coverage.labs,t.completeness.hasLabHistory],[K.coverage.vaccines,t.completeness.hasVaccinationHistory],[K.coverage.weight,t.completeness.hasWeightHistory],[K.coverage.vitals,t.completeness.hasVitalsHistory],[K.coverage.exams,t.completeness.hasPhysicalExamHistory],[K.coverage.procedures,t.completeness.hasProcedureHistory],[K.coverage.genetics,t.completeness.hasGeneticHistory],[K.coverage.parasite,t.completeness.hasParasitePreventionHistory],[K.coverage.reproductive,t.completeness.hasReproductiveHistory]].map(([y,f])=>jsx(View,{style:[d.coveragePill,f?a.chipTones.positive.bg:a.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${y}: ${f?K.onFile:K.noneOnFile}`,children:jsx(m,{style:[d.coverageText,f?a.chipTones.positive.fg:{color:a.rowMuted.color}],children:y})},y))}),jsxs(View,{style:d.metaRow,children:[jsx(m,{style:d.metaText,children:K.documentsOnFile(t.completeness.documentsIngested)}),t.completeness.documentsInReview>0?jsx(Ht,{label:K.inReviewChip(t.completeness.documentsInReview),tone:"warning"}):null,ma(t.completeness.heldTotal,t.completeness.entitiesPendingReview)>0?jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:K.beingVerifiedA11y(ma(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),children:jsx(Ht,{label:K.beingVerified(ma(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),t.completeness.earliestRecordAt||t.completeness.latestRecordAt?jsx(View,{style:d.metaRow,children:jsx(m,{style:d.metaText,children:K.dateRange(t.completeness.earliestRecordAt,t.completeness.latestRecordAt)})}):null,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).length>0?jsxs(m,{style:d.pendingText,children:[K.pendingReview,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).map(([y,f])=>`${Fr(y)} (${f})`).join(", ")]}):null]})]}):null,R.length>0?jsxs(View,{style:a.section,testID:"record-section-documents",children:[jsx(Pt,{title:K.documents,count:R.length}),jsx(View,{style:a.card,children:R.map((y,f)=>{let E=y.title?.trim()||K.uploadedDocument,b=y.receivedAt?Q(y.receivedAt):null,C=jsxs(Fragment,{children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:E}),b?jsx(m,{style:a.rowDetail,children:b}):null]}),n?jsx(Ir,{}):null]});return n?jsx(Pressable,{onPress:()=>n({name:"contributions",docId:y.docId}),accessibilityRole:"button",accessibilityLabel:K.documentRowA11y(E),style:[a.row,f>0?a.rowDivider:null],testID:`records-document-row-${y.docId}`,children:C},y.docId):jsx(View,{style:[a.row,f>0?a.rowDivider:null],children:C},y.docId)})})]}):null,e.identity.length>0?jsxs(View,{style:a.section,testID:"record-section-identity",children:[jsx(Pt,{title:K.identity}),jsx(View,{style:a.card,children:e.identity.map((y,f)=>jsxs(View,{style:[a.row,f>0?a.rowDivider:null],children:[jsx(m,{style:d.identityLabel,children:y.label}),jsx(m,{style:d.identityValue,children:y.value})]},`${f}:${y.label}`))})]}):null,e.forwardLooking.length>0?jsxs(View,{style:a.section,testID:"record-section-upcoming",children:[jsx(Pt,{title:K.upcomingCare,count:e.forwardLooking.length}),jsx(View,{style:a.card,children:e.forwardLooking.map((y,f)=>{let E=_n(y.dueAt,u);return jsxs(View,{style:[a.row,f>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.title}),y.detail?jsx(m,{style:a.rowDetail,children:y.detail}):null]}),E?jsx(Ht,{label:E.label,tone:E.overdue?"critical":"info"}):null]},`${y.title}-${f}`)})}),v(()=>Pc(r,e.forwardLooking.map(y=>{let f=_n(y.dueAt,u);return {label:y.title,relativeText:f?.label??"",tone:f?.overdue?"overdue":"upcoming"}}),e.petRef),K.askUpcomingCare,"records-ask-upcoming-care")]}):null,h.length>0?jsxs(View,{style:a.section,testID:"record-section-vaccination",children:[jsx(Pt,{title:Fr("vaccination"),count:h.reduce((y,f)=>y+f.items.length,0)}),h.map(y=>jsxs(View,{style:d.vaccineGroup,testID:`records-vaccine-group-${y.year}`,children:[jsx(m,{style:d.vaccineYear,accessibilityRole:"header",children:y.year.toUpperCase()}),jsx(View,{style:a.card,children:y.items.map((f,E)=>{let b=jsxs(View,{style:[a.row,E>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:f.name}),f.detail?jsx(m,{style:a.rowDetail,children:f.detail}):null,v(()=>ia(r,{entityTypeLabel:Fr(f.entity.category),title:f.name,detail:f.detail},f.entity.category,f.key),K.askEverfur,`records-ask-entity-${f.key}`)]}),jsx(Ht,{label:f.statusLabel,tone:Xc[f.tone]})]});return x&&Eo(f.entity)&&s?jsx(pa,{entity:f.entity,factEdit:s,children:b},f.key):jsx(View,{children:b},f.key)})})]},y.year))]}):null,g.order.map(y=>{let f=g.groups.get(y)??[];if(f.length===0)return null;let E=Fr(y);return jsxs(View,{style:a.section,testID:`record-section-${y}`,children:[jsx(Pt,{title:E,count:f.length}),jsx(View,{style:a.card,children:f.map((b,C)=>{let S=[Ur(b.value,b.unit),b.observedAt?Q(b.observedAt):null].filter(I=>I&&I.length>0).join(" \xB7 "),k=jsxs(View,{style:[a.row,C>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:b.label}),S?jsx(m,{style:a.rowDetail,children:S}):null,v(()=>ia(r,{entityTypeLabel:E,title:b.label,detail:S||null},y,b.key),K.askEverfur,`records-ask-entity-${b.key}`)]}),b.status?jsx(Ht,{label:ar(b.status)}):null]});return x&&Eo(b)&&s?jsx(pa,{entity:b,factEdit:s,children:k},b.key):jsx(View,{children:k},b.key)})})]},y)}),t&&t.physicalExams.length>0?jsxs(View,{style:a.section,testID:"record-section-exams",children:[jsx(Pt,{title:K.physicalExams,count:t.physicalExams.length}),t.physicalExams.map(y=>jsxs(View,{style:a.card,children:[jsx(m,{style:[a.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Q(y.observedOn):fe.exam}),y.systems.map((f,E)=>{let b=f.findingStatus==="abnormal",C=b?fe.abnormal:f.findingStatus==="not_examined"?fe.notExamined:fe.normal;return jsxs(View,{style:[a.row,E>0?a.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[Dr(f.system),C,b?f.finding:null].filter(Boolean).join(", "),children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:Dr(f.system)}),b&&f.finding?jsx(m,{style:a.rowDetail,children:f.finding}):null]}),jsx(Ht,{label:C,tone:b?"warning":f.findingStatus==="not_examined"?"neutral":"positive"})]},f.system)}),v(()=>Ic(r,{observedOn:y.observedOn?Q(y.observedOn):null,abnormal:y.systems.filter(f=>f.findingStatus==="abnormal").map(f=>({system:Dr(f.system),finding:f.finding??""}))},y.examId),K.askExam,`records-ask-exam-${y.examId}`)]},y.examId))]}):null,t&&t.clinicianNotes.length>0?jsxs(View,{style:a.section,testID:"record-section-notes",children:[jsx(Pt,{title:K.visitNotes,count:t.clinicianNotes.length}),t.clinicianNotes.map(y=>jsxs(View,{style:a.card,children:[jsx(m,{style:[a.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Q(y.observedOn):fe.visitNote}),y.sections.map((f,E)=>jsxs(View,{style:[d.noteSection,E>0?a.rowDivider:null],children:[jsx(m,{style:d.noteLabel,children:$r(f.section)}),jsx(m,{style:f.text?d.noteBody:d.noteBodyMuted,children:f.text||fe.notRecorded})]},`${f.section}:${E}`)),v(()=>Dc(r,{observedOn:y.observedOn?Q(y.observedOn):null,sections:y.sections.map(f=>({label:$r(f.section),text:f.text}))},y.noteId),K.askVisit,`records-ask-note-${y.noteId}`)]},y.noteId))]}):null,o&&t&&t.labResults.length>0?jsxs(View,{style:a.section,testID:"record-section-labs",children:[jsx(Pt,{title:K.labResults,count:t.labResults.length}),jsx(View,{style:a.card,children:t.labResults.map((y,f)=>{let E=Xt(y.latest.status),b=Pi(y.latest.at,y.trajectory,y.points.length);return jsxs(View,{style:[a.row,f>0?a.rowDivider:null],children:[jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.name}),jsx(m,{style:a.rowValue,children:Et(y.latest.value,y.latest.unit,y.latest.qualitativeResult)}),b?jsx(m,{style:a.rowDetail,children:b}):null]}),jsx(Ht,{label:E.label,tone:go(y.latest.status)})]},y.markerId)})})]}):null,t&&t.encounters.length>0?jsxs(View,{style:a.section,testID:"record-section-visits",children:[jsx(Pt,{title:K.visits,count:t.encounters.length}),jsx(View,{style:a.card,children:t.encounters.map((y,f)=>{let E=[y.date?Q(y.date):null,y.clinicName,y.veterinarian].filter(b=>b&&b!=="-").join(" \xB7 ");return jsx(View,{style:[a.row,f>0?a.rowDivider:null],children:jsxs(View,{style:a.rowMain,children:[jsx(m,{style:a.rowTitle,children:y.type?ar(y.type):fe.visit}),E?jsx(m,{style:a.rowDetail,children:E}):null]})},y.encounterId)})})]}):null]}),jsx(vr,{disclaimer:e.disclaimer})]})}i(Io,"RecordSections");function ma(e,t){return e>0?e:Object.values(t).reduce((r,o)=>r+o,0)}i(ma,"heldCount");function Af(){let e=V();return useMemo(()=>Of(e),[e])}i(Af,"useLocalStyles");function Of(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth;return StyleSheet.create({sections:{gap:r.lg+r.xs},vaccineGroup:{gap:r.xs+1,marginBottom:r.sm},vaccineYear:{..._(e,"monoMedium"),fontSize:n.size.micro,lineHeight:n.size.micro+r.xs,color:t.text.muted,letterSpacing:n.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:r.xs+2},ask:{marginTop:r.lg},conflictCard:{borderRadius:o.md,borderWidth:1,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},conflictHead:{flexDirection:"row",alignItems:"center",gap:r.sm},conflictTitle:{flex:1,..._(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},candidate:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen,paddingTop:r.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,paddingVertical:r.md},coveragePill:{borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs+1},coverageText:{..._(e,"medium"),fontSize:n.size.caption,lineHeight:n.size.caption+r.xs-1},metaRow:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingBottom:r.md},metaText:{flex:1,..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},pendingText:{..._(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.normal),color:t.text.muted,paddingBottom:r.md},identityLabel:{..._(e,"medium"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},identityValue:{flexShrink:1,textAlign:"right",..._(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},cardTitle:{paddingTop:r.sm},noteSection:{paddingVertical:r.md,gap:r.xs},noteLabel:{..._(e,"bold"),fontSize:n.size.bodyTight,color:t.text.secondary,textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},noteBody:{..._(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.primary},noteBodyMuted:{..._(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.muted,fontStyle:"italic"}})}i(Of,"makeLocalStyles");var Pn=Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:i(e=>`Call the clinic at ${e}`,"callAt")});var Lf=Math.round(mr/(1024*1024)),rt=Object.freeze({title:i(e=>`Upload ${He(e)}\u2019s records`,"title"),subtitle:i(e=>`Already have lab results, a vet summary, or test reports? Add them here and we\u2019ll read them and pull out ${He(e)}\u2019s health markers.`,"subtitle"),noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${Lf} MB each. You can pick several at once. We\u2019ll read them and add the results to your records.`,chooseFiles:"Choose files",chooseFilesA11y:"Choose records to upload",uploading:i((e,t)=>`Uploading ${e+1} of ${t}\u2026`,"uploading"),cancel:"Cancel",cancelA11y:"Cancel these uploads",received:i(e=>`${e===1?"Record received.":`${e} records received.`} We\u2019ll read and review ${e===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,"received"),retryFailed:i(e=>`Retry ${e} that didn\u2019t upload`,"retryFailed"),retryFailedA11y:i(e=>`Retry ${e} failed upload${e>1?"s":""}`,"retryFailedA11y"),addMore:"Add more files",addMoreA11y:"Add more records",done:"Done",doneA11y:"Done, view records",errors:Object.freeze({start:"We couldn\u2019t start that upload. Check your connection and try again.",startPlain:"We couldn\u2019t start that upload. Please try again.",upload:"We couldn\u2019t upload that record. Check your connection and try again."})});var od=Math.round(mr/(1024*1024)),Nr=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,t)=>`Uploading ${e+1} of ${t} records`,"uploading"),uploaded:i((e,t)=>`${e} of ${t} records uploaded`,"uploaded")});function id(e){let t=Math.round(e.progress*100);switch(e.status){case "done":return Nr.done;case "failed":return Nr.failed;case "uploading":return e.progress>=1?Nr.verifying:`${t}%`;case "queued":return Nr.queued;default:return null}}i(id,"uploadItemStatusLabel");function ad(e){if(e.length===0)return null;let t=i(l=>{let s=l.map(c=>c.name??"");return s.length<=3?s.join(", "):`${s.slice(0,3).join(", ")} and ${s.length-3} more`},"nameList"),r=e.filter(l=>l.reason==="too_large"),o=e.filter(l=>l.reason==="unsupported"),n=[];return o.length>0&&n.push(`${t(o)} ${o.length>1?"are not PDFs":"is not a PDF"}`),r.length>0&&n.push(`${t(r)} ${r.length>1?"are":"is"} over ${od} MB`),`Didn\u2019t upload: ${n.join("; ")}. We can only read PDFs up to ${od} MB right now.`}i(ad,"skippedFilesMessage");function sd(e){let t=[];for(let r of e)r.status==="skipped"&&r.skipReason!==null&&t.push({name:r.name,reason:r.skipReason});return t}i(sd,"skippedOf");var Lt=Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",updateEmailA11y:"Update clinic email and resend request",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep request",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We\u2019ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function ld({request:e,onRecovered:t,canUpload:r=false},o){let[n,l]=useState(""),[s,c]=useState(false),[a,d]=useState(null),[u,p]=useState(false),[g,h]=useState(null),R=useRef(false),v=useRef(false),x=useRef(0);useEffect(()=>(v.current=true,()=>{v.current=false,x.current+=1;}),[o]);let y=g!==null&&g.before===e.updatedAt?{...g.value,canRetrySend:e.canRetrySend===true&&g.value.canRetrySend===true,canUpdateClinicEmail:e.canUpdateClinicEmail===true&&g.value.canUpdateClinicEmail===true,canRevoke:e.canRevoke===true&&g.value.canRevoke===true,canConvertToUpload:e.canConvertToUpload===true&&g.value.canConvertToUpload===true}:e,f=n.trim(),E=f.length<=320&&!Array.from(f).some(I=>I.charCodeAt(0)<=32||I.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f),b=y.canUpdateClinicEmail===true&&f.length>0,C=y.canRetrySend===true&&!s&&!b,D=y.canUpdateClinicEmail===true&&!s&&E,S=y.canConvertToUpload===true&&r,k=i(async I=>{let G={retry:C,email:D,revoke:y.canRevoke===true&&u,convert:S};if(R.current||!v.current||!G[I])return;R.current=true,c(true),d(null);let z=x.current,Y=i(()=>v.current&&z===x.current,"live");try{let H=I==="retry"?await o.retryRequest(e.id):I==="email"?await o.updateClinicEmail(e.id,f):I==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!Y())return;if(!H.ok){d(H.error);return}if(H.value.id!==e.id||H.value.petRef!==e.petRef){d(q("internalError"));return}h({before:e.updatedAt,value:H.value}),l(""),p(!1),t();}catch{Y()&&d(q("internalError"));}finally{R.current=false,Y()&&c(false);}},"run");return {request:y,email:n,busy:s,error:a,canRetry:C,canUpdateEmail:D,canConvert:S,hasEmailEdit:b,confirmingRevoke:u&&y.canRevoke===true,emailInvalid:f.length>0&&!E,setEmail(I){R.current||(l(I),d(null));},retry:i(()=>k("retry"),"retry"),updateEmail:i(()=>k("email"),"updateEmail"),revoke:i(()=>k("revoke"),"revoke"),convert:i(()=>k("convert"),"convert"),askRevoke(){!R.current&&y.canRevoke===true&&p(true);},keepRequest(){R.current||p(false);}}}i(ld,"useRecordsRecovery");var qf=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],zf=["requested","awaiting_upload","records_received","processing","ready"],Ff=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],Dn=Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),kt=Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn\u2019t read this one automatically",manualReview:"Checking these by hand so nothing\u2019s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),Nf=Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),Mf=Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function Bf(e){return e.wireStatus??Mf[e.status]??"sent"}i(Bf,"wireStatusOf");function Hf(e,t){return e!=="awaiting_response"||t<=0?null:`${t} ${t===1?"reminder":"reminders"} sent`}i(Hf,"reminderProgressLabel");function Uf(e){switch(e){case "submitted":case "sent":return 1;case "awaiting_response":return 2;case "records_received":return 3;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 4;case "published":return 5;default:return -1}}i(Uf,"reachedRailIndex");function jf(e){switch(e.dispatchStatus){case "sent":return kt.delivered;case "preparing":case "queued":case "sending":return kt.emailing;case "failed":return kt.bounced;default:return null}}i(jf,"deliveryDetail");function $f(e,t){return Hf(t,e.reminderCount??0)??kt.waiting}i($f,"awaitingDetail");function Wf(e){return e.source==="owner_provided"||!!e.convertedToUploadAt}i(Wf,"isOwnerSourcedRequest");function Gf(e,t,r){let o=Wf(t);switch(e){case "sent_to_clinic":return jf(t);case "awaiting_clinic":return $f(t,r);case "awaiting_upload":return kt.upload;case "records_received":return o?kt.ownerAdded:kt.clinicSent;case "processing":return kt.preparing;case "ready":return kt.ready;default:return null}}i(Gf,"railDetail");function Yf(e,t){return !!e.reviewStartedAt||t==="parsing_failed"||t==="review_email_failed"}i(Yf,"tookReviewBranch");function Kf(e,t,r){if(e.key!=="processing"||!Yf(t,r))return [e];let o=r==="parsing_failed",n=r==="published",l=n?"done":o?"current":"done",s=n?"done":o?"upcoming":"current";return [{key:"parsing_failed",title:Dn.parsing_failed,detail:kt.parsingFailed,at:null,state:l},{key:"manual_review",title:Dn.manual_review,detail:kt.manualReview,at:t.reviewStartedAt??null,state:s}]}i(Kf,"expandProcessingPhase");function Qf(e){switch(e){case "awaiting_upload":return 3;case "records_received":return 4;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 5;case "published":return 6;default:return 3}}i(Qf,"convertedReachedIndex");function cd(e){return {key:"awaiting_clinic",title:kt.switchedTitle,detail:kt.switched,at:e.convertedToUploadAt??null,state:"done"}}i(cd,"convertedClinicSwitchEvent");function Xf(e){switch(e){case "submitted":case "sent":return 0;case "awaiting_upload":return 1;case "records_received":return 2;case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return 3;case "published":return 4;default:return -1}}i(Xf,"ownerReachedIndex");function Jf(e,t,r){switch(e){case "requested":return t.createdAt||null;case "awaiting_clinic":return t.lastReminderAt??null;case "processing":return t.parsingStartedAt??t.reviewStartedAt??null;case "ready":return r==="published"&&t.updatedAt||null;default:return null}}i(Jf,"railTimestamp");function dd(e,t,r,o){return {key:e,title:Dn[e],detail:Gf(e,t,r),at:Jf(e,t,r),state:o}}i(dd,"railEvent");function dr(e,t){return {key:e,title:Dn[e],detail:Nf[e]??null,at:t.updatedAt||null,state:"failed"}}i(dr,"terminalEvent");function fa(e,t,r,o,n){return e.map((l,s)=>{let c=n?.(l)??null;if(c!==null)return c;let a=o==="published"||s<t?"done":s===t?"current":"upcoming";return dd(l,r,o,a)}).flatMap(l=>Kf(l,r,o))}i(fa,"walkRail");function ga(e){let t=Bf(e),r=i(n=>dd(n,e,t,"done"),"done");if(t==="revoked")return [r("requested"),dr("revoked",e)];if(e.convertedToUploadAt)return t==="failed"?[r("requested"),r("sent_to_clinic"),cd(e),r("awaiting_upload"),r("records_received"),dr("processing_failed",e)]:fa(Ff,Qf(t),e,t,n=>n==="awaiting_clinic"?cd(e):null);if(e.source==="owner_provided"){if(t==="failed"||t==="clinic_declined")return [r("requested"),r("awaiting_upload"),r("records_received"),dr("processing_failed",e)];let n=Xf(t);return fa(zf,n<0?1:n,e,t)}if(t==="clinic_declined")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),dr("clinic_declined",e)];if(t==="clinic_responded_no_records")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),dr("clinic_no_records",e)];if(t==="failed"){let n=e.failureCode??null;return n==="no_response"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),dr("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[r("requested"),dr("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),r("records_received"),dr("processing_failed",e)]:[r("requested"),dr("delivery_failed",e)]}let o=Uf(t);return fa(qf,o<0?1:o,e,t)}i(ga,"buildRequestTimeline");var tg=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),Do=24,ba=10;function Oo({request:e}){let t=og(),r=ga(e);return jsx(View,{style:t.container,accessibilityRole:"summary",children:r.map((o,n)=>jsx(rg,{event:o,isLast:n===r.length-1,styles:t},o.key))})}i(Oo,"RequestTimeline");function rg({event:e,isLast:t,styles:r}){let o=e.at?Q(e.at):null,n=[e.title,e.detail,o,tg[e.state]].filter(Boolean);return jsxs(View,{style:r.row,accessible:true,accessibilityRole:"text",accessibilityLabel:n.join(", "),testID:`records-timeline-${e.key}`,children:[jsxs(View,{style:r.railColumn,children:[jsx(ng,{state:e.state,styles:r}),t?null:jsx(View,{style:[r.connector,e.state==="done"&&r.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),jsxs(View,{style:r.body,children:[jsxs(View,{style:r.titleRow,children:[jsx(m,{style:[r.title,e.state==="current"&&r.titleCurrent,e.state==="failed"&&r.titleFailed,e.state==="upcoming"&&r.titleUpcoming],children:e.title}),o?jsx(m,{style:r.date,children:o}):null]}),e.detail?jsx(m,{style:[r.detail,e.state==="upcoming"&&r.detailUpcoming],children:e.detail}):null]})]})}i(rg,"TimelineRow");function ng({state:e,styles:t}){return e==="done"?jsx(View,{style:[t.dot,t.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:[t.glyph,t.glyphOnBrand],children:"\u2713"})}):e==="failed"?jsx(View,{style:[t.dot,t.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:t.glyph,children:"!"})}):e==="current"?jsx(View,{style:[t.dot,t.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(View,{style:t.dotCurrentCore})}):jsx(View,{style:[t.dot,t.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(ng,"TimelineDot");function og(){let e=V();return useMemo(()=>ig(e),[e])}i(og,"useStyles");function ig(e){let{color:t,type:r}=e,{size:o}=r;return StyleSheet.create({container:{gap:0},row:{flexDirection:"row",alignItems:"flex-start",gap:12},railColumn:{alignItems:"center",width:Do},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},dot:{width:Do,height:Do,borderRadius:Do/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:t.brand},dotFailed:{backgroundColor:t.danger},dotCurrent:{borderWidth:2,borderColor:t.brand,backgroundColor:t.surface},dotCurrentCore:{width:ba,height:ba,borderRadius:ba/2,backgroundColor:t.brand},dotUpcoming:{borderWidth:2,borderColor:t.borderHairlineGreen,backgroundColor:t.surface},glyph:{..._(e,"bold"),fontSize:o.caption,lineHeight:o.caption+2,color:t.surface},glyphOnBrand:{color:t.onPrimary},connector:{width:2,flex:1,minHeight:22,backgroundColor:t.borderHairlineGreen,marginVertical:2},connectorDone:{backgroundColor:t.brand},title:{flex:1,..._(e,"bold"),fontSize:o.body,lineHeight:o.body+4,color:t.text.primary},titleCurrent:{color:t.brandInk},titleFailed:{color:t.danger},titleUpcoming:{color:t.text.muted,..._(e,"regular")},date:{..._(e,"regular"),fontSize:o.caption,lineHeight:o.caption+4,color:t.text.muted},detail:{..._(e,"regular"),fontSize:o.bodyTight,lineHeight:o.bodyTight+4,color:t.text.muted},detailUpcoming:{color:t.text.muted,opacity:.7}})}i(ig,"makeStyles");function Qr(e,t,r){let o=wr(e,r);switch(o.kind){case "consent_required":return jsx(lg,{onGrant:t});case "consent_unavailable":return jsx(cg,{});case "session_required":return jsx(dg,{});case "withheld":return jsx(ug,{});case "pet_not_found":case "error":return jsx(pg,{error:o.error,onRetry:e.refresh});default:return yr(o)}}i(Qr,"renderErrorFamily");function Xr(e,t){return ()=>{let r=aa(t,e.consent);if(r.length===0)return;let o=`records-consent-${Date.now().toString(36)}`;e.grantConsent(r,o);}}i(Xr,"makeGrantHandler");function md({records:e}){let t=On(),r=e.uploadQueue;if(r.length===0)return null;let o=r.filter(s=>s.status!=="skipped"),n=o.filter(s=>s.status==="done").length,l=ad(sd(r));return jsxs(View,{style:t.timeline,testID:"records-upload-queue",children:[l!==null?jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:t.errorText,children:l}):null,o.length>0?jsx(View,{accessibilityLiveRegion:"polite",accessibilityLabel:e.isUploading?Nr.uploading(n,o.length):Nr.uploaded(n,o.length),children:o.map(s=>{let c=Math.round(s.progress*100);return jsxs(View,{style:t.row,testID:`records-upload-file-${s.status}`,children:[jsx(m,{style:t.rowLabel,children:s.name??""}),jsx(m,{style:t.rowValue,children:id(s)}),s.status==="uploading"?jsx(View,{style:t.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:c},children:jsx(View,{style:[t.progressFill,{width:`${c}%`}]})}):null,s.status==="failed"&&s.error?jsx(m,{style:t.timelineMeta,children:s.error.displayMessage}):null]},s.key)})}):null]})}i(md,"UploadQueue");function lg({onGrant:e}){let t=On();return jsx(View,{style:t.centered,accessible:true,accessibilityRole:"alert",accessibilityLabel:de.consentRequired,children:jsx(Pressable,{onPress:e,accessibilityRole:"button",accessibilityLabel:de.allow,style:t.primaryButton,children:jsx(m,{style:t.primaryLabel,children:de.allow})})})}i(lg,"ConsentRequiredState");function va({label:e,glyph:t}){let r=On();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e);},[e]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:e,children:[jsx(View,{style:t==="withheld"?r.withheldGlyph:r.emptyGlyph}),jsx(m,{style:r.errorText,children:e})]})}i(va,"AlertState");function cg(){return jsx(va,{label:de.consentRequired,glyph:"empty"})}i(cg,"ConsentUnavailableState");function dg(){return jsx(va,{label:de.sessionRequired,glyph:"empty"})}i(dg,"SessionRequiredState");function ug(){return jsx(va,{label:de.recordUnavailable,glyph:"withheld"})}i(ug,"WithheldState");function pg({error:e,onRetry:t}){let r=On();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e.displayMessage);},[e.displayMessage]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:[jsx(m,{style:r.errorText,children:e.displayMessage}),e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:de.retry,style:r.primaryButton,children:jsx(m,{style:r.primaryLabel,children:de.retry})}):null]})}i(pg,"ErrorState");function yd({call:e,prompt:t}){let r=On(),o=t.trim().length>0?t:Pn.fallbackPrompt;return jsxs(View,{style:r.callCard,accessibilityRole:"summary",children:[jsx(m,{style:r.timelineLabel,children:Pn.heading}),jsx(m,{style:r.timelineMeta,children:o}),jsx(Pressable,{onPress:()=>{Linking?.openURL?.(e.dial);},accessibilityRole:"button",accessibilityLabel:Pn.callAt(e.phone),style:r.linkButton,testID:"records-call-clinic",children:jsx(m,{style:r.linkLabel,children:Pn.call})})]})}i(yd,"ClinicCallCard");function On(){let e=V();return useMemo(()=>mg(e),[e])}i(On,"useStyles");function mg(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c,letterSpacing:a}=n,d=Je(l.recordCard,StyleSheet.hairlineWidth),u=ot(l.recordCard),p=i((f,E)=>Math.round(f*E),"lh"),g=StyleSheet.hairlineWidth,h=r.xxl*3+r.xl,R=r.xxl+r.md,v=r.xxl+r.sm,x=e.brightness==="dark"?t.errorRed:t.danger,y={shadowColor:t.brand,shadowOffset:{width:0,height:r.xs},shadowRadius:r.sm,shadowOpacity:.08,elevation:r.xs};return StyleSheet.create({container:{flex:1,minHeight:h,backgroundColor:t.background},body:{flex:1},centered:{minHeight:h,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:v,height:v,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:g,borderColor:t.brandBorder},withheldGlyph:{width:v,height:v,borderRadius:o.sm,backgroundColor:t.badgeBgCaution,borderWidth:g,borderColor:t.cautionAccent},errorText:{..._(e,"regular"),fontSize:s.subtitle,lineHeight:p(s.subtitle,c.snug),color:x,textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...y,...Je(l.primaryButton)},primaryLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,letterSpacing:a.tight,...ot(l.primaryButton)},linkButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...y,...Je(l.primaryButton)},linkLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,letterSpacing:a.tight,...ot(l.primaryButton)},disabledButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.surfaceSubtle,borderWidth:g,borderColor:t.brandBorder},disabledLabel:{..._(e,"bold"),color:t.text.muted,fontSize:s.body,letterSpacing:a.tight},list:{flex:1},listContent:{padding:r.lg,gap:r.md},timeline:{paddingVertical:r.md,paddingHorizontal:r.lg,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:g,borderColor:t.brandBorder,gap:r.xs,...y,...d},timelineTitle:{..._(e,"bold"),fontSize:s.heading,lineHeight:p(s.heading,c.snug),color:t.text.primary,letterSpacing:a.tight,...u},timelineLabel:{..._(e,"bold"),fontSize:s.subtitle,lineHeight:p(s.subtitle,c.snug),color:t.text.secondary,letterSpacing:a.tight,...u},callCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:g,borderColor:t.brandBorder,...d},timelineMeta:{..._(e,"regular"),fontSize:s.bodyTight,lineHeight:p(s.bodyTight,c.normal),color:t.text.muted,...u},recordBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:g,borderColor:t.brandBorder,...y,...d},row:{flexDirection:"row",justifyContent:"space-between",gap:r.md,paddingVertical:r.xs,borderBottomWidth:g,borderBottomColor:t.borderHairlineGreen},rowLabel:{..._(e,"regular"),fontSize:s.body,lineHeight:p(s.body,c.normal),color:t.text.muted,flexShrink:1,...u},rowValue:{..._(e,"medium"),fontSize:s.body,lineHeight:p(s.body,c.normal),color:t.text.primary,textAlign:"right",flexShrink:1,...u},disclaimer:{..._(e,"regular"),fontSize:s.caption,lineHeight:p(s.caption,c.normal),color:t.text.muted,marginTop:r.md},progressTrack:{height:r.xs,borderRadius:o.pill,backgroundColor:t.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:t.brand}})}i(mg,"makeStyles");var gg=i((e,t)=>e.getRecordDepth(t),"readDepth"),bg=i(e=>!e.available,"depthEmpty");function Ea(e){let{style:t,renderPending:r,...o}=ze(e,["onNavigate","onBack","onAsk"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(hg,{...o,style:t})})}i(Ea,"EverfurRecordsDashboard");function hg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,style:c}){let a=be(),d=Sa(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=ta(e),g=$t(e,gg,bg),[h,R]=useState(null),v=useCallback((w,T)=>R({marker:w,point:T}),[]),x=useMemo(()=>zr(o,u.consent),[o,u.consent]),y=useMemo(()=>Xr(u,o),[u,o]),f=p.markers?.markers??[],E=f.length>0,b=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,C=Xn(u.requests,e),D=pi({hasMarkers:E,requests:u.requests,petRef:e}),S=mi({recordLoading:u.status==="loading",hasFullRecord:b,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:E,requestsLoading:u.status==="loading",dashboardState:D,drivingRequest:C}),k=p.markers?.disclaimer??u.record?.disclaimer??"",I=i(()=>{u.refresh(),p.refresh(),g.refresh();},"retryAll"),G=g.value!==null&&!g.value.withheld&&g.value.available?g.value:null,z=He(t),Y=s&&p.markers?.summary?()=>{let w=kc(t,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);s(w.prompt,w.entityRef);}:void 0,H=s?w=>{let T=Sc(t,{canonicalName:w.name,markerId:w.markerId,latestValueText:w.latest?Et(w.latest.value,w.unit,w.latest.qualitativeResult):null,statusText:w.latest?Xt(w.latest.status).label:null,trajectoryText:jr(w.trajectory,w.points.length),meaningText:w.meaning});s(T.prompt,T.entityRef);}:void 0,Z=s&&h?()=>{let{marker:w,point:T}=h,O=Tc(t,{canonicalName:w.name,valueText:Et(T.value,w.unit,T.qualitativeResult),collectedAt:Q(T.at),sourceClinic:T.sourceClinic,referenceText:T.refLow!==null||T.refHigh!==null?bo(T,w.unit):null,flagged:T.status==="above"?"above":T.status==="below"?"below":null,reviewed:T.reviewed,entityId:T.docId??w.markerId});R(null),s(O.prompt,O.entityRef);}:void 0,oe=jsxs(Fragment,{children:[p.markers?.summary?jsx(View,{style:a.inset,children:jsx(zc,{summary:p.markers.summary,onAsk:Y,testID:"dashboard-marker-summary"})}):null,jsx(m,{style:a.lead,children:dt.lead(t)}),jsx(Hc,{markers:f,onPointPress:v,onAsk:H})]}),Ee=i(w=>n?jsxs(View,{style:[a.inset,d.actions],children:[w?jsx(xa,{label:dt.viewFullRecord,onPress:()=>n({name:"record"}),testID:"dashboard-full-record-action"}):null,jsx(xa,{label:dt.viewTimeline,onPress:()=>n({name:"timeline"}),testID:"dashboard-timeline-action"})]}):null,"actions"),U;if(u.status==="error"){let w=wr(u,x);U=w.kind==="error"||w.kind==="pet_not_found"?jsx(Qe,{variant:wt(w.error),message:w.error.displayMessage,onAction:w.error.retryable?I:void 0,testID:"dashboard-error"}):Qr(u,y,x);}else switch(S){case "loading":U=jsx(ao,{testID:"dashboard-loading"});break;case "record":U=jsxs(ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-record",children:[E?oe:p.status==="error"?jsx(View,{style:[a.inset,d.actions],children:jsx(xa,{label:dt.retryMarkers,onPress:I,testID:"dashboard-markers-retry"})}):null,jsx(View,{style:a.inset,children:u.record?jsx(Io,{record:u.record,depth:G,petName:t,showLabs:!E,onNavigate:n,onAsk:s}):null}),Ee(true)]});break;case "error":U=jsx(Qe,{variant:wt(p.error??u.error),message:(p.error??u.error)?.displayMessage,onAction:(p.error??u.error)?.retryable?I:void 0,testID:"dashboard-error"});break;case "in_progress":U=jsxs(ScrollView,{contentContainerStyle:a.content,testID:"dashboard-in-progress",children:[C?jsx(Rg,{request:C,petName:z,onOpen:n?()=>n({name:"request",requestId:C.id}):void 0,onAsk:s?()=>{let w=_c(t,{clinicName:C.clinicName??null,statusLabel:kn(C),status:C.status,heldItemCount:C.heldItemCount},C.id);s(w.prompt,w.entityRef);}:void 0}):null,jsx(vr,{disclaimer:k})]});break;case "none":U=jsxs(ScrollView,{contentContainerStyle:a.content,testID:"dashboard-request-prompt",children:[jsxs(View,{style:d.promptCard,children:[jsxs(View,{style:d.promptHeader,children:[jsx(View,{style:d.promptGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.promptTitle,children:Pr.title(t)})]}),jsx(m,{style:d.promptBody,children:Pr.body}),n?jsxs(Fragment,{children:[jsx(re,{label:Pr.requestFromClinic,accessibilityLabel:Pr.requestFromClinicA11y(t),onPress:()=>n({name:"clinicPicker"}),style:d.promptCta,testID:"dashboard-request-prompt-clinic"}),jsx(re,{label:Pr.uploadDocument,kind:"outline",accessibilityLabel:Pr.uploadDocumentA11y(t),onPress:()=>n({name:"upload"}),style:d.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),jsx(vr,{disclaimer:k})]});break;case "labs_only":U=jsxs(ScrollView,{contentContainerStyle:a.contentTight,testID:"dashboard-labs-only",children:[oe,jsx(View,{style:a.inset,children:jsx(vr,{disclaimer:k})}),Ee(false)]});break;default:U=yr(S);}return jsxs(View,{style:[a.root,c],children:[jsx(et,{title:dt.title,onBack:l,testID:"dashboard-header",right:n?jsx(Pressable,{onPress:()=>n({name:"timeline"}),accessibilityRole:"button",accessibilityLabel:dt.openTimeline,hitSlop:12,style:d.headerButton,testID:"dashboard-timeline-link",children:jsx(xl,{})}):void 0}),jsx(View,{style:a.body,children:U}),jsx(Uc,{marker:h?.marker??null,point:h?.point??null,onClose:()=>R(null),onAsk:Z}),jsx(Me,{})]})}i(hg,"DashboardBody");function xa({label:e,onPress:t,testID:r}){let o=Sa();return jsxs(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:e,style:o.actionRow,testID:r,children:[jsxs(View,{style:o.actionLeft,children:[jsx(View,{style:o.actionIcon,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:o.actionLabel,children:e})]}),jsx(Ir,{})]})}i(xa,"ActionRow");function Rg({request:e,petName:t,onOpen:r,onAsk:o}){let n=be(),l=Sa(),s=e.clinicName?.trim()||Hr.title(t),c=kn(e),a=jsxs(View,{style:l.inProgressInner,children:[jsxs(View,{style:l.inProgressHead,children:[jsx(m,{style:l.inProgressTitle,children:s}),r?jsx(Ir,{}):null]}),jsx(Oo,{request:e}),c.length>0?jsx(View,{style:n.statusCard,children:jsx(m,{style:n.statusText,children:c})}):null]});return jsxs(View,{style:l.inProgressCard,testID:"dashboard-in-progress-card",accessibilityRole:"summary",accessible:r?false:void 0,accessibilityLabel:r?void 0:Hr.a11y(t),children:[r?jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Hr.openA11y(t,c),testID:"dashboard-in-progress-open",children:a}):a,o?jsx(re,{label:Hr.ask,kind:"ask",accessibilityLabel:Hr.askA11y,onPress:o,testID:"dashboard-in-progress-ask"}):null]})}i(Rg,"InProgressCard");function Sa(){let e=V();return useMemo(()=>vg(e),[e])}i(Sa,"useLocalStyles");function vg(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=r.xxl+r.md;return StyleSheet.create({headerButton:{width:s,height:s,alignItems:"center",justifyContent:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},actionIcon:{width:r.lg+r.xs/2,height:r.lg+r.xs/2,borderRadius:o.xs,backgroundColor:t.brandSoft,borderWidth:l,borderColor:t.brandBorder},actionLabel:{flex:1,..._(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},inProgressCard:{borderRadius:o.lg-r.xs/2,backgroundColor:t.surface,borderWidth:l,borderColor:t.brandBorder,padding:r.lg+r.xs/2,gap:r.lg},inProgressInner:{gap:r.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},inProgressTitle:{flex:1,..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),color:t.text.primary},promptCard:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:l,borderColor:t.borderRingCream,paddingHorizontal:r.lg+r.xs,paddingVertical:r.lg+r.xs/2},promptHeader:{flexDirection:"row",alignItems:"center",gap:r.xs+1},promptGlyph:{width:r.xl+1,height:r.xl+1,borderRadius:o.xs,borderWidth:2,borderColor:t.warningStrong},promptTitle:{flex:1,..._(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),letterSpacing:n.letterSpacing.headerBrand,color:t.brandInk},promptBody:{marginTop:r.sm-1,..._(e,"regular"),fontSize:n.size.bodyTight,lineHeight:r.lg+r.xs,color:t.text.primary},promptCta:{marginTop:r.sm-1,minHeight:r.xxl+r.sm},promptCtaSecondary:{marginTop:r.sm,minHeight:r.xxl+r.sm}})}i(vg,"makeLocalStyles");var Vo=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function bd(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(bd,"toMillis");function hd(e){let t=[...e.visits.map((r,o)=>({key:`visit-${o}-${r.visitId}`,kind:"visit",kindLabel:fe.kind.visit,at:r.visitDate,date:Q(r.visitDate),title:r.summary??fe.clinicVisit,detail:r.veterinarian?fe.doctor(r.veterinarian):null,docId:r.docId})),...e.vaccines.map((r,o)=>{let n=[];return r.lot&&n.push(fe.lot(r.lot)),r.expiresOn&&n.push(fe.expires(Q(r.expiresOn))),{key:`vaccine-${o}-${r.vaccineId}`,kind:"vaccine",kindLabel:fe.kind.vaccine,at:r.administeredOn,date:Q(r.administeredOn),title:r.product||fe.kind.vaccine,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}}),...e.weights.map((r,o)=>({key:`weight-${o}-${r.weightId}`,kind:"weight",kindLabel:fe.kind.weight,at:r.observedOn,date:Q(r.observedOn),title:Pl(r.weightKg),detail:null,docId:r.docId})),...e.medications.map((r,o)=>{let n=[r.dose,r.route,r.frequency].filter(l=>!!l);return {key:`medication-${o}-${r.medicationId}`,kind:"medication",kindLabel:fe.kind.medication,at:r.startedOn,date:Q(r.startedOn),title:r.drugName||fe.kind.medication,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}})];return Object.freeze(t.sort((r,o)=>{let n=bd(r.at),l=bd(o.at);return n===null&&l===null?Vo[r.kind]-Vo[o.kind]:n===null?1:l===null?-1:l!==n?l-n:Vo[r.kind]-Vo[o.kind]}))}i(hd,"buildTimelineRows");var kg=300,Tg=i((e,t)=>e.getTimeline(t),"readTimeline"),_g=i(e=>e.isEmpty,"timelineEmpty");var Pg=i(e=>e.contributions.length===0,"contributionsEmpty");function xd({petRef:e,style:t,onBack:r}){let o=$t(e,Tg,_g);return jsx(Cd,{state:o,style:t,onBack:r,header:jsx(et,{title:fe.timeline,onBack:ln(r),testID:"timeline-header"}),loading:jsx(Vl,{testID:"timeline-loading"}),empty:jsx(Qe,{variant:"no_records",testID:"timeline-empty"}),render:n=>jsx(Ag,{timeline:n})})}i(xd,"EverfurRecordsTimeline");function wd({petRef:e,docId:t,style:r,onBack:o}){let n=useCallback((c,a)=>c.getDocumentContributions(a,t),[t]),l=$t(e,n,Pg,t),s=l.value?.document?.title?.trim()||fe.uploadedDocument;return jsx(Cd,{state:l,style:r,onBack:o,header:jsx(et,{title:s,onBack:ln(o),testID:"contributions-header"}),empty:jsx(Qe,{variant:"no_records",testID:"contributions-empty"}),render:c=>jsx(Og,{view:c})})}i(wd,"EverfurDocumentContributions");function Cd({state:e,style:t,header:r,loading:o,empty:n,render:l,onBack:s}){let c=ka();return jsx(Ne,{capability:"records",style:t,...Be(ln(s),Ze),children:jsxs(View,{style:[c.container,t],children:[r??null,jsx(View,{style:c.body,children:Ig(e,l,c,o,n)}),jsx(Me,{})]})})}i(Cd,"DepthSurface");function Ig(e,t,r,o,n){switch(e.status){case "loading":return o??jsx(Dg,{styles:r});case "empty":return n??jsx(View,{style:r.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:de.empty,children:jsx(View,{style:r.emptyGlyph})});case "error":return e.error?jsx(Qe,{variant:wt(e.error),message:e.error.displayMessage,onAction:e.error.retryable?e.refresh:void 0,testID:"depth-error"}):null;case "populated":return e.value===null||e.value.withheld?null:t(e.value);default:return null}}i(Ig,"renderState");function Dg({styles:e}){let[t,r]=useState(false);return useEffect(()=>{let o=setTimeout(()=>r(true),kg);return ()=>clearTimeout(o)},[]),jsx(View,{style:e.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:de.loading,children:t?jsx(ActivityIndicator,{}):null})}i(Dg,"LoadingState");function Ag({timeline:e}){let t=ka(),r=hd(e);return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.timelineContent,accessibilityLabel:fe.timeline,children:[e.disclaimer.length>0?jsx(View,{style:t.timelineBand,accessible:true,accessibilityRole:"text",accessibilityLabel:dt.important(e.disclaimer),children:jsx(m,{style:t.timelineBandText,children:e.disclaimer})}):null,r.map((o,n)=>jsxs(View,{children:[n>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,accessible:true,accessibilityRole:"text",accessibilityLabel:[o.kindLabel,o.date,o.title,o.detail].filter(Boolean).join(", "),testID:`records-timeline-row-${o.kind}`,children:[jsx(View,{style:t.timelineBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.topLine,children:[jsx(m,{style:t.timelineKind,children:o.kindLabel}),jsx(m,{style:t.date,children:o.date})]}),jsx(m,{style:t.timelineTitle,children:o.title}),o.detail?jsx(m,{style:t.rowDetail,children:o.detail}):null]})]})]},o.key))]})}i(Ag,"TimelineBody");function Og({view:e}){let t=ka();return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.listContent,accessibilityLabel:de.records,children:[e.document?.receivedAt?jsx(m,{style:t.rowDetail,children:Q(e.document.receivedAt)}):null,jsx(View,{style:t.card,children:e.contributions.map(r=>jsxs(View,{style:t.row,accessible:true,accessibilityRole:"text",children:[jsx(m,{style:t.rowTitle,children:r.label}),jsx(m,{style:t.rowValue,children:Ur(r.value,r.unit)}),r.observedAt?jsx(m,{style:t.rowDetail,children:Q(r.observedAt)}):null]},r.key))})]})}i(Og,"ContributionsBody");function ka(){let e=V();return useMemo(()=>Lg(e),[e])}i(ka,"useStyles");function Lg(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:s,lineHeight:c}=n,a=i((x,y)=>Math.round(x*y),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl*3+r.xl,p=r.xxl+r.md,g=e.brightness==="dark"?t.errorRed:t.danger,h=ot(l.recordCard),R=i((x,y,f,E="regular")=>({..._(e,E),fontSize:x,lineHeight:a(x,y),color:f}),"text"),v=i((x,y,f,E="regular")=>({...R(x,y,f,E),...h}),"inCard");return StyleSheet.create({container:{flex:1,minHeight:u,backgroundColor:t.background},body:{flex:1},centered:{minHeight:u,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:r.xxl+r.sm,height:r.xxl+r.sm,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},errorText:{...R(s.subtitle,c.snug,g),textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:p,minWidth:p,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...Je(l.primaryButton)},primaryLabel:{..._(e,"bold"),color:t.onPrimary,fontSize:s.body,...ot(l.primaryButton)},list:{flex:1},listContent:{padding:r.lg,gap:r.md},section:{gap:r.sm},heading:{...R(s.heading,c.snug,t.text.primary,"bold")},card:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:d,borderColor:t.brandBorder,...Je(l.recordCard,d)},row:{gap:r.xs,paddingVertical:r.xs,borderBottomWidth:d,borderBottomColor:t.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:r.md},kindLabel:{...v(s.caption,c.normal,t.text.muted,"medium")},date:v(s.caption,c.normal,t.text.muted),rowTitle:{...v(s.body,c.normal,t.text.primary,"bold")},rowValue:{...v(s.body,c.normal,t.text.primary,"medium")},rowDetail:v(s.bodyTight,c.normal,t.text.muted),rowMuted:{...v(s.bodyTight,c.normal,t.text.muted),opacity:.7},chip:{...R(s.caption,c.normal,t.text.primary),alignSelf:"flex-start",paddingHorizontal:r.sm,paddingVertical:r.xs,borderRadius:o.pill},chipNeutral:{backgroundColor:t.badgeBgNeutral},chipCaution:{backgroundColor:t.badgeBgCaution},chipCritical:{backgroundColor:t.badgeBgCritical},disclaimer:{...R(s.caption,c.normal,t.text.muted),marginTop:r.md},timelineContent:{paddingBottom:r.xxl},timelineBand:{flexDirection:"row",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft,marginHorizontal:r.lg,marginTop:r.xs,marginBottom:r.md},timelineBandText:{flex:1,...R(s.caption,c.normal,t.text.secondary)},timelineSeparator:{height:d,backgroundColor:t.brandBorder,marginLeft:Ai},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBubble:{width:r.xxl+r.xs/2,height:r.xxl+r.xs/2,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},timelineBody:{flex:1,gap:r.xs-1},timelineKind:{..._(e,"mono"),fontSize:s.micro,lineHeight:s.bodyTight,letterSpacing:n.letterSpacing.eyebrow/3,textTransform:"uppercase",color:t.text.secondary},timelineTitle:{...R(s.body,c.normal,t.text.primary,"medium")}})}i(Lg,"makeStyles");function Ta(e,t={}){let r=cr(),{userRef:o}=ke(),n=t.now??Date.now,[l,s]=useState(null),[c,a]=useState(true),[d,u]=useState(null),[p,g]=useState(null),h=p===true,[R,v]=useState({}),[x,y]=useState(false),[f,E]=useState(null),[b,C]=useState(false),[D,S]=useState(false),k=Bn(e),I=useRef(0),G=useRef(true),z=useCallback(async()=>{let T=I.current+=1;if(a(true),u(null),o===null){s(null),a(false);return}let O=await r.listShares(e);T!==I.current||!G.current||(O.ok?(s(O.value),g(true)):xr(O.error)?(s(null),g(false)):(s(null),u(O.error),Ed(O)&&g(true)),a(false));},[r,e,o]);useEffect(()=>(G.current=true,z(),()=>{G.current=false,I.current+=1;}),[z]);let Y=useRef(k);useEffect(()=>{Y.current!==k&&(Y.current=k,v({}),S(true),z());},[k,z]);let H=useCallback(async()=>{y(true);let T=await r.createShare(e);return G.current&&(y(false),T.ok?(v(O=>({...O,[T.value.shareId]:T.value.shareUrl})),z()):xr(T.error)?g(false):rr(T.error)&&S(true)),T},[r,e,z]),Z=useCallback(async T=>{E(T);let O=await r.revokeShare(e,T);return G.current&&(E(null),z()),O},[r,e,z]),oe=useCallback(async()=>{C(true);let T=await r.getPdfLink(e);return G.current&&(C(false),!T.ok&&rr(T.error)&&S(true)),T},[r,e]),Ee=useCallback(()=>{S(false),z();},[z]),U=useMemo(()=>Il(l??[],R,n()),[l,R,n]),w=c?"loading":d!==null?"error":U.length===0?"empty":"populated";return useMemo(()=>({status:w,rows:U,available:h,consentRequired:D,error:d,creating:x,revokingId:f,preparingPdf:b,createLink:H,revoke:Z,pdfLink:oe,refresh:Ee}),[w,U,h,D,d,x,f,b,H,Z,oe,Ee])}i(Ta,"useRecordShares");function Ed(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(Ed,"answeredBehindGate");function Sd(e){return e.available||e.status!=="empty"}i(Sd,"sharesListShown");function _a(e){let t=cr(),{userRef:r}=ke(),o=useMemo(()=>({}),[t,e,r]),[n,l]=useState({scope:o,lit:null});useEffect(()=>{if(r===null)return;let c=true;return t.listShares(e).then(a=>{c&&(!a.ok&&xr(a.error)?l({scope:o,lit:false}):Ed(a)&&l({scope:o,lit:true}));},()=>{}),()=>{c=false;}},[t,e,r,o]);let s=n.scope===o?n.lit:null;return useMemo(()=>({lit:s}),[s])}i(_a,"useRecordsDepthProbe");function Pa(e){let t=cr(),o=_a(e).lit===true,[n,l]=useState(false),[s,c]=useState(null),a=useRef(true);useEffect(()=>(a.current=true,()=>{a.current=false;}),[]);let d=useCallback(async()=>{l(true),c(null);let u=await t.getPdfLink(e);return a.current&&(l(false),u.ok||c(u.error)),u},[t,e]);return useMemo(()=>({preparing:n,available:o,error:s,pdfLink:d}),[n,o,s,d])}i(Pa,"useRecordPdfLink");var Tt=K.document,_d=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),Fg=i((e,t)=>e.getRecordDepth(t),"readDepth"),Ng=i(e=>!e.available,"depthEmpty");function Ia(e){let{style:t,renderPending:r,...o}=ze(e,["onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(Bg,{...o,style:t})})}i(Ia,"EverfurRecordDocument");function Mg(e,t){return e.identity.length===0&&e.entities.length===0&&e.forwardLooking.length===0&&(t===null||t.labResults.length===0&&t.physicalExams.length===0&&t.clinicianNotes.length===0)}i(Mg,"documentIsEmpty");function Bg({petRef:e,petName:t,controller:r,consentVersion:o,onBack:n,onOpenUrl:l,style:s}){let c=be(),a=Pd(),d=V(),u=yt(r?{petRef:e,controller:r}:{petRef:e}),p=$t(e,Fg,Ng),g=Pa(e),h=useMemo(()=>zr(o,u.consent),[o,u.consent]),R=useMemo(()=>Xr(u,o),[u,o]),v=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,x=u.record,y=i(()=>{g.pdfLink().then(b=>{if(!b.ok)return;Tr(l??(D=>Linking.openURL(D)),b.value.downloadUrl,"record_pdf");});},"download"),f,E=false;if(u.status==="loading"||p.status==="loading"&&x!==null)f=jsx(View,{style:a.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:dt.loading,testID:"record-document-loading",children:jsx(ActivityIndicator,{color:d.color.brandInk})});else if(u.status==="error"){let b=wr(u,h);f=b.kind==="error"||b.kind==="pet_not_found"?jsx(Qe,{variant:wt(b.error),message:b.error.displayMessage,onAction:b.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):Qr(u,R,h);}else x===null||Mg(x,v)?f=jsx(View,{style:a.centered,testID:"record-document-empty",children:jsx(m,{style:a.emptyText,children:Tt.empty})}):(E=true,f=jsx(Hg,{record:x,depth:v,petName:t,wordmark:d.meta.displayName}));return jsxs(View,{style:[c.root,a.root,s],children:[jsx(et,{title:Tt.title,variant:"document",onBack:n,testID:"record-document-header",right:g.available&&E?jsx(Pressable,{onPress:y,disabled:g.preparing,accessibilityRole:"button",accessibilityLabel:Tt.download,accessibilityState:{disabled:g.preparing,busy:g.preparing},hitSlop:8,style:a.download,testID:"record-document-download",children:g.preparing?jsx(ActivityIndicator,{size:"small",color:d.color.brandInk}):jsx(El,{})}):void 0}),g.error?jsx(m,{style:[c.errorText,a.inset],accessibilityRole:"alert",children:g.error.displayMessage}):null,jsx(View,{style:c.body,children:f}),jsx(Me,{})]})}i(Bg,"DocumentBody");function Hg({record:e,depth:t,petName:r,wordmark:o}){let n=Pd(),l=useMemo(()=>{let a=[],d=new Map;for(let g of e.entities){let h=g.category.trim();if(h.length===0)continue;let R=d.get(h);R===void 0?(a.push(h),d.set(h,[g])):R.push(g);}let u=_d.filter(g=>a.includes(g)),p=a.filter(g=>!_d.includes(g));return [...u,...p].map(g=>({type:g,rows:d.get(g)??[]}))},[e.entities]),s=Date.now(),c=i((a,d,u)=>jsxs(View,{style:n.section,testID:u,children:[jsxs(View,{style:n.sectionHeader,children:[jsx(m,{style:n.sectionTitle,accessibilityRole:"header",children:a}),jsx(View,{style:n.rule})]}),jsx(View,{children:d})]},u),"section");return jsxs(ScrollView,{contentContainerStyle:n.page,showsVerticalScrollIndicator:false,testID:"record-document",children:[jsxs(View,{style:n.letterhead,children:[jsx(m,{style:n.wordmark,children:o}),jsx(m,{style:n.docTitle,children:Tt.docTitle}),jsx(m,{style:n.petName,children:r?.trim()||Tt.namelessPet}),jsx(m,{style:n.generated,children:Tt.generated(e.generatedAt)})]}),e.identity.length>0?c(Tt.identity,e.identity.map((a,d)=>jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsx(m,{style:n.rowLabel,children:a.label}),jsx(m,{style:n.rowValue,children:a.value})]},`${d}:${a.label}`)),"record-document-identity"):null,t&&t.labResults.length>0?c(Tt.labs,t.labResults.map((a,d)=>{let u=Xt(a.latest.status),p=Gc(a.points[a.points.length-1]??null),g=Et(a.latest.value,a.latest.unit??a.unit,a.latest.qualitativeResult);return jsxs(View,{style:[n.row,u.outOfRange?n.rowFlag:null,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:a.name}),jsxs(m,{style:n.rowMeta,children:[p?Tt.ref(p):Tt.noRange,a.latest.at?` \xB7 ${Q(a.latest.at)}`:""]})]}),jsxs(View,{style:n.rowRight,children:[g!=="-"?jsx(m,{style:[n.rowValue,u.outOfRange?n.rowValueAlert:null],children:g}):null,jsx(m,{style:[n.markerStatus,u.outOfRange?n.rowValueAlert:null],children:u.label})]})]},a.markerId)}),"record-document-labs"):null,l.map(({type:a,rows:d})=>c(Fr(a),d.map((u,p)=>{let g=[Ur(u.value,u.unit),u.observedAt?Q(u.observedAt):null].filter(h=>h&&h.length>0).join(" \xB7 ");return jsx(View,{style:[n.row,p>0?n.rowDivider:null],children:jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:u.label}),g?jsx(m,{style:n.rowMeta,children:g}):null]})},u.key)}),`record-document-${a}`)),e.forwardLooking.length>0?c(Tt.upcomingCare,e.forwardLooking.map((a,d)=>{let u=_n(a.dueAt,s);return jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:a.title}),a.detail?jsx(m,{style:n.rowMeta,children:a.detail}):null]}),u?jsx(m,{style:[n.rowValue,u.overdue?n.rowValueAlert:null],children:u.label}):null]},`${a.title}-${d}`)}),"record-document-upcoming"):null,t&&t.physicalExams.length>0?c(Tt.physicalExams,t.physicalExams.map((a,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[a.observedOn?jsx(m,{style:n.blockDate,children:Q(a.observedOn)}):null,a.systems.filter(u=>u.finding).map(u=>jsxs(View,{style:n.fieldRow,children:[jsx(m,{style:n.fieldLabel,children:Dr(u.system)}),jsx(m,{style:n.fieldValue,children:u.finding})]},u.system))]},a.examId)),"record-document-exams"):null,t&&t.clinicianNotes.length>0?c(Tt.clinicianNotes,t.clinicianNotes.map((a,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[a.observedOn?jsx(m,{style:n.blockDate,children:Q(a.observedOn)}):null,a.sections.filter(u=>u.text).map((u,p)=>jsxs(View,{style:n.noteSection,children:[jsx(m,{style:n.noteLabel,children:$r(u.section)}),jsx(m,{style:n.noteBody,children:u.text})]},`${u.section}-${p}`))]},a.noteId)),"record-document-notes"):null,e.disclaimer.length>0?jsx(View,{style:n.disclaimer,children:jsx(m,{style:n.disclaimerText,children:e.disclaimer})}):null]})}i(Hg,"RecordDocument");function Pd(){let e=V();return useMemo(()=>Ug(e),[e])}i(Pd,"useLocalStyles");function Ug(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,s=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text"),c=i((a,d)=>({..._(e,"mono"),fontSize:a,lineHeight:a+r.xs-1,color:d,letterSpacing:n.letterSpacing.eyebrow/2,textTransform:"uppercase"}),"mono");return StyleSheet.create({root:{backgroundColor:t.surface},inset:{paddingHorizontal:r.lg},download:{width:r.xxl+r.xs+r.xs/2,height:r.xxl+r.xs+r.xs/2,borderRadius:o.pill,alignItems:"center",justifyContent:"center"},centered:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xxl,minHeight:r.xxl*3+r.xl},emptyText:{...s(n.size.body,n.lineHeight.normal,t.text.muted,"medium"),textAlign:"center"},page:{paddingHorizontal:r.lg+r.xs,paddingBottom:r.xxl+r.lg},letterhead:{alignItems:"center",paddingTop:r.md,paddingBottom:r.lg+r.xs+r.xs/2,borderBottomWidth:2,borderBottomColor:t.brand,gap:r.xs+r.xs/2,marginBottom:r.sm},wordmark:{...s(n.size.heading,n.lineHeight.snug,t.brandInk,"bold"),letterSpacing:n.letterSpacing.headerBrand},docTitle:{...c(n.size.caption,t.brandInk),marginTop:r.sm+r.xs/2,letterSpacing:n.letterSpacing.eyebrow+.4},petName:s(n.size.verdict+r.xs/2,n.lineHeight.tight,t.text.primary),generated:{...c(n.size.tiny,t.text.muted),textTransform:"none"},section:{marginTop:r.lg+r.xs+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2,marginBottom:r.sm},sectionTitle:c(n.size.tiny,t.brandInk),rule:{flex:1,height:l,backgroundColor:t.borderHairlineGreen},row:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.md+r.xs/2,paddingVertical:r.sm+1},rowDivider:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen},rowFlag:{backgroundColor:t.badgeBgCritical,marginHorizontal:-r.sm,paddingHorizontal:r.sm,borderRadius:o.xs},rowMain:{flexShrink:1},rowRight:{alignItems:"flex-end",gap:r.xs/2},rowLabel:{flexShrink:1,...s(n.size.body,n.lineHeight.normal,t.text.primary,"medium")},rowValue:{...s(n.size.body,n.lineHeight.normal,t.text.primary,"bold"),textAlign:"right"},rowValueAlert:{color:t.danger},rowMeta:{marginTop:r.xs/2,..._(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},markerStatus:c(n.size.micro,t.text.muted),block:{paddingVertical:r.sm+r.xs/2},blockDate:{...c(n.size.tiny,t.text.muted),marginBottom:r.xs+r.xs/2},fieldRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md+r.xs/2,paddingVertical:r.xs-1},fieldLabel:{width:120,...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted,"medium")},fieldValue:{flex:1,...s(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")},noteSection:{marginTop:r.sm},noteLabel:{...c(n.size.tiny,t.brandInk),marginBottom:r.xs/2},noteBody:s(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),disclaimer:{marginTop:o.xl,paddingTop:r.md+r.xs/2,borderTopWidth:l,borderTopColor:t.borderHairlineGreen},disclaimerText:s(n.size.tiny,n.lineHeight.relaxed,t.text.muted)})}i(Ug,"makeLocalStyles");function Ad({petRef:e,onClose:t,onNavigate:r,onOpenUrl:o,onCopy:n}){let l=Yg(),s=be(),c=Ta(e),[a,d]=useState(null),[u,p]=useState(null),g=c.available&&!c.consentRequired,h=i((f,E)=>{Tr(o??(C=>Linking.openURL(C)),f,E).then(C=>{C.ok||d(ue.toasts.shareSheet);});},"open"),R=i(()=>{d(null),c.createLink().then(f=>{f.ok?h(f.value.shareUrl,"share_link"):d(no(f.error,"create"));});},"onCreateLink"),v=i(()=>{d(null),c.pdfLink().then(f=>{f.ok?h(f.value.downloadUrl,"record_pdf"):d(no(f.error,"download"));});},"onDownload"),x=i(f=>{!n||f.shareUrl===null||Tr(n,f.shareUrl).then(E=>d(E.ok?ue.toasts.copied:ue.toasts.copyFailed));},"onCopyRow"),y=i(f=>{c.revoke(f).then(E=>{p(null),d(E.ok?ue.toasts.turnedOff:no(E.error,"revoke"));});},"onConfirmRevoke");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:t,children:jsxs(View,{style:l.backdrop,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:ue.closeSheetA11y,onPress:t}),jsxs(View,{style:l.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[jsx(View,{style:l.handle}),jsxs(View,{style:l.header,children:[jsxs(View,{style:l.headerText,children:[jsx(m,{style:l.title,accessibilityRole:"header",children:ue.title}),jsx(m,{style:l.helper,children:ue.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:ue.close,onPress:t,hitSlop:12,style:l.closeButton,testID:"share-record-close",children:jsx(m,{style:l.closeGlyph,children:"\xD7"})})]}),jsxs(ScrollView,{style:l.scroll,contentContainerStyle:l.body,showsVerticalScrollIndicator:false,children:[jsxs(View,{style:l.actions,children:[r?jsx(re,{label:ue.viewDocument,onPress:()=>{t(),r({name:"document"});},testID:"share-view-document"}):null,g?jsx(re,{label:c.creating?ue.creatingLink:ue.createLink,kind:"outline",busy:c.creating,onPress:R,testID:"share-create-link"}):null,g?jsx(re,{label:c.preparingPdf?ue.preparingPdf:ue.downloadPdf,kind:"outline",busy:c.preparingPdf,onPress:v,testID:"share-download-pdf"}):null]}),c.consentRequired?jsxs(View,{style:l.stateCard,testID:"share-consent-off",children:[jsx(m,{style:l.stateTitle,accessibilityRole:"header",children:ue.consentOffTitle}),jsx(m,{style:l.stateBody,children:ue.consentOffBody}),jsx(re,{label:ue.retry,kind:"outline",onPress:c.refresh,testID:"share-consent-retry"})]}):null,a?jsx(m,{style:l.notice,accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:"share-notice",children:a}):null,Sd(c)?jsxs(View,{style:l.section,children:[jsx(m,{style:l.sectionLabel,accessibilityRole:"header",children:ue.activeLinks}),c.status==="loading"?jsx(zl,{testID:"share-record-loading"}):c.status==="error"?jsxs(View,{style:l.stateCard,testID:"share-record-error",children:[jsx(m,{style:l.stateTitle,children:ue.errorTitle}),jsx(m,{style:l.stateBody,children:ue.errorBody}),jsx(re,{label:ue.retry,kind:"outline",onPress:c.refresh,testID:"share-record-retry"})]}):c.rows.length===0?jsxs(View,{style:l.stateCard,testID:"share-record-empty",children:[jsx(m,{style:l.stateTitle,children:ue.emptyTitle}),jsx(m,{style:l.stateBody,children:ue.emptyBody})]}):jsx(View,{style:l.list,children:c.rows.map(f=>jsxs(View,{style:l.row,testID:`share-row-${f.shareId}`,children:[jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:f.a11yLabel,children:[jsxs(View,{style:l.statusLine,children:[jsx(View,{style:[l.statusDot,{backgroundColor:f.active?l.active.color:l.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:l.status,children:f.statusLabel}),jsx(m,{style:l.expiry,children:f.expiryLabel})]}),f.createdLabel?jsx(m,{style:l.created,children:f.createdLabel}):null]}),f.shareUrl!==null&&!n?jsx(m,{selectable:true,style:l.url,testID:`share-url-${f.shareId}`,children:f.shareUrl}):null,u===f.shareId?jsxs(View,{style:l.confirm,testID:`share-revoke-confirm-${f.shareId}`,children:[jsx(m,{style:l.confirmText,children:ue.confirmTurnOff}),jsxs(View,{style:l.rowActions,children:[jsx(re,{label:c.revokingId===f.shareId?ue.turningOff:ue.turnOff,kind:"danger",busy:c.revokingId===f.shareId,onPress:()=>y(f.shareId),testID:`share-revoke-do-${f.shareId}`}),jsx(re,{label:ue.keep,kind:"outline",disabled:c.revokingId===f.shareId,onPress:()=>p(null),testID:`share-revoke-cancel-${f.shareId}`})]})]}):jsxs(View,{style:l.rowActions,children:[n?jsx(re,{label:ue.copyLink,kind:"outline",disabled:f.shareUrl===null,accessibilityLabel:ue.copyLinkA11y(f.actionContext),onPress:()=>x(f),testID:`share-copy-${f.shareId}`}):null,jsx(re,{label:ue.turnOff,kind:"danger",accessibilityLabel:ue.turnOffA11y(f.actionContext),onPress:()=>p(f.shareId),testID:`share-ask-revoke-${f.shareId}`})]})]},f.shareId))})]}):null]}),jsx(View,{style:s.inset})]})]})})}i(Ad,"ShareSheet");function Yg(){let e=V();return useMemo(()=>Kg(e),[e])}i(Yg,"useStyles");function Kg(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,s=StyleSheet.hairlineWidth,c=i((a,d,u,p="regular")=>({..._(e,p),fontSize:a,lineHeight:Math.round(a*d),color:u}),"text");return StyleSheet.create({active:{color:t.success},inactive:{color:t.text.muted},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:"rgba(0,0,0,0.4)"},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),scroll:{flexGrow:0},body:{gap:r.lg,paddingBottom:r.sm},actions:{gap:r.sm},notice:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.secondary),padding:r.md,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft},section:{gap:r.sm},sectionLabel:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},stateCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder},stateTitle:{...c(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},stateBody:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),list:{gap:r.md},row:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:s,borderColor:t.brandBorder},statusLine:{flexDirection:"row",alignItems:"center",gap:r.sm},statusDot:{width:r.sm,height:r.sm,borderRadius:r.xs},status:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.primary,"bold")},expiry:{...c(n.size.caption,n.lineHeight.normal,t.text.muted)},created:c(n.size.tiny,n.lineHeight.normal,t.text.muted),url:{...c(n.size.caption,n.lineHeight.normal,t.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},confirm:{gap:r.sm},confirmText:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")}})}i(Kg,"makeStyles");var Jg=i((e,t)=>e.getRecordDepth(t),"readDepth"),Zg=i(e=>!e.available,"depthEmpty");function La(e){let{style:t,renderPending:r,...o}=ze(e,["onNavigate","onBack","onAsk"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(eb,{...o,style:t})})}i(La,"EverfurRecordDetail");function eb({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:s,onOpenUrl:c,onCopy:a,style:d}){let u=be(),p=tb(),g=yt(r?{petRef:e,controller:r}:{petRef:e}),h=$t(e,Jg,Zg),R=da(e),v=_a(e),[x,y]=useState(false),f=useMemo(()=>zr(o,g.consent),[o,g.consent]),E=useMemo(()=>Xr(g,o),[g,o]),b=h.value!==null&&!h.value.withheld&&h.value.available?h.value:null,C=g.record,D=i(()=>{g.refresh(),h.refresh();},"retry"),S=n!==void 0||v.lit===true,k;if(g.status==="loading"||h.status==="loading"&&C!==null&&!C.isEmpty)k=jsx(ao,{testID:"everfur-record-loading"});else if(g.status==="error"){let I=wr(g,f);k=I.kind==="error"||I.kind==="pet_not_found"?jsx(Qe,{variant:wt(I.error),message:I.error.displayMessage,onAction:I.error.retryable?D:void 0,testID:"everfur-record-error"}):Qr(g,E,f);}else if(C===null||C.isEmpty){let I=b?.completeness?.documentsInReview??0;k=jsxs(ScrollView,{contentContainerStyle:u.content,testID:"everfur-record-empty",children:[jsx(Qe,{variant:"no_records",message:I>0?K.inReview(I):void 0}),jsx(vr,{disclaimer:C?.disclaimer??""})]});}else k=jsx(ScrollView,{contentContainerStyle:p.content,testID:"everfur-record",children:jsx(Io,{record:C,depth:b,petName:t,onNavigate:n,onAsk:s,factEdit:R})});return jsxs(View,{style:[u.root,d],children:[jsx(et,{title:K.title,onBack:l,testID:"everfur-record-header",right:S||n?jsxs(Fragment,{children:[n?jsx(Pressable,{onPress:()=>n({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:K.requestClinicsA11y,hitSlop:8,style:p.share,testID:"everfur-record-request-clinics",children:jsx(Cl,{})}):null,S?jsx(Pressable,{onPress:()=>y(true),accessibilityRole:"button",accessibilityLabel:K.shareA11y,hitSlop:8,style:p.share,testID:"everfur-record-share",children:jsx(wl,{})}):null]}):void 0}),jsx(View,{style:u.body,children:k}),x?jsx(Ad,{petRef:e,onClose:()=>y(false),onNavigate:n,...c?{onOpenUrl:c}:{},...a?{onCopy:a}:{}}):null,jsx(Me,{})]})}i(eb,"RecordBody");function tb(){let e=V();return useMemo(()=>rb(e),[e])}i(tb,"useLocalStyles");function rb(e){let{space:t,radius:r}=e;return StyleSheet.create({content:{paddingHorizontal:t.lg,paddingBottom:t.xxl+t.sm,gap:t.lg+t.xs},share:{width:t.xxl+t.sm,height:t.xxl+t.sm,borderRadius:r.pill,alignItems:"center",justifyContent:"center"}})}i(rb,"makeLocalStyles");function qa(e){let{style:t,renderPending:r,...o}=ze(e,["onNavigate","onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(ab,{...o,style:t})})}i(qa,"EverfurRecordsUpload");function ab({petRef:e,petName:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:s,style:c}){let a=be(),d=Nd(),{runtime:u}=ke(),p=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),g=Sn(o)&&(r!==void 0||n!==void 0||Fn(u.registry.services.uploadTransport));return jsxs(View,{style:[a.root,c],children:[jsx(et,{title:"",onBack:s,testID:"upload-header"}),jsxs(ScrollView,{contentContainerStyle:d.content,testID:"upload-screen",children:[jsxs(View,{style:d.header,children:[jsx(View,{style:d.iconBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.title,accessibilityRole:"header",children:rt.title(t)}),jsx(m,{style:d.subtitle,children:rt.subtitle(t)})]}),jsx(za,{records:p,requestId:null,onPickDocument:o,canUpload:g,onDone:l?h=>l({name:"request",requestId:h}):void 0})]}),jsx(Me,{})]})}i(ab,"UploadBody");function za({records:e,requestId:t,onPickDocument:r,canUpload:o,onDone:n}){let l=be(),s=Nd(),[c,a]=useState(null),[d,u]=useState(0),p=useRef(t),g=useRef([]),h=e.uploadQueue.filter(b=>b.status!=="skipped"),R=h.filter(b=>b.status==="done").length,v=h.filter(b=>b.status==="failed").length,x=!e.isUploading&&d>0,y=useCallback(async b=>{if(b.length===0)return;a(null);let C=p.current;if(C===null){let S=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!S.ok){a(rt.errors.start);return}C=S.value.id,p.current=C;}u(S=>S+1);let D=await e.uploadDocuments(C,b);g.current=D.flatMap((S,k)=>S.status==="failed"&&b[k]!==void 0?[b[k]]:[]);},[e]),f=useCallback(()=>{!r||!o||Tr(r).then(b=>{if(!b.ok){a(rt.errors.startPlain);return}let C=b.value;C!==null&&y(Array.isArray(C)?C:[C]);});},[r,o,y]),E=useCallback(()=>{y(g.current);},[y]);return jsxs(View,{style:s.card,testID:"records-upload-card",children:[jsx(m,{style:s.cardTitle,accessibilityRole:"header",children:rt.cardTitle}),jsx(m,{style:s.cardSubtitle,children:rt.cardSubtitle}),c?jsx(View,{style:l.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:l.errorText,children:c})}):null,jsx(md,{records:e}),e.isUploading?jsx(View,{style:s.uploadingRow,children:jsx(m,{style:s.progressText,children:rt.uploading(R,h.length)})}):x?jsxs(View,{style:s.settled,children:[R>0?jsx(m,{style:s.success,accessibilityRole:"alert",children:rt.received(R)}):null,v>0?jsx(re,{label:rt.retryFailed(v),kind:"link",accessibilityLabel:rt.retryFailedA11y(v),onPress:E,testID:"records-upload-retry-failed"}):null,jsxs(View,{style:s.settledActions,children:[jsx(re,{label:rt.addMore,kind:"link",accessibilityLabel:rt.addMoreA11y,disabled:!o,onPress:f,testID:"records-upload-another"}),n&&p.current!==null&&R>0?jsx(re,{label:rt.done,accessibilityLabel:rt.doneA11y,onPress:()=>n(p.current),testID:"records-upload-done"}):null]})]}):jsx(re,{label:rt.chooseFiles,accessibilityLabel:rt.chooseFilesA11y,disabled:!o,onPress:f,testID:"records-upload-choose"})]})}i(za,"UploadRecordCard");function Nd(){let e=V();return useMemo(()=>sb(e),[e])}i(Nd,"useLocalStyles");function sb(e){let{color:t,space:r,radius:o,type:n}=e,l=i((s,c,a,d="regular")=>({..._(e,d),fontSize:s,lineHeight:Math.round(s*c),color:a}),"text");return StyleSheet.create({content:{padding:r.lg+r.xs,gap:r.lg+r.xs},header:{gap:r.sm,alignItems:"center"},iconBubble:{width:r.xxl+r.lg+r.xs,height:r.xxl+r.lg+r.xs,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{...l(n.size.heading+r.xs/2,n.lineHeight.snug,t.brandInk,"bold"),textAlign:"center"},subtitle:{...l(n.size.body,n.lineHeight.normal,t.text.muted),textAlign:"center",maxWidth:340},card:{borderRadius:o.md,backgroundColor:t.surface,borderWidth:1,borderColor:t.brandSoft,padding:r.lg,gap:r.md},cardTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},cardSubtitle:l(n.size.bodyTight,n.lineHeight.normal,t.text.muted),uploadingRow:{flexDirection:"row",alignItems:"center",gap:r.sm},progressText:{flex:1,...l(n.size.bodyTight,n.lineHeight.normal,t.text.secondary)},settled:{gap:r.sm},success:l(n.size.bodyTight,n.lineHeight.normal,t.text.primary),settledActions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:r.sm}})}i(sb,"makeLocalStyles");function Na(e){let{style:t,renderPending:r,...o}=ze(e,["onNavigate","onBack"]);return jsx(Ne,{capability:"records",style:t,...r?{renderPending:r}:{},...Be(o.onBack,Ze),children:jsx(yb,{...o,style:t})})}i(Na,"EverfurRecordsRequest");function yb({petRef:e,requestId:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:s,style:c,nowMs:a}){let d=be(),{runtime:u,userRef:p,scopeEpoch:g}=ke(),h=yt(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),R=h.requests.find(f=>f.id===t)??null,v=Sn(o)&&(r!==void 0||n!==void 0||Fn(u.registry.services.uploadTransport)),x=R?ho(R):"",y;return h.status==="loading"?y=jsx(Ll,{testID:"records-request-loading"}):h.status==="error"&&h.error?y=jsx(Qe,{variant:wt(h.error),message:h.error.displayMessage,onAction:h.error.retryable?h.refresh:void 0,testID:"records-request-error"}):R===null?y=jsx(Qe,{variant:"no_requests",testID:"records-request-missing"}):p===null?y=jsx(Qe,{variant:"error",testID:"records-request-error"}):y=jsx(fb,{request:R,records:h,canUpload:v,onPickDocument:o,onNavigate:l,nowMs:a},JSON.stringify([p,g,R.id])),jsxs(View,{style:[d.root,c],children:[jsx(et,{title:x,onBack:s,testID:"records-request-header"}),jsx(KeyboardAvoidingView,{behavior:"padding",style:d.body,children:y}),jsx(Me,{})]})}i(yb,"RequestBody");function fb({request:e,records:t,canUpload:r,onPickDocument:o,onNavigate:n,nowMs:l}){let s=be(),c=gb(),a=V(),d=ld({request:e,onRecovered:t.refresh,canUpload:r},Mt()),[u,p]=useState(null),[g,h]=useState(false),[R,v]=useState(null),x=useRef(true);useEffect(()=>(x.current=true,()=>{x.current=false;}),[]);let y=d.request,f=l??Date.now(),E=y.status==="published",b=y.status==="published"||y.status==="failed"||y.status==="revoked",C=fi(y),D=y.wireStatus==="clinic_responded_no_records",S=js(y,f),k=yi(y,f),I=b?null:y.waitingExpectation?.trim()||null,G=Ro(y),z=$s(y),Y=d.canConvert,H=b&&!E,Z=d.error!==null&&u!==null&&u!=="start"?u==="revoke"?ge.errors.cancel:ge.errors[u]:null,oe=i((U,w)=>{p(U),w();},"run"),Ee=i(()=>{g||(h(true),v(null),t.createRequest(`records-upload-${Date.now().toString(36)}`).then(U=>{if(x.current){if(h(false),!U.ok){v(ge.errors.start);return}n?.({name:"request",requestId:U.value.id});}}));},"startFresh");return jsxs(ScrollView,{contentContainerStyle:c.content,keyboardShouldPersistTaps:"handled",testID:`records-request-${y.id}`,children:[jsx(Oo,{request:y}),y.status==="awaiting_upload"?jsx(za,{records:t,requestId:y.id,onPickDocument:o,canUpload:r}):null,y.statusLabel.length>0?jsx(View,{style:s.statusCard,accessibilityRole:"summary",children:jsx(m,{style:s.statusText,children:y.statusLabel})}):null,I&&!S?jsx(View,{style:s.infoNote,accessibilityRole:"summary",children:jsx(m,{style:s.infoNoteText,children:I})}):y.wireStatus==="awaiting_response"&&!S?jsx(View,{style:s.infoNote,accessibilityRole:"summary",children:jsx(m,{style:s.infoNoteText,children:ge.awaitingNote})}):null,S?jsx(View,{style:s.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:jsx(m,{style:s.cautionNoteText,children:ge.waitingBanner(k)})}):null,E&&n?jsx(re,{label:ge.viewRecords,onPress:()=>n({name:"dashboard"}),style:c.readyCta,testID:"records-request-view-dashboard"}):null,z?jsxs(View,{style:[c.failureCard,C?c.failureCritical:c.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[jsx(m,{style:[c.failureTitle,C?c.failureTitleCritical:c.failureTitleCaution],children:Us(y)}),y.canUpdateClinicEmail!==true&&y.canRetrySend!==true?jsx(m,{style:s.rowDetail,children:ge.nextStep}):null,y.canUpdateClinicEmail===true?jsxs(View,{style:c.emailBlock,children:[jsx(m,{style:s.fieldLabel,children:Lt.email}),jsx(qe,{style:s.field,accessibilityLabel:Lt.email,placeholder:Lt.emailPlaceholder,placeholderTextColor:a.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,value:d.email,editable:!d.busy,onChangeText:d.setEmail,testID:"records-failure-clinic-email"}),d.emailInvalid?jsx(m,{style:s.errorText,accessibilityRole:"alert",children:ge.errors.invalidEmail}):null,jsx(re,{label:Lt.updateEmail,accessibilityLabel:Lt.updateEmailA11y,disabled:!d.canUpdateEmail,busy:d.busy&&u==="email",onPress:()=>oe("email",d.updateEmail),testID:"records-failure-update-email"})]}):null,y.canRetrySend===true?jsx(re,{label:Lt.retry,kind:"outline",accessibilityLabel:Lt.retryA11y,disabled:!d.canRetry,busy:d.busy&&u==="retry",onPress:()=>oe("retry",d.retry),testID:"records-failure-retry-send"}):null,y.canRetrySend===true&&d.hasEmailEdit?jsx(m,{style:s.rowDetail,children:Lt.retryHint}):null,Z&&(u==="email"||u==="retry")?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null]}):null,(C||D)&&n?jsx(re,{label:ge.tryAnotherClinic,kind:"outline",accessibilityLabel:ge.tryAnotherClinicA11y,onPress:()=>n({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,G!==null?jsxs(View,{style:c.callBlock,children:[jsx(yd,{call:G,prompt:y.statusLabel}),y.canRetrySend===true?jsx(re,{label:d.busy&&u==="retry"?ge.resending:ge.resend,kind:"outline",accessibilityLabel:d.busy&&u==="retry"?ge.resendingA11y:ge.resendA11y,disabled:!d.canRetry,onPress:()=>oe("retry",d.retry),testID:"records-resend-authorization"}):null]}):null,Y?jsxs(View,{style:c.block,children:[jsx(re,{label:d.busy&&u==="convert"?ge.converting:ge.convert,busy:d.busy&&u==="convert",onPress:()=>oe("convert",d.convert),testID:"records-convert-upload"}),jsx(m,{style:s.muted,children:ge.convertHint}),Z&&u==="convert"?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null]}):null,H?jsxs(View,{style:c.block,children:[jsx(re,{label:g?ge.freshUploadStarting:ge.freshUpload,kind:C||D?"outline":"primary",busy:g,onPress:Ee,testID:"records-upload-own-fresh"}),R?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:R})}):null]}):null,Z&&u==="revoke"?jsx(View,{style:s.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:s.errorText,children:Z})}):null,y.canRevoke===true?d.confirmingRevoke?jsxs(View,{style:c.block,testID:"records-revoke-confirm",children:[jsx(m,{style:c.confirmTitle,accessibilityRole:"header",children:Lt.cancelQuestion}),jsx(m,{style:s.bodyText,children:Lt.cancelConsequence}),jsx(re,{label:d.busy&&u==="revoke"?ge.cancelling:ge.cancel,kind:"danger",accessibilityLabel:d.busy&&u==="revoke"?ge.cancellingA11y:ge.cancelA11y,busy:d.busy&&u==="revoke",onPress:()=>oe("revoke",d.revoke),testID:"records-revoke-do"}),jsx(re,{label:Lt.keepRequest,kind:"outline",disabled:d.busy,onPress:d.keepRequest,testID:"records-revoke-keep"})]}):jsx(re,{label:ge.cancel,kind:"danger",accessibilityLabel:ge.cancelA11y,disabled:d.busy,onPress:d.askRevoke,testID:"records-revoke"}):null]})}i(fb,"RequestDetail");function gb(){let e=V();return useMemo(()=>bb(e),[e])}i(gb,"useLocalStyles");function bb(e){let{color:t,space:r,radius:o,type:n}=e,l=i((s,c,a,d="regular")=>({..._(e,d),fontSize:s,lineHeight:Math.round(s*c),color:a}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg+r.xs/2},readyCta:{minHeight:r.xxl+r.lg+r.xs/2},failureCard:{borderRadius:o.lg-r.xs,borderWidth:1,padding:r.md+r.xs/2,gap:r.md},failureCritical:{borderColor:t.badgeBgCritical,backgroundColor:t.badgeBgCritical},failureCaution:{borderColor:t.badgeBgCaution,backgroundColor:t.badgeBgCaution},failureTitle:{...l(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},failureTitleCritical:{color:t.danger},failureTitleCaution:{color:t.warningStrong},emailBlock:{gap:r.sm},callBlock:{gap:r.sm},block:{gap:r.sm},confirmTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")}})}i(bb,"makeLocalStyles");function Md(e){let{petRef:t,petName:r,controller:o,clinicController:n,onPickDocument:l,uploadTransport:s,consentVersion:c,ownerName:a,onCaptureSignature:d,initialScreen:u,onExit:p,style:g,renderPending:h,onOpenUrl:R,onCopy:v,onAsk:x,location:y}=ze(e,["onExit"]),[f,E]=useReducer(ai,u,Wn),b=Gn(f),C=f.stack.length;useEffect(()=>{let Y=i(()=>C<=1?false:(E({type:"pop"}),true),"onBackPress"),H=BackHandler.addEventListener("hardwareBackPress",Y);return ()=>{H.remove();}},[C]);let D=useCallback(Y=>E({type:"navigate",screen:Y}),[]),S=useMemo(()=>Yn(f).handled?()=>E({type:"pop"}):p,[f,p]),k={onNavigate:D,...S?{onBack:S}:{},...r!==void 0?{petName:r}:{},...R?{onOpenUrl:R}:{},...v?{onCopy:v}:{},...x?{onAsk:x}:{},...y?{location:y}:{}},I={...o?{controller:o}:{},...c!==void 0?{consentVersion:c}:{}},G={...l?{onPickDocument:l}:{},...s?{uploadTransport:s}:{}},z=h?{renderPending:h}:{};switch(b.name){case "dashboard":return jsx(Ea,{petRef:t,...k,...I,...z,style:g});case "request":return jsx(Na,{petRef:t,requestId:b.requestId,...k,...I,...G,...z,style:g});case "timeline":return jsx(xd,{petRef:t,...k,style:g});case "record":return jsx(La,{petRef:t,...k,...I,...z,style:g});case "document":return jsx(Ia,{petRef:t,...k,...I,...z,style:g});case "contributions":return jsx(wd,{petRef:t,docId:b.docId,...k,style:g});case "clinicPicker":return jsx(Oi,{petRef:t,...k,...n?{controller:n}:{},...o?{recordsController:o}:{},style:g});case "clinicBatch":return jsx(Ki,{petRef:t,petName:r??"",ownerName:a??"",...S?{onClose:S}:{},onCreated:()=>E({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:g});case "consent":return jsx(oa,{petRef:t,clinic:b.clinic,...k,...a!==void 0?{ownerName:a}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:g});case "upload":return jsx(qa,{petRef:t,...k,...o?{controller:o}:{},...G,...z,style:g});default:return yr(b)}}i(Md,"EverfurRecordsFlow");var Cb=Md;function Tb(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Ne,{capability:"recordsClinic",...Be(e.onClose,$.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:de.sessionRequired}):jsx(_b,{...ze(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(Tb,"EverfurClinicRequest");function _b(e){let t=Mt(),[r,o]=useState(null),n=useCallback(async()=>r===null?null:{signaturePngBase64:r},[r]),l=Nl(e,e.controller??t,e.onCaptureSignature??n),s=e.onCaptureSignature!==void 0||r!==null,c=V(),a={minHeight:44,padding:c.space.sm,borderWidth:1,borderColor:c.color.borderHairlineGreen,borderRadius:c.radius.sm,color:c.color.text.primary,backgroundColor:c.color.surface},d={color:c.color.text.primary,fontSize:c.type.size.body},u=i((p,g,h=false)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:p,accessibilityState:{disabled:h},disabled:h,onPress:g,style:[a,{justifyContent:"center",opacity:h?.5:1}],children:jsx(m,{style:d,children:p})}),"button");return jsxs(View,{accessibilityLabel:$.title,style:[{backgroundColor:c.color.surface,padding:c.space.lg,gap:c.space.md,borderRadius:c.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[d,{..._(c,"bold"),fontSize:c.type.size.heading}],children:$.title}),jsx(m,{style:d,children:e.petName}),l.created?jsx(m,{accessibilityLiveRegion:"polite",style:d,children:l.created.statusLabel||de.records}):jsxs(Fragment,{children:[jsx(m,{style:d,children:$.ownerName}),jsx(qe,{accessibilityLabel:$.ownerName,style:a,value:l.ownerName,maxLength:200,editable:!l.busy,autoComplete:"name",onChangeText:l.setOwnerName}),jsx(m,{style:d,children:$.clinic}),jsx(qe,{accessibilityLabel:$.clinic,style:a,value:l.query,placeholder:$.placeholder,placeholderTextColor:c.color.text.placeholder,maxLength:200,editable:!l.busy,onChangeText:l.setQuery}),u($.search,()=>{l.search();},l.busy||l.searching||l.query.trim().length<2),l.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:de.loading}),l.recent.length>0&&jsx(m,{accessibilityRole:"header",style:d,testID:"records-clinic-recent-label",children:$.recentlyUsed}),l.recent.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},`recent-${p.id}`)),l.clinics.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},p.id)),l.needsEmail&&jsxs(Fragment,{children:[jsx(m,{style:d,children:$.email}),jsx(qe,{accessibilityLabel:$.email,style:a,value:l.email,placeholder:$.emailPlaceholder,placeholderTextColor:c.color.text.placeholder,maxLength:320,editable:!l.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:l.setEmail})]}),jsx(m,{accessibilityRole:"header",style:d,children:$.scopeHeading}),l.copy?jsx(m,{style:d,children:l.query.trim()&&l.ownerName.trim()?l.scope??q("internalError").displayMessage:de.consentRequired}):!l.error&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:de.loading}),!e.onCaptureSignature&&jsx(Vr,{onChange:o,disabled:l.busy}),!s&&jsx(m,{accessibilityRole:"alert",style:d,children:$.missingSignature}),l.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:d,children:l.error.displayMessage}),!l.copy&&l.error&&u(de.retry,l.retryCopy),u(l.busy?$.sending:$.send,()=>{l.submit();},l.busy||!l.ready||!s)]}),e.onClose&&u($.cancel,e.onClose,l.busy),jsx(Me,{})]})}i(_b,"ClinicRequestBody");
4
+ export{Oi as EverfurClinicPicker,Tb as EverfurClinicRequest,Ki as EverfurClinicRequestBatch,La as EverfurRecordDetail,Ia as EverfurRecordDocument,Cb as EverfurRecords,oa as EverfurRecordsConsent,Ea as EverfurRecordsDashboard,Md as EverfurRecordsFlow,Na as EverfurRecordsRequest,qa as EverfurRecordsUpload,Br as RECORDS_CLINIC_BATCH_MAX,as as RECORDS_TERMINAL,Dn as REQUEST_TIMELINE_TITLES,Vr as SignaturePad,ca as applyFactOverlay,ga as buildRequestTimeline,Gn as currentRecordsScreen,pi as deriveRecordsDashboardState,Wn as initialRecordsNav,Eo as isFactEditable,Mr as isTerminalStatus,Xn as pickPetRecordsRequest,Yn as popRecordsNav,ni as pushRecordsNav,pr as recordsDenialReasonOf,ai as recordsNavReducer,qi as registerRnSignature,oi as replaceRecordsNav,ii as resetRecordsNav,Ro as selectClinicCall,mi as selectDashboardView,kn as selectPrimaryLabel,af as selectRequestList,ho as selectRequestTitle,Ts as transitionRecordsNav,yt as useEverfurRecords,Mt as useEverfurRecordsClinic,hi as useEverfurRecordsClinicBatch,da as useRecordFactEdit,Pa as useRecordPdfLink,Ta as useRecordShares,ta as useRecordsMarkers};