@everfur/sdk 0.1.1 → 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 (219) hide show
  1. package/CHANGELOG.md +703 -4
  2. package/README.md +63 -23
  3. package/consent/package.json +8 -0
  4. package/dist/Chat-BZZ-Py5l.d.ts +128 -0
  5. package/dist/Chat-Dq4fffIO.d.cts +128 -0
  6. package/dist/DepthViews-BG3E25MD.d.ts +16 -0
  7. package/dist/DepthViews-B_hIypI6.d.cts +19 -0
  8. package/dist/DepthViews-CL75jyRA.d.cts +16 -0
  9. package/dist/DepthViews-CkYri51q.d.ts +19 -0
  10. package/dist/ErrorPolicyPort-CNf4uQZP.d.cts +22 -0
  11. package/dist/ErrorPolicyPort-CwbfmxzJ.d.ts +22 -0
  12. package/dist/{EverfurResult-D92-uL82.d.cts → EverfurResult-DN9pL2Ab.d.cts} +11 -10
  13. package/dist/{EverfurResult-D92-uL82.d.ts → EverfurResult-DN9pL2Ab.d.ts} +11 -10
  14. package/dist/{PhotoController-BItt5M7u.d.cts → PhotoController-3l7MT9jA.d.cts} +1 -1
  15. package/dist/{PhotoController-D8zMTdcW.d.ts → PhotoController-vzY5bfY_.d.ts} +1 -1
  16. package/dist/animations/index.cjs +1 -1997
  17. package/dist/animations/index.d.cts +35 -35
  18. package/dist/animations/index.d.ts +35 -35
  19. package/dist/animations/index.js +1 -1972
  20. package/dist/attachments-BorG422I.d.cts +146 -0
  21. package/dist/attachments-BrUWQYNK.d.ts +257 -0
  22. package/dist/attachments-D_SECjr1.d.cts +257 -0
  23. package/dist/attachments-DpldrvIW.d.ts +146 -0
  24. package/dist/bookingCopy-CqtDYvCR.d.ts +732 -0
  25. package/dist/bookingCopy-SREvkG19.d.cts +732 -0
  26. package/dist/branding-CsRdeNwK.d.cts +566 -0
  27. package/dist/branding-CsRdeNwK.d.ts +566 -0
  28. package/dist/callCopy-DoQKG3-L.d.cts +40 -0
  29. package/dist/callCopy-DoQKG3-L.d.ts +40 -0
  30. package/dist/casesRepository-DwtZVsbj.d.cts +51 -0
  31. package/dist/casesRepository-v6QczS9N.d.ts +51 -0
  32. package/dist/chat/index.cjs +1 -1170
  33. package/dist/chat/index.d.cts +32 -53
  34. package/dist/chat/index.d.ts +32 -53
  35. package/dist/chat/index.js +1 -1167
  36. package/dist/client/index.cjs +9 -2315
  37. package/dist/client/index.d.cts +80 -16
  38. package/dist/client/index.d.ts +80 -16
  39. package/dist/client/index.js +9 -2215
  40. package/dist/{config-CiJ0PVBB.d.ts → config--Wu1Umhd.d.cts} +64 -26
  41. package/dist/{config-BSjBdxrZ.d.cts → config-C7eb_IMD.d.ts} +64 -26
  42. package/dist/consent/index.cjs +1 -0
  43. package/dist/consent/index.d.cts +33 -0
  44. package/dist/consent/index.d.ts +33 -0
  45. package/dist/consent/index.js +1 -0
  46. package/dist/context-CL3lyuy1.d.cts +159 -0
  47. package/dist/context-CahAEha8.d.ts +159 -0
  48. package/dist/copy-DdVFDL01.d.ts +198 -0
  49. package/dist/copy-UeUJVk8X.d.cts +198 -0
  50. package/dist/core/index.cjs +13 -3178
  51. package/dist/core/index.d.cts +164 -29
  52. package/dist/core/index.d.ts +164 -29
  53. package/dist/core/index.js +13 -3166
  54. package/dist/depth-D5HwcvKC.d.cts +533 -0
  55. package/dist/depth-DvPwPuT_.d.ts +533 -0
  56. package/dist/entitlementRepository-B7egEdW6.d.ts +43 -0
  57. package/dist/entitlementRepository-BpJ7tiwl.d.cts +43 -0
  58. package/dist/{identity-Brl-lDd6.d.cts → identity-C2-08BZW.d.cts} +20 -7
  59. package/dist/{identity-DK9zORrG.d.ts → identity-CEi9GRFZ.d.ts} +20 -7
  60. package/dist/{ids-CJ1S6adf.d.cts → ids-B2GAAifq.d.cts} +1 -1
  61. package/dist/{ids-CJ1S6adf.d.ts → ids-B2GAAifq.d.ts} +1 -1
  62. package/dist/index.cjs +12 -4494
  63. package/dist/index.d.cts +30 -121
  64. package/dist/index.d.ts +30 -121
  65. package/dist/index.js +12 -4470
  66. package/dist/models-B-Uh2LTf.d.ts +214 -0
  67. package/dist/models-D2EUxPZY.d.cts +214 -0
  68. package/dist/notifications/index.cjs +2 -0
  69. package/dist/notifications/index.d.cts +17 -0
  70. package/dist/notifications/index.d.ts +17 -0
  71. package/dist/notifications/index.js +2 -0
  72. package/dist/optionalModule-DbJmsq5f.d.cts +21 -0
  73. package/dist/optionalModule-DbJmsq5f.d.ts +21 -0
  74. package/dist/pets-DJv2sj2H.d.ts +92 -0
  75. package/dist/pets-JVCXgRgR.d.cts +92 -0
  76. package/dist/petsRepository-B_gKbAzJ.d.cts +142 -0
  77. package/dist/petsRepository-Bk6GDwLs.d.ts +142 -0
  78. package/dist/photo/index.cjs +1 -2189
  79. package/dist/photo/index.d.cts +6 -6
  80. package/dist/photo/index.d.ts +6 -6
  81. package/dist/photo/index.js +1 -2186
  82. package/dist/ports-BN6RHF9W.d.cts +48 -0
  83. package/dist/ports-BN6RHF9W.d.ts +48 -0
  84. package/dist/ports-BY2ph0_y.d.cts +376 -0
  85. package/dist/ports-D7YW8qz9.d.ts +376 -0
  86. package/dist/profile-CSs1wlXT.d.cts +93 -0
  87. package/dist/profile-CSs1wlXT.d.ts +93 -0
  88. package/dist/records/depth/index.cjs +2 -0
  89. package/dist/records/depth/index.d.cts +13 -0
  90. package/dist/records/depth/index.d.ts +13 -0
  91. package/dist/records/depth/index.js +2 -0
  92. package/dist/records/index.cjs +3 -2839
  93. package/dist/records/index.d.cts +137 -203
  94. package/dist/records/index.d.ts +137 -203
  95. package/dist/records/index.js +3 -2833
  96. package/dist/requestFunnel-BjDpqqvm.d.cts +110 -0
  97. package/dist/requestFunnel-DFMGcluw.d.ts +110 -0
  98. package/dist/{resolve-Dq_4_agU.d.ts → resolve-D4Ywz5OS.d.cts} +10 -4
  99. package/dist/{resolve-Dq_4_agU.d.cts → resolve-D4Ywz5OS.d.ts} +10 -4
  100. package/dist/{runtime-Bvr8yqXm.d.cts → runtimeTypes-gZEJu-da.d.cts} +104 -132
  101. package/dist/{runtime-BIYzf9cK.d.ts → runtimeTypes-w5KqBMcs.d.ts} +104 -132
  102. package/dist/server/events/index.cjs +2 -0
  103. package/dist/server/events/index.d.cts +550 -0
  104. package/dist/server/events/index.d.ts +550 -0
  105. package/dist/server/events/index.js +2 -0
  106. package/dist/server/index.cjs +2 -533
  107. package/dist/server/index.d.cts +73 -18
  108. package/dist/server/index.d.ts +73 -18
  109. package/dist/server/index.js +2 -530
  110. package/dist/species-BXAIMh7I.d.cts +9 -0
  111. package/dist/species-BXAIMh7I.d.ts +9 -0
  112. package/dist/televet/booking/index.cjs +1 -0
  113. package/dist/televet/booking/index.d.cts +294 -0
  114. package/dist/televet/booking/index.d.ts +294 -0
  115. package/dist/televet/booking/index.js +1 -0
  116. package/dist/televet/call/index.cjs +1 -0
  117. package/dist/televet/call/index.d.cts +141 -0
  118. package/dist/televet/call/index.d.ts +141 -0
  119. package/dist/televet/call/index.js +1 -0
  120. package/dist/televet/index.cjs +1 -0
  121. package/dist/televet/index.d.cts +142 -0
  122. package/dist/televet/index.d.ts +142 -0
  123. package/dist/televet/index.js +1 -0
  124. package/dist/testing/index.cjs +5 -823
  125. package/dist/testing/index.d.cts +18 -4
  126. package/dist/testing/index.d.ts +18 -4
  127. package/dist/testing/index.js +5 -820
  128. package/dist/testing/rn/index.cjs +1 -449
  129. package/dist/testing/rn/index.d.cts +18 -29
  130. package/dist/testing/rn/index.d.ts +18 -29
  131. package/dist/testing/rn/index.js +1 -444
  132. package/dist/testing/web/index.cjs +1 -0
  133. package/dist/testing/web/index.d.cts +132 -0
  134. package/dist/testing/web/index.d.ts +132 -0
  135. package/dist/testing/web/index.js +1 -0
  136. package/dist/timelineRows-C15jxFFH.d.ts +19 -0
  137. package/dist/timelineRows-odO8g9r2.d.cts +19 -0
  138. package/dist/typeStyle-CKqVYD6L.d.cts +111 -0
  139. package/dist/typeStyle-DmoyacDG.d.ts +111 -0
  140. package/dist/uploadTransport-D0M0T4hN.d.ts +38 -0
  141. package/dist/uploadTransport-DKJHs3Yj.d.cts +38 -0
  142. package/dist/useRecordsDepth-C6rjEaLn.d.cts +237 -0
  143. package/dist/useRecordsDepth-crhBllQK.d.ts +237 -0
  144. package/dist/useVetVisit-Bc84hWUU.d.cts +187 -0
  145. package/dist/useVetVisit-CjmMa896.d.ts +187 -0
  146. package/dist/video/index.cjs +1 -1941
  147. package/dist/video/index.d.cts +4 -4
  148. package/dist/video/index.d.ts +4 -4
  149. package/dist/video/index.js +1 -1938
  150. package/dist/view-Bxwxp4xD.d.ts +310 -0
  151. package/dist/view-DyitEO0m.d.cts +310 -0
  152. package/dist/visitIntent-D7_yVp1I.d.cts +8 -0
  153. package/dist/visitIntent-D7_yVp1I.d.ts +8 -0
  154. package/dist/web/consent/index.cjs +1 -0
  155. package/dist/web/consent/index.d.cts +34 -0
  156. package/dist/web/consent/index.d.ts +34 -0
  157. package/dist/web/consent/index.js +1 -0
  158. package/dist/web/index.cjs +14 -0
  159. package/dist/web/index.d.cts +218 -0
  160. package/dist/web/index.d.ts +218 -0
  161. package/dist/web/index.js +14 -0
  162. package/dist/web/notifications/index.cjs +2 -0
  163. package/dist/web/notifications/index.d.cts +213 -0
  164. package/dist/web/notifications/index.d.ts +213 -0
  165. package/dist/web/notifications/index.js +2 -0
  166. package/dist/web/records/depth/index.cjs +2 -0
  167. package/dist/web/records/depth/index.d.cts +12 -0
  168. package/dist/web/records/depth/index.d.ts +12 -0
  169. package/dist/web/records/depth/index.js +2 -0
  170. package/dist/web/records/index.cjs +4 -0
  171. package/dist/web/records/index.d.cts +285 -0
  172. package/dist/web/records/index.d.ts +285 -0
  173. package/dist/web/records/index.js +4 -0
  174. package/dist/web/televet/booking/index.cjs +1 -0
  175. package/dist/web/televet/booking/index.d.cts +349 -0
  176. package/dist/web/televet/booking/index.d.ts +349 -0
  177. package/dist/web/televet/booking/index.js +1 -0
  178. package/dist/web/televet/call/index.cjs +1 -0
  179. package/dist/web/televet/call/index.d.cts +142 -0
  180. package/dist/web/televet/call/index.d.ts +142 -0
  181. package/dist/web/televet/call/index.js +1 -0
  182. package/dist/web/televet/index.cjs +1 -0
  183. package/dist/web/televet/index.d.cts +136 -0
  184. package/dist/web/televet/index.d.ts +136 -0
  185. package/dist/web/televet/index.js +1 -0
  186. package/notifications/package.json +8 -0
  187. package/package.json +266 -10
  188. package/records/depth/package.json +8 -0
  189. package/server/events/device-blocked.cjs +15 -0
  190. package/server/events/package.json +9 -0
  191. package/televet/booking/package.json +8 -0
  192. package/televet/call/package.json +8 -0
  193. package/televet/package.json +8 -0
  194. package/testing/web/native-blocked.cjs +12 -0
  195. package/testing/web/package.json +8 -0
  196. package/web/consent/native-blocked.cjs +12 -0
  197. package/web/consent/package.json +8 -0
  198. package/web/native-blocked.cjs +12 -0
  199. package/web/notifications/native-blocked.cjs +12 -0
  200. package/web/notifications/package.json +8 -0
  201. package/web/package.json +8 -0
  202. package/web/records/depth/native-blocked.cjs +12 -0
  203. package/web/records/depth/package.json +8 -0
  204. package/web/records/native-blocked.cjs +12 -0
  205. package/web/records/package.json +8 -0
  206. package/web/televet/booking/native-blocked.cjs +12 -0
  207. package/web/televet/booking/package.json +8 -0
  208. package/web/televet/call/native-blocked.cjs +12 -0
  209. package/web/televet/call/package.json +8 -0
  210. package/web/televet/native-blocked.cjs +12 -0
  211. package/web/televet/package.json +8 -0
  212. package/dist/ChatController-CKdBvPj2.d.ts +0 -146
  213. package/dist/ChatController-CpUMvvZf.d.cts +0 -146
  214. package/dist/FilePort-BabWrv7I.d.cts +0 -22
  215. package/dist/FilePort-BabWrv7I.d.ts +0 -22
  216. package/dist/petsRepository-BEGb97M9.d.cts +0 -326
  217. package/dist/petsRepository-Bu18r2kK.d.ts +0 -326
  218. package/dist/requestFunnel-DuUH-kAe.d.cts +0 -28
  219. package/dist/requestFunnel-dio5OmR9.d.ts +0 -28
@@ -0,0 +1,4 @@
1
+ import {createContext,useRef,useMemo,useState,useCallback,useEffect,useReducer,useId,useContext,useSyncExternalStore,Component,createElement}from'react';import {z as z$1}from'zod';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var Vd=Object.defineProperty;var i=(e,r)=>Vd(e,"name",{value:r,configurable:true});var yo=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(yo.map(e=>e.wireCode));var Wd=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"}),da=Object.freeze(yo.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:Wd[e.wireCode]}))),Gd=new Map(da.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),Yd=Object.freeze(["http_envelope",...[...new Set(da.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function En(e,r){if(typeof e!="string")return;let t=e.trim().toUpperCase();if(t.length!==0)for(let o of [r??"http_envelope",...Yd]){let n=Gd.get(o+t);if(n)return n}}i(En,"contractErrorFor");function Kd(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(Kd,"contractDocUrl");function ca(e){return null}i(ca,"publishedDocUrl");var Qd=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 ua(e){return Qd[e]}i(ua,"categoryFor");function pa(e){let r=En(e);if(r)return r.normalized;let t=(e??"").trim().toUpperCase(),o=t.replace(/[^A-Z0-9]/g,"");if(o==="AUTHREJECTED")return "authRejected";if(t.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(pa,"fromWire");var Xd=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function go(e){return Xd.has(e)}i(go,"isAutoRetryable");var Jd=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function ma(e){return go(e)||Jd.has(e)}i(ma,"isRetryableCode");var Zd=500,bo=8e3,fa=4;function ya(e,r=Math.random){let t=Math.max(0,e),o=Math.min(Zd*2**t,bo);return Math.floor(r()*o)}i(ya,"backoffDelayMs");var ec=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 ec[e]}i(ho,"userFacingError");function ga(e,r,t){Object.defineProperty(e,r,{value:t,enumerable:false,writable:false,configurable:false});}i(ga,"defineHidden");var rc=/^[a-z][a-z0-9_]{0,63}$/;function z(e,r){let t=En(r?.wireCode,r?.wireEnvelope),o={code:e,category:ua(e),retryable:r?.retryable??ma(e),displayMessage:ho(e)};if(r?.httpStatus!==void 0&&(o.httpStatus=r.httpStatus),r?.requestId&&(o.requestId=r.requestId),typeof r?.reasonCode=="string"&&rc.test(r.reasonCode)&&(o.reasonCode=r.reasonCode),t);return r?.wireMessage&&ga(o,"wireMessage",r.wireMessage),r?.raw!==void 0&&r.raw!==null&&ga(o,"raw",r.raw),Object.freeze(o)}i(z,"makeEverfurError");function ke(e,r){return Object.freeze(r===void 0?{ok:true,value:e}:{ok:true,value:e,warning:r})}i(ke,"ok");function j(e){return Object.freeze({ok:false,error:e})}i(j,"err");var xn=class xn extends Error{constructor(r,t){super(t),this.name="EverfurConfigError",this.kind=r,Object.setPrototypeOf(this,xn.prototype);}};i(xn,"EverfurConfigError");var Zt=xn;var Ca=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),ba=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 tc(e){let r=Object.prototype.hasOwnProperty.call(ba,e)?ba[e]:void 0;if(r!==void 0)return r;let t=e;return Ca.has(t)?t:"parsing"}i(tc,"normalizeStatus");function Ea(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Ea,"normalizeOrigin");var nc=z$1.object({request_id:z$1.string().min(1),pet_ref:z$1.string().min(1),status:z$1.string(),simple_status:z$1.string().nullish(),simple_status_detail:z$1.string().nullish(),status_label:z$1.string().optional(),dispatch_status:z$1.string().nullish(),can_retry_send:z$1.boolean().optional(),can_revoke:z$1.boolean().optional(),can_convert_to_upload:z$1.boolean().optional(),can_update_clinic_email:z$1.boolean().optional(),reminder_count:z$1.number().int().nonnegative().optional(),last_reminder_at:z$1.string().nullish(),waiting_expectation:z$1.string().nullish(),document_count:z$1.number().optional(),held_item_count:z$1.number().optional(),received_at:z$1.string().nullish(),parsing_started_at:z$1.string().nullish(),review_started_at:z$1.string().nullish(),created_at:z$1.string().optional(),updated_at:z$1.string().optional(),source:z$1.string().nullish().catch(null),action_needed_label:z$1.string().nullish().catch(null),failure_reason:z$1.string().nullish().catch(null),failure_code:z$1.string().nullish().catch(null),recovery_stage:z$1.string().nullish().catch(null),show_clinic_phone:z$1.boolean().optional().catch(void 0),clinic_name:z$1.string().nullish().catch(null),clinic_email:z$1.string().nullish().catch(null),clinic_phone:z$1.string().nullish().catch(null),converted_to_upload_at:z$1.string().nullish().catch(null),request_group_id:z$1.string().nullish().catch(null)}).passthrough();function nt(e){let r=nc.safeParse(e);if(!r.success)return null;let t=r.data,o=ic(t.simple_status),n=o==="requested"&&(t.status==="awaiting_upload"||t.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":o==="parsing"&&(t.simple_status_detail==="in_review"||t.simple_status_detail==="review_email_failed")?"in_review":o??tc(t.status);return Object.freeze({id:t.request_id,petRef:t.pet_ref,status:n,simpleStatus:o,simpleStatusDetail:t.simple_status_detail??null,statusLabel:t.status_label??"",dispatchStatus:t.dispatch_status??null,canRetrySend:t.can_retry_send===true,canRevoke:t.can_revoke===true,canConvertToUpload:t.can_convert_to_upload===true,canUpdateClinicEmail:t.can_update_clinic_email===true,reminderCount:t.reminder_count??0,lastReminderAt:t.last_reminder_at??null,waitingExpectation:t.waiting_expectation??null,documentCount:Ra(t.document_count,0),heldItemCount:Ra(t.held_item_count,0),receivedAt:t.received_at??null,parsingStartedAt:t.parsing_started_at??null,reviewStartedAt:t.review_started_at??null,createdAt:t.created_at??"",updatedAt:t.updated_at??"",wireStatus:t.status,source:t.source??null,actionNeededLabel:t.action_needed_label??null,failureReason:t.failure_reason??null,failureCode:t.failure_code??null,recoveryStage:t.recovery_stage??null,showClinicPhone:t.show_clinic_phone===true,clinicName:t.clinic_name??null,clinicEmail:t.clinic_email??null,clinicPhone:t.clinic_phone??null,convertedToUploadAt:t.converted_to_upload_at??null,requestGroupId:t.request_group_id??null})}i(nt,"mapRequestView");var oc=z$1.object({request_group_id:z$1.string().min(1),pet_ref:z$1.string().min(1),total:z$1.number().int().nonnegative(),responded:z$1.number().int().nonnegative(),pending:z$1.number().int().nonnegative(),members:z$1.array(z$1.unknown())});function xa(e){let r=oc.safeParse(e);if(!r.success)return null;let t=r.data,o=Ro(t.members);return o.some(n=>n.petRef!==t.pet_ref)?null:Object.freeze({requestGroupId:t.request_group_id,petRef:t.pet_ref,total:t.total,responded:t.responded,pending:t.pending,members:o})}i(xa,"mapRequestGroup");function ic(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Ca.has(e)?e:null}i(ic,"normalizeSimpleStatus");function Ro(e){let r=Array.isArray(e)?e:[],t=[];for(let o of r){let n=nt(o);n!==null&&t.push(n);}return Object.freeze(t)}i(Ro,"mapRequestList");var ac=z$1.object({source_doc_id:z$1.string().min(1),request_id:z$1.string().min(1)});function Sa(e){let r=ac.safeParse(e);return r.success?Object.freeze({documentId:r.data.source_doc_id,requestId:r.data.request_id,status:"received"}):null}i(Sa,"mapUploadedDocument");var sc=z$1.object({label:z$1.string(),value:z$1.string()}),vo=z$1.object({key:z$1.string(),category:z$1.string().optional(),label:z$1.string().optional(),value:z$1.string().nullish(),unit:z$1.string().nullish(),observed_at:z$1.string().nullish(),status:z$1.string().nullish(),origin:z$1.string().nullish(),canonical_key:z$1.string().nullish()}),lc=z$1.object({at:z$1.string(),value:z$1.number().nullish(),display:z$1.string().nullish(),origin:z$1.string().nullish()}),dc=z$1.object({key:z$1.string(),label:z$1.string().optional(),points:z$1.array(lc).optional()}),cc=z$1.object({title:z$1.string(),detail:z$1.string().nullish(),due_at:z$1.string().nullish()}),Co=z$1.object({doc_id:z$1.string(),title:z$1.string().nullish(),page_count:z$1.number().nullish(),received_at:z$1.string().nullish()});function Eo(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:Ea(e.origin),canonicalKey:e.canonical_key??null})}i(Eo,"mapEntityRow");function xo(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(xo,"mapDocumentRow");var uc=z$1.object({identity:z$1.array(sc).optional(),entities:z$1.array(vo).optional(),entity_series:z$1.array(dc).optional(),forward_looking:z$1.array(cc).optional(),documents:z$1.array(Co).optional()});function wa(e,r){let t=mc(r)?r:{},o=va(t.schema_version,"epdf/1.0"),n=va(t.disclaimer,""),l=typeof t.pet_ref=="string"&&t.pet_ref.length>0?t.pet_ref:e;if(t.withheld===true)return ha(l,o,n);let a=uc.safeParse(t);if(!a.success)return ha(l,o,n);let d=a.data,s=(d.identity??[]).map(b=>Object.freeze({label:b.label,value:b.value})),c=(d.entities??[]).map(Eo),u=(d.entity_series??[]).map(b=>Object.freeze({key:b.key,label:b.label??b.key,points:Object.freeze((b.points??[]).map(m=>Object.freeze({at:m.at,value:m.value??null,display:m.display??null,origin:Ea(m.origin)})))})),p=(d.forward_looking??[]).map(b=>Object.freeze({title:b.title,detail:b.detail??null,dueAt:b.due_at??null})),f={};for(let b of d.documents??[])f[b.doc_id]=xo(b);let g=t.is_empty===true||s.length===0&&c.length===0&&u.length===0&&p.length===0&&Object.keys(f).length===0;return Object.freeze({petRef:l,schemaVersion:o,isEmpty:g,withheld:false,generatedAt:fc(t.generated_at),identity:Object.freeze(s),entities:Object.freeze(c),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(p),documents:Object.freeze(f),disclaimer:n})}i(wa,"mapRecordView");function ha(e,r,t){return Object.freeze({petRef:e,schemaVersion:r,isEmpty:false,withheld:true,generatedAt:null,identity:Object.freeze([]),entities:Object.freeze([]),entitySeries:Object.freeze([]),forwardLooking:Object.freeze([]),documents:Object.freeze({}),disclaimer:t})}i(ha,"withheldView");var pc=z$1.object({pet_ref:z$1.string().optional(),granted:z$1.boolean().optional(),version:z$1.string().nullish(),granted_at:z$1.string().nullish()});function Sn(e,r){let t=pc.safeParse(r),o=t.success?t.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(Sn,"mapConsent");function mc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(mc,"isObject");function Ra(e,r){return typeof e=="number"&&Number.isFinite(e)?e:r}i(Ra,"numberOr");function va(e,r){return typeof e=="string"&&e.length>0?e:r}i(va,"strOr");function fc(e){return typeof e=="string"&&e.length>0?e:null}i(fc,"strOrNull");var ka=Object.freeze(["published","failed","revoked"]);function Ot(e){return ka.includes(e)}i(Ot,"isTerminalStatus");function ot(e){if(e===null)return null;let r=e.recordsReason;return r==="consent_required"||r==="session_required"||r==="entitlement"||r==="pet_not_found"?r:null}i(ot,"recordsDenialReasonOf");var yc="records_consent_required";function gc(e){let r=e.raw;if(r===null||typeof r!="object")return null;let t=r,o=typeof t.error=="object"&&t.error!==null?t.error.code:t.code;return typeof o=="string"&&o.length>0?o:null}i(gc,"recordsWireCodeOf");function Yr(e){return e===null||e.httpStatus!==409?false:gc(e)===yc}i(Yr,"isRecordsConsentRequired");var bc=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function wn(e){return e!==bc}i(wn,"isUploadTransportAvailable");var _a=Object.freeze({record(){}}),zr=25*1024*1024,Pa=64,en=128,tr=128,it="application/pdf",Ta=9e4;function Ia(e){return new So(e)}i(Ia,"createRecordsController");var wo=class wo{constructor(r){this.recordCache=new Map;this.consentEpoch=new Map;this.reportedGaps=new Set;this.repository=r.repository,this.uploads=r.uploads,this.telemetry=r.telemetry??_a,this.newIdempotencyKey=r.newIdempotencyKey??Ec(),this.timers=r.timers??vc,this.uploadDeadlineMs=r.uploadDeadlineMs??Ta;}async createUploadRequest(r){let t=await this.repository.createRequest({pet_ref:r.petRef,idempotency_key:r.idempotencyKey});if(!t.ok)return this.onRequestError(t.error);let o=nt(t.value);return o===null?j(kn()):(this.observeRequest(o),ke(o))}async getRequest(r){let t=await this.repository.getRequest(r);if(!t.ok)return this.onRequestError(t.error);let o=nt(t.value);return o===null?j(kn()):(this.observeRequest(o),ke(o))}async listRequests(){let r=await this.repository.listRequests();if(!r.ok)return this.onRequestError(r.error);let t=Ro(r.value);for(let o of t)this.observeRequest(o);return ke(t)}async uploadDocument(r){let{requestId:t,file:o}=r,n=hc(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),j(Da(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(t,{content_type:it,file_size:o.sizeBytes});if(!l.ok)return this.onRequestError(l.error);let a=await this.postToS3(l.value,o,r);if(!a.ok)return this.telemetry.record("records.upload.failed",{reason:a.reason}),j(Da(a.reason));let d=await this.repository.completeUpload(t,{upload_id:l.value.upload_id});if(!d.ok)return d.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:Rc(d.error)??"corrupt"}),this.onRequestError(d.error);let s=Sa(d.value);return s===null?j(kn()):ke(s)}async postToS3(r,t,o){let n=new AbortController,l=Cc(n.signal,o.signal),a=this.timers.setTimeout(()=>n.abort(),this.uploadDeadlineMs);try{let d={signal:l};return o.onProgress&&(d.onProgress=o.onProgress),await this.uploads.postMultipart(r,t,d),{ok:!0}}catch{return {ok:false,reason:n.signal.aborted&&o.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(a);}}async getRecord(r){let t=this.consentEpoch.get(r)??0,o=await this.repository.getRecord(r);if(t!==(this.consentEpoch.get(r)??0))return j(Object.freeze({...z("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let l=ot(o.error);return l==="consent_required"?(this.recordCache.delete(r),this.telemetry.record("records.consent.denied",{pet_ref:r})):l==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:r}),j(o.error)}let n=wa(r,o.value);return n.petRef!==r?j(kn()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:r}),this.recordCache.delete(r),ke(n)):(this.recordCache.set(r,n),ke(n))}peekCachedRecord(r){return this.recordCache.get(r)??null}async getConsent(r){let t=await this.repository.getConsent(r);return t.ok?ke(Sn(r,t.value)):j(t.error)}async grantConsent(r){let t=await this.repository.putConsent(r.petRef,{consent_version:r.consentVersion,idempotency_key:r.idempotencyKey});return t.ok?ke(Sn(r.petRef,t.value)):(ot(t.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:r.petRef}),j(t.error))}async revokeConsent(r){let t=await this.repository.deleteConsent(r);return t.ok?(this.consentEpoch.set(r,(this.consentEpoch.get(r)??0)+1),this.recordCache.delete(r),ke(Sn(r,t.value))):j(t.error)}reportCapabilityDenied(r){this.telemetry.record("records.capability.denied",r?{pet_ref:r}:{});}observeRequest(r){r.reviewStartedAt!==null&&!this.reportedGaps.has(r.id)&&(this.reportedGaps.add(r.id),this.telemetry.record("records.parse.gap",{request_id:r.id}));}onRequestError(r){return ot(r)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),j(r)}};i(wo,"RecordsControllerImpl");var So=wo;function hc(e){if(e.mimeType!==it)return "unsupported_format";let r=e.sizeBytes;return typeof r!="number"||!Number.isFinite(r)||r<=0||r>zr?"oversize":null}i(hc,"validateFile");function Rc(e){let r=e.wireMessage;return r==="unsupported_format"||r==="oversize"||r==="corrupt"?r:null}i(Rc,"reasonFromWire");function Da(e){return z("mediaUploadFailed",{retryable:false,wireMessage:e})}i(Da,"uploadFailed");function kn(){return z("internalError",{retryable:true})}i(kn,"internal");var vc={setTimeout:i((e,r)=>setTimeout(e,r),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function Cc(e,r){if(!r)return e;let t=new AbortController;if(e.aborted||r.aborted)return t.abort(),t.signal;let o=i(()=>t.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true}),t.signal}i(Cc,"mergeSignals");function Ec(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(Ec,"defaultIdempotencyFactory");function at(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(at,"assertNever");function Oa(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(Oa,"errorFrame");function wc(e){let r={};return e.mode==="personalized"?r.authorization=`Bearer ${e.token}`:r["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(r["x-everfur-user-ref"]=e.userRef),e.sessionId&&(r["x-everfur-session-id"]=e.sessionId),r}i(wc,"authHeaders");function rn(e,r){return {...e,headers:{...kc(e.headers),...wc(r)}}}i(rn,"withAuthHeaders");function kc(e){if(!e)return {};let r={};for(let[t,o]of Object.entries(e)){let n=t.toLowerCase();n==="authorization"||n==="x-everfur-partner-key"||(r[t]=o);}return r}i(kc,"stripAuthHeaders");async function Aa(e,r){if(r.mode==="anonymous")return r.transport.request(rn(e,{mode:"anonymous",publishableKey:r.publishableKey,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));let t;try{t=await r.identity.currentToken();}catch{return j(ko())}let o=await r.transport.request(rn(e,{mode:"personalized",token:t,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));if(o.ok||o.error.httpStatus!==401)return o;let n;try{n=await r.identity.currentToken({forceRefresh:!0});}catch{return j(ko())}let l=await r.transport.request(rn(e,{mode:"personalized",token:n,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?j(ko(l.error.httpStatus)):l}i(Aa,"authedSend");function ko(e){return z("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(ko,"authRejectedError");function qa(e){return z("internalError",{retryable:true,wireMessage:_c(e)})}i(qa,"networkError");function _c(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(_c,"describeCause");var Pc=3e4,Tc=bo*2,Dc="idempotency-key",Ic=new Set(["POST","PUT","PATCH","DELETE"]),Oc=Object.freeze({onEvent(){}}),Ac=Object.freeze({setTimeout:i((e,r)=>setTimeout(e,r),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function qc(e){let r=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return r.length===0?null:`efs_${r}`.slice(0,128)}i(qc,"seededIdempotencyKey");function st(e){let r=e.observer??Oc,t=e.timers??Ac,o=e.rng??Math.random,n=e.sleep??((f,g)=>Wc(f,t,g)),l=e.maxAttempts??fa,a=e.unaryTimeoutMs??Pc,d=e.newIdempotencyKey??Kr(),s=i(f=>{try{r.onEvent(f);}catch{}},"emit");async function c(f,g,b){let m=b?.maxAttempts,C=Math.max(1,m??l),R=b?.idempotent??Ic.has(g.method),x=b?.idempotencyKey===void 0?null:qc(b.idempotencyKey),y=R?x??d():null,v=Nc(g,y),h=0;for(;;){let E=i(L=>Object.freeze({call:f,method:g.method,path:g.path,attempt:h,...y?{idempotencyKey:y}:{},...L}),"stamp");s(E({phase:"attempt"}));let T=Hc(a,t),w=Vc(T.signal,g.signal),D;try{D=await Aa({...v,signal:w.signal},e.auth);}catch(L){D=j(qa(L));}finally{w.dispose(),T.cancel();}if(D.ok)return s(E({phase:"settled",ok:true,reason:"ok"})),D;let A=D.error,O=Lc(A,h,{maxAttempts:C,rng:o,now:t.now(),aborted:g.signal?.aborted===true,...m!==void 0?{perCallMaxAttempts:m}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),$={ok:false,code:A.code,reason:O.reason,...A.httpStatus!==void 0?{httpStatus:A.httpStatus}:{},...A.requestId!==void 0?{requestId:A.requestId}:{}};if(!O.retry)return s(E({phase:"settled",...$})),j(A);if(s(E({phase:"retry",...$,delayMs:O.delayMs})),await n(O.delayMs,g.signal),g.signal?.aborted===true)return s(E({phase:"settled",...$,reason:"aborted"})),j(A);h+=1;}}i(c,"send");async function u(f){return rn(f,await jc(e.auth))}i(u,"authorize");async function*p(f,g,b){s(Object.freeze({call:f,phase:"stream.open",method:g.method,path:g.path,attempt:0}));try{yield*e.auth.transport.stream(g,b);}catch{yield Oa({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:c,authorize:u,stream:p})}i(st,"createRequestFunnel");function Nc(e,r){let t={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==Dc&&(t[o]=n);return r!==null&&(t["Idempotency-Key"]=r),{...e,headers:t}}i(Nc,"assembleHeaders");function Kr(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(Kr,"defaultIdempotencyKeyFactory");var Fc=10;function Lc(e,r,t){if(t.aborted)return {retry:false,reason:"aborted"};let o=zc(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!go(e.code))return {retry:false,reason:"terminal-code"};let n=o==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(t.policy===void 0)return false;try{return !t.policy.shouldRetry(e.code,r)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let a=i(()=>{if(t.policy===void 0)return null;let c;try{c=t.policy.maxAttempts(e.code);}catch{return null}return typeof c!="number"||!Number.isFinite(c)?null:Math.max(1,Math.min(Fc,Math.floor(c)))},"policyCeiling"),d=t.perCallMaxAttempts??a()??t.maxAttempts;if(r+1>=d)return {retry:false,reason:"attempts-exhausted"};let s=Mc(e,t.now);return s!==null?s>Tc?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:s}:{retry:true,reason:n,delayMs:ya(r,t.rng)}}i(Lc,"decideRetry");function zc(e){let r=e.code==="unknown"?pa(Bc(e.raw)):e.code;return r==="quotaExceeded"?"quota":r==="rateLimited"||e.httpStatus===429?"burst":null}i(zc,"throttleKind");function Mc(e,r){let t=$c(e.raw);if(t===null)return null;let o=t-r;return o>0?o:0}i(Mc,"retryOverrideMs");function $c(e){for(let r of Fa(e)){let t=r.resets_at,o=Uc(t);if(o!==null)return o}return null}i($c,"findResetsAt");function Fa(e){if(!Na(e))return [];let r=[e];for(let t of ["error","detail"]){let o=e[t];Na(o)&&r.push(o);}return r}i(Fa,"candidateScopes");function Uc(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 r=Date.parse(e);return Number.isFinite(r)?r:null}return null}i(Uc,"parseInstantMs");function Bc(e){for(let r of Fa(e)){let t=r.code;if(typeof t=="string"&&t.length>0)return t}return null}i(Bc,"rawWireCode");function Na(e){return typeof e=="object"&&e!==null}i(Na,"isRecord");async function jc(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(jc,"resolveDeviceAuth");function Hc(e,r){let t=new AbortController,o=r.setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>r.clearTimeout(o),"cancel")}}i(Hc,"boundedSignal");function Vc(e,r){let t=i(()=>{},"noop");if(!r)return {signal:e,dispose:t};let o=new AbortController;if(e.aborted||r.aborted)return o.abort(),{signal:o.signal,dispose:t};let n=i(()=>o.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),r.addEventListener("abort",n,{once:true}),{signal:o.signal,dispose:i(()=>{e.removeEventListener("abort",n),r.removeEventListener("abort",n);},"dispose")}}i(Vc,"mergeSignals");function Wc(e,r,t){return e<=0||t?.aborted===true?Promise.resolve():new Promise(o=>{let n=r.setTimeout(()=>{t?.removeEventListener("abort",l),o();},e),l=i(()=>{r.clearTimeout(n),o();},"onAbort");t?.addEventListener("abort",l,{once:true});})}i(Wc,"delayAbortable");function lt(e){for(let r=0;r<e.length;r+=1){let t=e.charCodeAt(r);if(t>=55296&&t<=56319){let o=e.charCodeAt(r+1);if(!(o>=56320&&o<=57343))return true;r+=1;}else if(t>=56320&&t<=57343)return true}return false}i(lt,"hasLoneSurrogate");var Qr="/widget/v1/records";function za(e){let{auth:r}=e,t=r.mode,o=e.funnel??st({auth:r,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(s,c,u)=>{let p=await o.send(s,c);return p.ok?p:j(Kc(p.error,t,u))},"send"),l=i((s,c)=>typeof c!="string"||c.length===0?z("validationFailed",{retryable:false,wireMessage:`${s} is required and must be a non-empty string`}):lt(c)?z("validationFailed",{retryable:false,wireMessage:`${s} contains an unpaired surrogate and cannot be encoded`}):null,"segmentError"),a=i((s,c,u)=>{let p=l(s,c);if(p!==null)return p;let g=[...c].length;return g>u?z("validationFailed",{retryable:false,wireMessage:`${s} is ${g} characters; the server accepts at most ${u}`}):null},"boundsError"),d=i((...s)=>s.find(c=>c!==null)??null,"firstError");return {createRequest:i(s=>{let c=d(a("idempotency_key",s.idempotency_key,en),a("pet_ref",s.pet_ref,tr));return c?Promise.resolve(j(c)):n("records.createRequest",_o(`${Qr}/requests`,s),"request")},"createRequest"),initiateUpload:i((s,c)=>{let u=l("request_id",s);return u?Promise.resolve(j(u)):n("records.initiateUpload",_o(`${Qr}/requests/${encodeURIComponent(s)}/uploads/initiate`,c),"request")},"initiateUpload"),completeUpload:i((s,c)=>{let u=l("request_id",s);return u?Promise.resolve(j(u)):n("records.completeUpload",_o(`${Qr}/requests/${encodeURIComponent(s)}/uploads/complete`,c),"request")},"completeUpload"),getRequest:i(s=>{let c=l("request_id",s);return c?Promise.resolve(j(c)):n("records.getRequest",_n(`${Qr}/requests/${encodeURIComponent(s)}`),"request")},"getRequest"),listRequests:i(async()=>{let s=await n("records.listRequests",_n(`${Qr}/requests`),"request");if(!s.ok)return s;let c=s.value;return {ok:true,value:Array.isArray(c)?c:c.items??[]}},"listRequests"),getRecord:i(s=>{let c=a("pet_ref",s,tr);return c?Promise.resolve(j(c)):n("records.getRecord",_n(`${Qr}/pets/${encodeURIComponent(s)}/record`),"content")},"getRecord"),getConsent:i(s=>{let c=a("pet_ref",s,tr);return c?Promise.resolve(j(c)):n("records.getConsent",_n(`${Qr}/pets/${encodeURIComponent(s)}/consent`),"consent")},"getConsent"),putConsent:i((s,c)=>{let u=d(a("consent_version",c.consent_version,Pa),a("idempotency_key",c.idempotency_key,en),a("pet_ref",s,tr));return u?Promise.resolve(j(u)):n("records.putConsent",Qc(`${Qr}/pets/${encodeURIComponent(s)}/consent`,c),"consent")},"putConsent"),deleteConsent:i(s=>{let c=a("pet_ref",s,tr);return c?Promise.resolve(j(c)):n("records.deleteConsent",Xc(`${Qr}/pets/${encodeURIComponent(s)}/consent`),"consent")},"deleteConsent")}}i(za,"createHttpRecordsRepository");function La(e,r){let t={...e,recordsReason:r};for(let o of ["wireMessage","raw"]){let n=Object.getOwnPropertyDescriptor(e,o);n!==void 0&&Object.defineProperty(t,o,n);}return Object.freeze(t)}i(La,"withReason");var Gc="pet_not_registered";function Yc(e){return e.httpStatus!==404?null:e.reasonCode===Gc?"pet_not_found":"entitlement"}i(Yc,"recordsErrorReasonFor");function Kc(e,r,t){let o=Yc(e);return o!==null?La(e,o):e.code!=="accessDenied"?e:La(e,r==="anonymous"?"session_required":t==="content"?"consent_required":"entitlement")}i(Kc,"tagReason");function _n(e){return {method:"GET",path:e}}i(_n,"get");function _o(e,r){return {method:"POST",path:e,body:r}}i(_o,"post");function Qc(e,r){return {method:"PUT",path:e,body:r}}i(Qc,"put");function Xc(e){return {method:"DELETE",path:e}}i(Xc,"del");var Ma=Symbol.for("@everfur/sdk#EverfurContext@v1"),$a=globalThis,Ua=$a[Ma]??($a[Ma]=createContext(null));Ua.displayName??="EverfurContext";function Z(){let e=useContext(Ua);if(e===null)throw new Zt("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(Z,"useEverfurContext");var Po=new Map,To=new Set;function Ba(e){Po.set(e,(Po.get(e)??0)+1);for(let r of [...To])r();}i(Ba,"notifyRecordsConsentWithdrawn");function tu(e){return Po.get(e)??0}i(tu,"recordsConsentEpochOf");function nu(e){return To.add(e),()=>{To.delete(e);}}i(nu,"subscribe");function Pn(e){let r=useCallback(()=>tu(e),[e]);return useSyncExternalStore(nu,r,r)}i(Pn,"useRecordsConsentEpoch");var Io={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},Ha=4e3,iu=30;function Ke(e){let{petRef:r}=e,t=useRef(e.uploadTransport);t.current=e.uploadTransport;let o=e.uploadTransport!==void 0,{runtime:n,userRef:l,scopeEpoch:a}=Z(),d=useMemo(()=>({}),[n,l,r,a,e.controller]),s=useRef(d),[c,u]=useState({scope:d,controller:e.controller??null}),p=e.controller??(c.scope===d?c.controller:null),[f,g]=useState({scope:d,value:Io}),b=f.scope===d?f.value:Io,m=useCallback(k=>{g(S=>S.scope===d?{scope:d,value:k(S.value)}:S);},[d]),C=useRef(0);useEffect(()=>(s.current=d,g({scope:d,value:Io}),()=>{s.current=null,C.current+=1;}),[d]),useEffect(()=>{if(e.controller)return;let{services:k}=n.registry,S={record:i((P,B)=>k.telemetry.track(P,B),"record")},q=n.registry.acquire("records",`${l??""}|${r}${o?"|own-upload":""}`,()=>Ia({repository:za({auth:k.authFor(l),...k.errorPolicy?{errorPolicy:k.errorPolicy}:{}}),uploads:o?{postMultipart:i((P,B,se)=>(t.current??k.uploadTransport).postMultipart(P,B,se),"postMultipart")}:k.uploadTransport,telemetry:S}),()=>{});return u({scope:d,controller:q}),()=>{n.registry.release(q);}},[n,l,r,e.controller,a,d,o]);let R=useCallback(k=>{m(S=>({...S,...k}));},[m]),x=useCallback(async()=>{if(!p||s.current!==d)return;let k=C.current+=1;E.current=0,D(),R({loading:true,error:null,denialReason:null,withheld:false});let[S,q]=await Promise.all([p.getConsent(r),p.listRequests()]);if(k!==C.current)return;let P=S.ok?S.value:null,B=q.ok?q.value.filter(Pe=>Pe.petRef===r):[],se=q.ok?null:q.error;if(P&&P.granted){let Pe=await p.getRecord(r);if(k!==C.current)return;if(Pe.ok){R({consent:P,requests:B,record:Pe.value,withheld:Pe.value.withheld,error:Pe.value.withheld?cu():se,denialReason:null,loading:false});return}R({consent:P,requests:B,record:null,error:Pe.error,denialReason:ot(Pe.error),withheld:false,loading:false});return}R({consent:P,requests:B,record:null,error:S.ok?se:S.error,denialReason:P?"consent_required":du(S),withheld:false,loading:false});},[p,r,R,d]);useEffect(()=>(x(),()=>{C.current+=1;}),[x]);let y=useMemo(()=>lu(b.requests),[b.requests]),v=y?.id??null,h=y?.status??null,E=useRef(0),T=useRef(null),[w,D]=useReducer(k=>k+1,0);useEffect(()=>{if(!p||v===null||h===null||Ot(h)||h==="in_review")return;T.current!==String(v)&&(T.current=String(v),E.current=0);let k=false,S=i(async()=>{if(k||E.current>=iu)return;E.current+=1;let P=await p.getRequest(v);if(!k){if(P.ok&&P.value.petRef===r){if(m(B=>({...B,requests:Dn(B.requests,P.value)})),Ot(P.value.status)){P.value.status==="published"&&x();return}if(P.value.status==="in_review")return}q=setTimeout(()=>{S();},Ha);}},"tick"),q=setTimeout(()=>{S();},Ha);return ()=>{k=true,clearTimeout(q);}},[p,v,h,x,w,r,m]);let A=useCallback(async k=>{if(!p||s.current!==d)return In();let S=await p.createUploadRequest({petRef:r,idempotencyKey:k});return s.current===d&&S.ok&&S.value.petRef===r&&m(q=>({...q,requests:Dn(q.requests,S.value)})),S},[p,r,d,m]),O=useCallback((k,S)=>{m(q=>({...q,uploadQueue:q.uploadQueue.map(P=>P.key===k?S(P):P)}));},[m]),$=useCallback(async(k,S)=>{let q=Date.now().toString(36),P=S.map((se,Pe)=>{let te=au(se);return {key:`${q}-${Pe}`,name:se.name??null,status:te===null?"queued":"skipped",progress:0,skipReason:te,error:null}}),B=[...P];if(!p||s.current!==d)return Object.freeze(B);m(se=>({...se,uploadQueue:P,isUploading:true,uploadProgress:0}));for(let[se,Pe]of S.entries()){let te=P[se];if(te.status==="skipped")continue;if(s.current!==d)break;O(te.key,Ve=>({...Ve,status:"uploading",progress:0})),R({uploadProgress:0});let ve=await p.uploadDocument({requestId:k,file:Pe,onProgress:i(Ve=>{if(s.current!==d)return;let xr=Math.min(1,Math.max(0,Ve));O(te.key,Sr=>({...Sr,progress:Math.max(Sr.progress,xr)})),R({uploadProgress:xr});},"onProgress")});if(s.current!==d)break;let or=ve.ok?{...te,status:"done",progress:1}:{...te,status:"failed",error:ve.error};if(B[se]=or,O(te.key,()=>or),ve.ok){let Ve=await p.getRequest(k);s.current===d&&Ve.ok&&Ve.value.petRef===r&&m(xr=>({...xr,requests:Dn(xr.requests,Ve.value)}));}}return s.current===d&&R({isUploading:false,uploadProgress:null}),Object.freeze(B)},[p,R,O,r,d,m]),L=useCallback(async(k,S)=>{if(!p||s.current!==d)return In();let q=`${Date.now().toString(36)}-0`;m(B=>({...B,isUploading:true,uploadProgress:0,uploadQueue:[{key:q,name:S.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let P=await p.uploadDocument({requestId:k,file:S,onProgress:i(B=>{s.current===d&&(R({uploadProgress:B}),O(q,se=>({...se,progress:Math.max(se.progress,Math.min(1,B))})));},"onProgress")});if(s.current!==d)return P;if(R({isUploading:false,uploadProgress:null}),O(q,B=>P.ok?{...B,status:"done",progress:1}:{...B,status:"failed",error:P.error}),P.ok){let B=await p.getRequest(k);s.current===d&&B.ok&&B.value.petRef===r&&m(se=>({...se,requests:Dn(se.requests,B.value)}));}return P},[p,R,O,r,d,m]),V=useCallback(async(k,S)=>{if(!p||s.current!==d)return In();let q=await p.grantConsent({petRef:r,consentVersion:k,idempotencyKey:S});return q.ok&&s.current===d&&x(),q},[p,r,x,d]),J=useCallback(async()=>{if(!p||s.current!==d)return In();let k=await p.revokeConsent(r);return k.ok&&Ba(r),k.ok&&s.current===d&&(C.current+=1,R({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:k.value})),k},[p,r,R,d]),Ce=useCallback(()=>{x();},[x]),re=su(b,p!==null);return useMemo(()=>({status:re,record:b.record,requests:b.requests,activeRequest:y,consent:b.consent,error:b.error,denialReason:b.denialReason,withheld:b.withheld,isUploading:b.isUploading,uploadProgress:b.uploadProgress,uploadQueue:b.uploadQueue,createRequest:A,uploadDocument:L,uploadDocuments:$,grantConsent:V,revokeConsent:J,refresh:Ce}),[re,b,y,A,L,$,V,J,Ce])}i(Ke,"useEverfurRecords");function au(e){if(e.mimeType!==it)return "unsupported";let r=e.sizeBytes;return typeof r!="number"||!Number.isFinite(r)||r<=0||r>zr?"too_large":null}i(au,"skipReasonFor");function su(e,r){return e.loading||!r?"loading":e.withheld||e.denialReason!==null||e.error!==null?"error":e.record!==null&&!e.record.isEmpty||e.requests.length>0?"populated":"empty"}i(su,"selectStatus");function lu(e){if(e.length===0)return null;let r=e[0];for(let t of e)t.updatedAt>r.updatedAt&&(r=t);return r}i(lu,"newestRequest");function Dn(e,r){let t=e.filter(o=>o.id!==r.id);return [r,...t]}i(Dn,"replaceRequest");function du(e){return e.ok?"consent_required":ot(e.error)??"consent_required"}i(du,"consentDenial");function cu(){return z("internalError",{retryable:false})}i(cu,"withheldSentinel");function In(){return {ok:false,error:z("internalError",{retryable:true})}}i(In,"notReady");function Oo(e){let r=globalThis.console;try{r?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(Oo,"reportHostFailure");function uu(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(uu,"isThenable");function pu(e,...r){if(typeof e=="function")try{let t=e(...r);return uu(t)&&Promise.resolve(t).then(void 0,Oo),t}catch(t){Oo(t);return}}i(pu,"callHost");var Va=new WeakMap;function nn(e){if(typeof e!="function")return;let r=Va.get(e);if(r!==void 0)return r;let t=i((...o)=>{pu(e,...o);},"guarded");return Va.set(e,t),t}i(nn,"guardHost");function Te(e,r){let t=null;for(let o of r){let n=e[o];typeof n=="function"&&(t??={...e},t[o]=nn(n));}return t??e}i(Te,"guardHostProps");function on(e,...r){let t;try{t=e(...r);}catch(o){return Oo(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(t).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(on,"callHostAsync");var Wa=Object.freeze({name:"dashboard"});function On(e=Wa){return Object.freeze({stack:Object.freeze([e])})}i(On,"initialRecordsNav");function An(e){return e.stack[e.stack.length-1]??Wa}i(An,"currentRecordsScreen");function Ao(e,r){return Object.freeze({stack:Object.freeze([...e.stack,r])})}i(Ao,"pushRecordsNav");function qo(e,r){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),r])})}i(qo,"replaceRecordsNav");function No(e){return On(e)}i(No,"resetRecordsNav");function qn(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(qn,"popRecordsNav");function Ga(e,r){return r.name==="dashboard"?No(r):An(e).name==="upload"&&r.name==="request"?qo(e,r):Ao(e,r)}i(Ga,"transitionRecordsNav");function Fo(e,r){switch(r.type){case "push":return Ao(e,r.screen);case "pop":return qn(e).state;case "replace":return qo(e,r.screen);case "reset":return No(r.screen);case "navigate":return Ga(e,r.screen);default:return e}}i(Fo,"recordsNavReducer");var K=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"}),Ya=100;var xe=Object.freeze({title:K.title,placeholder:K.placeholder,searchA11y:K.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:K.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 Ka(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(Ka,"clinicEmailStatusBadge");function Qa(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(Qa,"formatClinicDistanceLabel");function Xa(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(Xa,"formatClinicDistanceForA11y");var Ja=300,Lo=2;var W=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 Za(e){return !Ot(e.status)}i(Za,"isRecordsInProgress");function Nn(e,r){if(r===null)return null;let t=e.filter(l=>l.petRef===r);if(t.length===0)return null;let o=t.find(l=>l.status==="published");return o!==void 0?o:t.filter(Za).sort((l,a)=>a.updatedAt.localeCompare(l.updatedAt))[0]??null}i(Nn,"pickPetRecordsRequest");function zo(e){if(e.hasMarkers)return "published";let r=Nn(e.requests,e.petRef);return r===null?"none":r.status==="published"||Za(r)?"in_progress":"none"}i(zo,"deriveRecordsDashboardState");function mu(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(mu,"selectDashboardLoading");function Mo(e){return mu(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(Mo,"selectDashboardView");function Ze(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(Ze,"recordsEmptyVariantForError");var ce=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 fu(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(fu,"fallbackFailureTitle");function es(e){let r=e.failureReason?.trim()??"";return r.length>0?r:fu(e)}i(es,"failureTitle");var yu=1440*60*1e3;function $o(e,r){if(!e.createdAt)return 0;let t=Date.parse(e.createdAt);if(Number.isNaN(t))return 0;let o=r-t;return o<=0?0:Math.floor(o/yu)}i($o,"requestElapsedDays");var gu=7;function rs(e,r){return e.wireStatus!=="awaiting_response"?false:$o(e,r)>=gu}i(rs,"requestWaitingTooLong");function Uo(e){return e.status==="failed"}i(Uo,"isTerminalFailure");function ts(e){return Uo(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(ts,"shouldOfferRecovery");function is(e,r){let[t,o]=useState(""),[n,l]=useState(""),[a,d]=useState([]),[s,c]=useState(null),[u,p]=useState([]),[f,g]=useState(true),[b,m]=useState(false),[C,R]=useState(false),[x,y]=useState(null),[v,h]=useState(null),[E,T]=useState(0),w=useRef(0),D=useRef(true),A=r?.latitude,O=r?.longitude,$=useMemo(()=>A!==void 0&&O!==void 0?{latitude:A,longitude:O}:void 0,[A,O]);useEffect(()=>(D.current=true,()=>{D.current=false,w.current+=1;}),[e]),useEffect(()=>{let re=true;return g(true),e.recentClinics({limit:5}).then(k=>{re&&(k.ok&&p(k.value.clinics),g(false));}).catch(()=>{re&&g(false);}),()=>{re=false;}},[e]),useEffect(()=>{let re=t.trim();if(re.length<Lo){l("");return}let k=setTimeout(()=>l(re),Ja);return ()=>clearTimeout(k)},[t]);let L=n.length>=Lo;useEffect(()=>{let re=w.current+=1;if(d([]),c(null),y(null),h(null),!L){m(false);return}m(true),e.searchClinics({query:n,limit:25,...$?{location:$}:{}}).then(k=>{!D.current||re!==w.current||(k.ok?(d(k.value.clinics),c(k.value.nextCursor)):y(k.error),m(false));}).catch(()=>{D.current&&re===w.current&&m(false);});},[e,n,L,$,E]);let V=useCallback(()=>{if(!L||s===null||C)return;let re=w.current;R(true),h(null),e.searchClinics({query:n,limit:25,cursor:s,...$?{location:$}:{}}).then(k=>{!D.current||re!==w.current||(k.ok?(d(S=>[...S,...k.value.clinics]),c(k.value.nextCursor)):h(k.error),R(false));}).catch(()=>{D.current&&re===w.current&&R(false);});},[e,s,n,L,C,$]),J=useCallback(re=>o(re),[]),Ce=useCallback(()=>T(re=>re+1),[]);return useMemo(()=>({query:t,debouncedQuery:n,isSearchActive:L,clinics:a,recent:u,recentLoading:f,initialLoading:b,loadingMore:C,hasNextPage:s!==null,error:x,pageError:v,setQuery:J,loadMore:V,retry:Ce}),[t,n,L,a,u,f,b,C,s,x,v,J,V,Ce])}i(is,"useClinicPicker");function jo(e,r,t,o){return Object.freeze({key:e?.id??`free:${r??""}`,clinic:e,freeText:r,email:t,idempotencyKey:o})}i(jo,"clinicDraftFor");var At=10,Ln=z$1.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),an=i((e,r=1)=>z$1.string().refine(t=>!lt(t)&&[...t].length>=r&&[...t].length<=e),"text"),ss=i(e=>[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127),"hasControl"),bu=z$1.object({clinicId:Ln.optional(),clinicFreeText:an(200).refine(e=>e.trim().length>0).optional(),clinicEmail:an(320,3).refine(e=>!ss(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:Ln.optional(),signaturePngBase64:z$1.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z$1.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)),hu=z$1.object({petRef:an(128),ownerName:an(200).refine(e=>e.trim().length>0&&!ss(e)),authorizationVersion:an(64),clinics:z$1.array(bu).min(1).max(At)}).strict(),Ru=z$1.object({request_group_id:Ln,pet_ref:z$1.string(),created_count:z$1.number().int().nonnegative(),failed_count:z$1.number().int().nonnegative(),results:z$1.array(z$1.object({idempotency_key:z$1.string(),clinic_id:Ln.nullable().optional(),clinic_free_text:z$1.string().nullable().optional(),created:z$1.boolean(),request:z$1.unknown().optional(),failure_code:z$1.string().nullable().optional(),failure_reason:z$1.string().nullable().optional()}))});function ls(e){let r=e.funnel??st({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(t){if(!hu.safeParse(t).success)return j(z("validationFailed",{retryable:false}));let o=await r.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:t.petRef,owner_name:t.ownerName,authorization_version:t.authorizationVersion,clinics:t.clinics.map(a=>({...a.clinicId!==void 0?{clinic_id:a.clinicId}:{clinic_free_text:a.clinicFreeText},...a.clinicEmail!==void 0?{clinic_email:a.clinicEmail}:{},...a.signatureId!==void 0?{signature_id:a.signatureId}:{signature_png_base64:a.signaturePngBase64},idempotency_key:a.idempotencyKey}))}});if(!o.ok)return o;let n=Ru.safeParse(o.value);if(!n.success||n.data.pet_ref!==t.petRef)return as();let l=[];for(let a of n.data.results){let d=a.request===void 0||a.request===null?null:nt(a.request);if(a.created!==(d!==null))return as();l.push(Object.freeze({idempotencyKey:a.idempotency_key,clinicId:a.clinic_id??null,clinicFreeText:a.clinic_free_text??null,created:a.created,request:d,failureCode:a.failure_code??null,failureReason:a.failure_reason??null}));}return ke(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(ls,"createRecordsClinicBatchClient");function as(){return j(z("internalError",{retryable:false}))}i(as,"malformed");var ds=z$1.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),vu=z$1.object({clinics:z$1.array(z$1.object({clinic_id:ds,name:z$1.string().min(1),address:z$1.string().nullable(),phone:z$1.string().nullable(),email_status:z$1.string(),distance_km:z$1.number().finite().nonnegative().nullable()})),next_cursor:z$1.string().nullable().optional()}),Cu=z$1.object({authorization_version:z$1.string().min(1),scope_template:z$1.string().min(1),authorization_template:z$1.string().min(1)}),Eu=z$1.object({upload_id:z$1.string().min(1),upload_url:z$1.string().url().refine(e=>e.startsWith("https://")),upload_fields:z$1.record(z$1.string())});function cs(e){let{repository:r}=e,t=i(async n=>{let l=await n;if(!l.ok)return l;let a=nt(l.value);return a===null?ht():ke(a)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let a=vu.safeParse(l.value);return a.success?ke(Object.freeze({clinics:Object.freeze(a.data.clinics.map(d=>Object.freeze({id:d.clinic_id,name:d.name,address:d.address,phone:d.phone,emailStatus:d.email_status,distanceKm:d.distance_km}))),nextCursor:a.data.next_cursor??null})):ht()},"page");return {searchClinics:i((n={})=>o(r.searchClinics(n)),"searchClinics"),recentClinics:i((n={})=>o(r.recentClinics(n)),"recentClinics"),async getRequestGroup(n){let l=await r.getRequestGroup(n);if(!l.ok)return l;let a=xa(l.value);return a===null?ht():ke(a)},async getAuthorizationCopy(){let n=await r.getAuthorizationCopy();if(!n.ok)return n;let l=Cu.safeParse(n.value);return l.success?ke(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):ht()},async createClinicRequest(n){let l=await t(r.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?ht():l},retryRequest:i(n=>t(r.retryRequest(n)),"retryRequest"),revokeRequest:i(n=>t(r.revokeRequest(n)),"revokeRequest"),updateClinicEmail:i((n,l)=>t(r.updateClinicEmail(n,l)),"updateClinicEmail"),convertToUpload:i(n=>t(r.convertToUpload(n)),"convertToUpload"),async initiateSignatureUpload(n){let l=await r.initiateSignatureUpload(n);if(!l.ok)return l;let a=Eu.safeParse(l.value);return a.success?ke(Object.freeze({uploadId:a.data.upload_id,uploadUrl:a.data.upload_url,uploadFields:Object.freeze(a.data.upload_fields)})):ht()},async completeSignatureUpload(n){let l=await r.completeSignatureUpload(n);if(!l.ok)return l;let a=z$1.object({signature_id:ds}).safeParse(l.value);return a.success?ke(a.data.signature_id):ht()}}}i(cs,"createRecordsClinicController");function ht(){return j(z("internalError",{retryable:false}))}i(ht,"malformed");var dt="/widget/v1/records",us=z$1.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),ut=i((e,r=1)=>z$1.string().refine(t=>!lt(t)&&[...t].length>=r&&[...t].length<=e),"text"),ms=i(e=>[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127),"hasControl"),fs=ut(320,3).refine(e=>!ms(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),ps=ut(64),xu=z$1.object({limit:z$1.number().int().min(1).max(25).optional()}).strict(),Su=z$1.object({query:ut(200,0).optional(),location:z$1.object({latitude:z$1.number().finite().min(-90).max(90),longitude:z$1.number().finite().min(-180).max(180)}).strict().optional(),limit:z$1.number().int().min(1).max(100).optional(),cursor:ut(512,0).optional()}).strict(),wu=z$1.object({petRef:ut(128),ownerName:ut(200).refine(e=>e.trim().length>0&&!ms(e)),authorizationVersion:ut(64),clinicId:us.optional(),clinicFreeText:ut(200).refine(e=>e.trim().length>0).optional(),clinicEmail:fs.optional(),signatureId:us.optional(),signaturePngBase64:z$1.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z$1.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 ys(e){let r=e.funnel??st({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),t=i((n,l,a=false)=>r.send(`records.clinic.${n}`,l,l.method==="GET"||a?void 0:{idempotent:false,maxAttempts:1}),"send"),o=i((n,l,a)=>ps.safeParse(n).success?t(l,{method:"POST",path:`${dt}/requests/${encodeURIComponent(n)}/${l}`,...a?{body:a}:{}}):ct(),"recover");return {searchClinics(n){return Su.safeParse(n).success?t("search",{method:"GET",path:`${dt}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):ct()},recentClinics(n){return xu.safeParse(n).success?t("recent",{method:"GET",path:`${dt}/clinics/recent`,query:{limit:n.limit}}):ct()},getRequestGroup(n){return ps.safeParse(n).success?t("requestGroup",{method:"GET",path:`${dt}/request-groups/${encodeURIComponent(n)}`}):ct()},getAuthorizationCopy:i(()=>t("authorizationCopy",{method:"GET",path:`${dt}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return wu.safeParse(n).success?t("create",{method:"POST",path:`${dt}/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):ct()},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 fs.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):ct()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?ct():t("signatureInitiate",{method:"POST",path:`${dt}/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)?t("signatureComplete",{method:"POST",path:`${dt}/signatures/complete`,body:{upload_id:n}}):ct()}}}i(ys,"createHttpRecordsClinicRepository");function ct(){return Promise.resolve(j(z("validationFailed",{retryable:false})))}i(ct,"invalid");function _r(){let{runtime:e,userRef:r,scopeEpoch:t}=Z(),o=useMemo(()=>{let{services:l}=e.registry;return cs({repository:ys({auth:l.authFor(r),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})})},[e,r,t]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>{let l=i(async a=>{if(r===null||n.current!==o)return j(z("accessDenied"));let d=await a();return n.current===o?d:j(z("accessDenied"))},"run");return {searchClinics:i(a=>l(()=>o.searchClinics(a)),"searchClinics"),recentClinics:i(a=>l(()=>o.recentClinics(a)),"recentClinics"),getRequestGroup:i(a=>l(()=>o.getRequestGroup(a)),"getRequestGroup"),getAuthorizationCopy:i(()=>l(()=>o.getAuthorizationCopy()),"getAuthorizationCopy"),createClinicRequest:i(a=>l(()=>o.createClinicRequest(a)),"createClinicRequest"),retryRequest:i(a=>l(()=>o.retryRequest(a)),"retryRequest"),revokeRequest:i(a=>l(()=>o.revokeRequest(a)),"revokeRequest"),updateClinicEmail:i((a,d)=>l(()=>o.updateClinicEmail(a,d)),"updateClinicEmail"),convertToUpload:i(a=>l(()=>o.convertToUpload(a)),"convertToUpload"),initiateSignatureUpload:i(a=>l(()=>o.initiateSignatureUpload(a)),"initiateSignatureUpload"),completeSignatureUpload:i(a=>l(()=>o.completeSignatureUpload(a)),"completeSignatureUpload")}},[o,r])}i(_r,"useEverfurRecordsClinic");function Ho(){let{runtime:e,userRef:r,scopeEpoch:t}=Z(),o=useMemo(()=>{let{services:l}=e.registry;return ls({auth:l.authFor(r),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})},[e,r,t]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>({async createClinicRequestBatch(l){if(r===null||n.current!==o)return j(z("accessDenied"));let a=await o.createClinicRequestBatch(l);return n.current===o?a:j(z("accessDenied"))}}),[o,r])}i(Ho,"useEverfurRecordsClinicBatch");var Go=class Go extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(t,o){return Object.is(t.resetKey,o.key)?null:{failed:false,key:t.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(Go,"HostRenderBoundary");var Vo=Go;function _u({render:e}){return e()}i(_u,"RenderHost");function Wo({render:e,fallback:r,resetKey:t}){return createElement(Vo,{fallback:r,resetKey:t,children:createElement(_u,{render:e})})}i(Wo,"HostRender");function Qo(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let r of Object.keys(e))Qo(e[r]);}return e}i(Qo,"deepFreeze");var Pu=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),vs={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Cs={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Rs={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Tu={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Du={regular:"400",medium:"500",bold:"700"},Iu={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Ou=0,Mn="System",$n="monospace",Au=["content","heading","control","compact","badge"];function qu(e){let r={};for(let t of Au)r[t]=e;return r}i(qu,"authoredTierSizes");function Es(){return {family:Mn,mono:$n,fontUrl:null,families:{regular:Mn,medium:Mn,bold:Mn,mono:$n,monoMedium:$n,monoBold:$n},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Rs,tierSizes:qu(Rs),lineHeight:Tu,weight:Du,letterSpacing:Iu,scale:1,maxScale:Ou,scaleCaps:Pu}}i(Es,"baseType");var xs={},Yo=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function Ko(e){return `cubic-bezier(${e.join(", ")})`}i(Ko,"cssCubicBezier");var Ss={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:Ko(Yo.standard),emphasized:Ko(Yo.emphasized),exit:Ko(Yo.exit)},reducedMotion:false},Nu={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)"},ws=Qo({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Nu,space:vs,radius:Cs,type:Es(),motion:Ss,slots:xs}),Fu={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)"};Qo({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Fu,space:vs,radius:Cs,type:Es(),motion:Ss,slots:xs});var ks=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),_s=globalThis,Xo=_s[ks]??(_s[ks]=createContext(ws));Xo.displayName??="EverfurThemeContext";function ue(){return useContext(Xo)}i(ue,"useEverfurTheme");var Ps=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var Ts='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',Mu="System";function $u(e){let r=e.trim();return r.length===0||r===Mu?Ts:`${Ds(r)}, ${Ts}`}i($u,"cssFontFamily");function Uu(e){let r=e.trim();return r.length===0||r==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${Ds(r)}, ui-monospace, Menlo, Consolas, monospace`}i(Uu,"cssMonoFamily");function Ds(e){return `"${e.replace(/[\\"]/g,"\\$&")}"`}i(Ds,"quote");function I(e,r){let t=e.type,o=t.families[r];return {fontFamily:r==="mono"||r==="monoMedium"||r==="monoBold"?Uu(o):$u(o),fontWeight:t.namedFaces[r]?t.weight.regular:t.weight[Ps[r]]}}i(I,"faceCss");var Bu=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 ju(e){return Bu[e]}i(ju,"requires");function Is(e,r,t){let o=ju(e),n=new Map;for(let d of r)n.set(d.resource,d);if(t?.isPending===true&&o.some(d=>!n.has(d)))return Jo({name:e,enabled:false,isPending:true,limits:{}});let l=Hu(o,n);return o.filter(d=>n.get(d)?.granted!==true).length===0?Jo({name:e,enabled:true,isPending:false,limits:l}):Jo({name:e,enabled:false,isPending:false,limits:l,disabled:Vu(o,n)})}i(Is,"decideCapability");function Hu(e,r){let t={};for(let o of e){let n=r.get(o)?.limits;if(n)for(let[l,a]of Object.entries(n)){let d=t[l];t[l]=d===void 0?a:Math.min(d,a);}}return t}i(Hu,"mergeLimits");function Vu(e,r){for(let t of e){let o=r.get(t)?.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(Vu,"disabledFor");function Jo(e){let r={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(r.disabled=e.disabled),Object.freeze(r)}i(Jo,"freezeDecision");function Zo(e){let{runtime:r}=Z(),t=r.entitlements,o=useSyncExternalStore(t.subscribe,t.getSnapshot,t.getSnapshot);return useMemo(()=>Is(e,o.decisions,{isPending:o.isPending}),[e,o])}i(Zo,"useCapability");var Yu=48;function Ku(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Ku,"selectView");function De(e){let{capability:r,children:t,renderDisabled:o,renderPending:n,style:l,className:a}=e,d=Zo(r),s=useMemo(()=>Ku(d),[d]);switch(s){case "enabled":return t;case "pending":return n?jsx(Wo,{render:n,fallback:jsx(Os,{capability:r,style:l,className:a})}):jsx(Os,{capability:r,style:l,className:a});case "disabled":return o?jsx(Wo,{render:()=>o(d),fallback:jsx(As,{decision:d,style:l,className:a}),resetKey:d}):jsx(As,{decision:d,style:l,className:a});default:return at(s)}}i(De,"CapabilityGate");function Os({capability:e,style:r,className:t}){let o=ue(),n=useMemo(()=>qs(o),[o]);return jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${e}`,className:t,style:{...n.offstate,...r},children:jsx("div",{style:n.skeletonBar})})}i(Os,"PendingSkeleton");function As({decision:e,style:r,className:t}){let o=ue(),n=useMemo(()=>qs(o),[o]),l=e.disabled?.reason??"";return jsx("div",{className:t,style:{...n.offstate,...r},children:l.length>0?jsx("p",{style:n.offstateText,children:l}):null})}i(As,"OffState");function qs(e){let{color:r,space:t,radius:o,type:n}=e;return {offstate:{boxSizing:"border-box",minHeight:Yu,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${t.md}px ${t.lg}px`,backgroundColor:r.surfaceCream,borderRadius:o.md,border:`1px solid ${r.brandBorder}`},offstateText:{margin:0,...I(e,"regular"),fontSize:n.size.body,lineHeight:`${Math.round(n.size.body*n.lineHeight.normal)}px`,color:r.text.muted},skeletonBar:{height:t.md,borderRadius:o.xs,backgroundColor:r.brandSofter}}}i(qs,"makeStyles");var ri=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 Ie(e){let r=ue(),t=useMemo(()=>Xu(r),[r]);return jsxs("div",{role:"note",className:e.className,style:{...t.container,...e.style},children:[jsx("p",{style:t.title,children:ri.title}),jsx("p",{style:t.body,children:ri.body})]})}i(Ie,"ClinicalDisclaimer");function Xu(e){let{color:r,space:t,type:o}=e,n=`${Math.round(o.size.caption*o.lineHeight.snug)}px`;return {container:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.xs,padding:`${t.md}px ${t.lg}px`,borderTop:`1px solid ${r.borderHairlineGreen}`,backgroundColor:r.surfaceCream},title:{margin:0,...I(e,"bold"),fontSize:o.size.caption,lineHeight:n,color:r.text.secondary,letterSpacing:o.letterSpacing.eyebrow},body:{margin:0,...I(e,"regular"),fontSize:o.size.caption,lineHeight:n,color:r.text.muted}}}i(Xu,"makeStyles");var Zu=120,ep=44;function rp({reason:e,onExit:r,exitLabel:t,style:o,className:n}){let{color:l,space:a,radius:d,type:s}=ue();return jsxs("div",{className:n,"data-testid":"records-gate-off",style:{boxSizing:"border-box",minHeight:Zu,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"flex-start",gap:a.md,padding:a.lg,borderRadius:d.md,border:`1px solid ${l.brandBorder}`,backgroundColor:l.surfaceCream,color:l.text.primary,...o},children:[e.length>0?jsx("p",{style:{margin:0,fontSize:s.size.bodyTight,color:l.text.muted},children:e}):null,jsx("button",{type:"button",onClick:r,"data-testid":"records-gate-off-exit",style:{minHeight:ep,padding:`0 ${a.lg}px`,borderRadius:d.pill,border:`1.5px solid ${l.brand}`,backgroundColor:"transparent",color:l.brand,font:"inherit",fontSize:s.size.body,cursor:"pointer"},children:t})]})}i(rp,"RecordsGateOffState");function Oe(e,r){return e===void 0?{}:{renderDisabled:i(t=>jsx(rp,{reason:t.disabled?.reason??"",onExit:e,exitLabel:r}),"renderDisabled")}}i(Oe,"recordsGateExit");function np(e,r){if(e===void 0)return {};let t={};return e.backgroundColor!==void 0&&(t.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(t.borderColor=e.borderColor,t.borderWidth=r??1),e.borderRadius!==void 0&&(t.borderRadius=e.borderRadius),t}i(np,"slotBox");function Ur(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Ur,"slotText");function Pr(e,r){let t=np(e,r),o={};return t.backgroundColor!==void 0&&(o.backgroundColor=t.backgroundColor),t.borderColor!==void 0&&(o.border=`${t.borderWidth??1}px solid ${t.borderColor}`),t.borderRadius!==void 0&&(o.borderRadius=t.borderRadius),o}i(Pr,"slotBoxCss");var op="your pet";function we(e){let r=e?.trim()??"";return r.length>0?r:op}i(we,"petNameOr");var ar=Object.freeze({title:"Health records",openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${we(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")}),hr=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,r,t,o)=>`Marker summary: ${e} ${e===1?"marker":"markers"}, ${r} in range, ${t} out of range${o>0?`, ${o} without a range`:""}.`,"a11y")}),ni=Object.freeze({counter:i((e,r)=>`${e+1} of ${r}`,"counter"),a11y:i((e,r,t)=>e!==null?`${e}, marker ${r+1} of ${t}. Swipe left or right to see more markers.`:`Marker ${r+1} of ${t}`,"a11y")}),Xr=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,r,t)=>`Latest reading ${e}, ${r}, collected ${t}`,"latestA11y"),readingsA11y:i(e=>`${e} readings, oldest to newest`,"readingsA11y")}),sr=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"}),qt=Object.freeze({title:i(e=>`${we(e)}\u2019s records request`,"title"),body:i(e=>`We\u2019re requesting ${we(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 ${we(e)}.`,"a11y"),openA11y:i((e,r)=>`Open ${we(e)}\u2019s records request. ${r}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),Rt=Object.freeze({title:i(e=>`Add ${we(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 ${we(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${we(e)}\u2019s records`,"uploadDocumentA11y")});var ap=120,sn=44,$e="Back";function G(){let e=ue(),r=useMemo(()=>sp(e),[e]);return {theme:e,styles:r}}i(G,"useScreenStyles");function We({title:e,onBack:r,right:t,testID:o,variant:n="brand"}){let{styles:l}=G();return jsxs("header",{style:l.headerRow,"data-testid":o,children:[r?jsx("button",{type:"button",onClick:r,"aria-label":$e,style:l.iconButton,"data-testid":o?`${o}-back`:void 0,children:jsx("span",{"aria-hidden":"true",style:l.backChevron})}):jsx("span",{style:l.iconButton}),jsx("h2",{style:n==="document"?l.documentTitle:l.headerTitle,children:e}),jsx("div",{style:l.headerRight,children:t??jsx("span",{style:l.iconButton})})]})}i(We,"ScreenHeader");function pt({disclaimer:e,style:r}){let{styles:t}=G();return e.trim().length===0?null:jsxs("p",{role:"note","aria-label":ar.important(e),style:{...t.band,...r},"data-testid":"records-disclaimer-band",children:[jsx("span",{"aria-hidden":"true",style:t.infoGlyph,children:"i"}),jsx("span",{style:t.bandText,children:e})]})}i(pt,"DisclaimerBand");function Y({label:e,onClick:r,kind:t="primary",disabled:o=false,busy:n=false,ariaLabel:l,ariaDescribedBy:a,testID:d,style:s}){let{styles:c}=G(),u=t==="primary"?c.pillPrimary:t==="outline"?c.pillOutline:t==="danger"?c.pillDanger:t==="ask"?c.pillAsk:c.pillLink;return jsx("button",{type:"button",onClick:r,disabled:o||n,"aria-busy":n,"aria-label":l,"aria-describedby":a,style:{...c.pill,...u,...o?c.pillDisabled:{},...s},"data-testid":d,children:e})}i(Y,"Pill");function dr({label:e,tone:r="neutral",testID:t}){let{styles:o}=G();return jsx("span",{style:{...o.chip,...o.chipTones[r]},"data-testid":t,children:e})}i(dr,"Chip");function Tr({title:e,count:r}){let{styles:t}=G();return jsxs("div",{style:t.sectionHeader,children:[jsx("h3",{style:t.sectionTitle,children:e}),r!==void 0?jsx("span",{style:t.sectionCount,children:r}):null]})}i(Tr,"SectionHeader");function vt({direction:e="right"}){let{styles:r}=G(),t=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsx("span",{"aria-hidden":"true",style:{...r.chevron,transform:`rotate(${t})`}})}i(vt,"Chevron");function sp(e){let{color:r,space:t,radius:o,type:n,slots:l}=e,a=i((g,b)=>`${Math.round(g*b)}px`,"lh"),d=i((g,b,m,C="regular")=>({margin:0,...I(e,C),fontSize:g,lineHeight:a(g,b),color:m}),"text"),s=Ur(l.recordCard),c=`1px solid ${r.brandBorder}`,u=e.brightness==="dark"?r.errorRed:r.danger,p=i((g,b)=>({backgroundColor:g,color:b}),"tone"),f={boxSizing:"border-box",minHeight:sn,minWidth:sn,padding:`${t.md}px ${t.lg+t.xs/2}px`,borderRadius:o.pill,...I(e,"bold"),fontSize:n.size.body,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:t.sm,textDecoration:"none"};return {chipTones:{neutral:p(r.badgeBgNeutral,r.text.secondary),info:p(r.brandSoft,r.brand),warning:p(r.badgeBgCaution,r.warningStrong),critical:p(r.badgeBgCritical,r.danger),positive:p(r.badgeBgPositive,r.success)},root:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:ap,height:"100%",backgroundColor:r.background,color:r.text.primary,...I(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},content:{display:"flex",flexDirection:"column",gap:t.lg,padding:`0 ${t.lg}px ${t.xxl}px`},contentTight:{display:"flex",flexDirection:"column",gap:t.lg,padding:`0 ${t.sm}px ${t.xxl}px`},inset:{padding:`0 ${t.sm}px`},headerRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:t.sm,padding:`${t.xs}px ${t.lg}px ${t.md}px`},iconButton:{boxSizing:"border-box",width:sn,height:sn,display:"inline-flex",alignItems:"center",justifyContent:"center",border:0,background:"transparent",cursor:"pointer",padding:0,color:r.brand,flexShrink:0},backChevron:{display:"block",width:t.md,height:t.md,borderLeft:`2px solid ${r.brand}`,borderBottom:`2px solid ${r.brand}`,transform:"rotate(45deg)",marginLeft:t.xs},headerTitle:{...d(n.size.heading,n.lineHeight.tight,r.brand,"bold"),flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},documentTitle:{...d(n.size.subtitle,n.lineHeight.snug,r.text.primary,"bold"),flex:1,textAlign:"center"},headerRight:{display:"flex",alignItems:"center",gap:t.sm+t.xs/2},section:{display:"flex",flexDirection:"column",gap:t.sm+t.xs/2},sectionHeader:{display:"flex",alignItems:"center",gap:t.sm,padding:`0 ${t.xs}px`},sectionTitle:{...d(n.size.body+1,n.lineHeight.snug,r.text.primary,"bold")},sectionCount:{...d(n.size.bodyTight,n.lineHeight.snug,r.text.muted,"medium")},card:{boxSizing:"border-box",borderRadius:o.lg-t.xs,border:c,backgroundColor:r.surface,padding:`${t.xs}px ${t.lg}px`,margin:0,listStyle:"none",...Pr(l.recordCard,1)},creamCard:{boxSizing:"border-box",borderRadius:o.lg-t.xs/2,border:c,backgroundColor:r.surfaceCream,padding:t.lg,display:"flex",flexDirection:"column",gap:t.md,...Pr(l.recordCard,1)},row:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:t.md,padding:`${t.md}px 0`},rowDivider:{borderTop:`1px solid ${r.borderHairlineGreen}`},rowMain:{flex:1,minWidth:0},rowRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:t.xs+t.xs/2},rowTitle:{...d(n.size.body,n.lineHeight.snug,r.text.primary,"medium"),...s},rowDetail:{...d(n.size.caption,n.lineHeight.normal,r.text.secondary),marginTop:t.xs/2,...s},rowValue:{...d(n.size.body+1,n.lineHeight.snug,r.text.primary,"bold"),marginTop:t.xs/2,...s},rowMuted:{...d(n.size.caption,n.lineHeight.normal,r.text.muted),...s},chip:{display:"inline-block",borderRadius:o.pill,padding:`${t.xs-1}px ${t.sm}px`,...I(e,"medium"),fontSize:n.size.tiny,lineHeight:a(n.size.tiny,n.lineHeight.snug),whiteSpace:"nowrap"},pill:f,pillPrimary:{border:0,backgroundColor:r.brand,color:r.onPrimary,...Pr(l.primaryButton),...Ur(l.primaryButton)},pillOutline:{border:`1.5px solid ${r.brand}`,backgroundColor:"transparent",color:r.brand},pillDanger:{border:`1.4px solid ${r.danger}`,backgroundColor:r.surface,color:r.danger,fontSize:n.size.bodyTight},pillAsk:{border:`1px solid ${r.borderRingCream}`,backgroundColor:r.surface,color:r.text.primary},pillLink:{border:0,backgroundColor:"transparent",color:r.linkInk,padding:`${t.sm}px`},pillDisabled:{opacity:.5,cursor:"default"},infoNote:{display:"flex",gap:t.sm,borderRadius:o.md-t.xs/2,backgroundColor:r.brandSoft,padding:`${t.sm+t.xs/2}px ${t.md}px`,...d(n.size.bodyTight,n.lineHeight.normal,r.text.primary)},cautionNote:{display:"flex",gap:t.sm,borderRadius:o.md-t.xs/2,backgroundColor:r.badgeBgCaution,padding:`${t.sm+t.xs/2}px ${t.md}px`,...d(n.size.bodyTight,n.lineHeight.normal,r.warningStrong)},statusCard:{borderRadius:o.md,backgroundColor:r.brandSoft,padding:t.md+t.xs/2,...d(n.size.bodyTight,n.lineHeight.relaxed,r.text.primary)},errorBanner:{display:"flex",gap:t.sm,borderRadius:o.md-t.xs/2,backgroundColor:r.badgeBgCritical,padding:t.md,...d(n.size.bodyTight,n.lineHeight.normal,u)},errorText:d(n.size.bodyTight,n.lineHeight.normal,u),band:{display:"flex",alignItems:"flex-start",gap:t.sm,borderRadius:o.md-t.xs/2,padding:t.md,backgroundColor:r.brandSoft,margin:0},bandText:{flex:1,...d(n.size.caption,n.lineHeight.normal,r.text.secondary)},infoGlyph:{boxSizing:"border-box",flexShrink:0,width:t.md+t.xs/2,height:t.md+t.xs/2,borderRadius:o.pill,border:`1px solid ${r.text.secondary}`,display:"inline-flex",alignItems:"center",justifyContent:"center",...I(e,"bold"),fontSize:n.size.small,color:r.text.secondary},chevron:{display:"inline-block",width:t.sm,height:t.sm,borderTop:`2px solid ${r.text.muted}`,borderRight:`2px solid ${r.text.muted}`,flexShrink:0},lead:{...d(n.size.body+1,n.lineHeight.snug,r.text.primary,"bold"),padding:`0 ${t.sm}px`},field:{boxSizing:"border-box",display:"block",width:"100%",minHeight:sn,padding:`${t.sm}px ${t.md}px`,border:`1px solid ${r.borderHairlineGreen}`,borderRadius:o.sm,color:r.text.primary,backgroundColor:r.surface,...I(e,"regular"),fontSize:n.size.body},fieldLabel:{...d(n.size.bodyTight,n.lineHeight.normal,r.text.secondary,"medium"),display:"block",marginBottom:t.xs},muted:d(n.size.caption,n.lineHeight.normal,r.text.muted),bodyText:d(n.size.body,n.lineHeight.normal,r.text.primary),mono:I(e,"mono"),plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},sheetBackdrop:{position:"fixed",inset:0,backgroundColor:"rgba(0,0,0,0.4)",display:"flex",alignItems:"flex-end",justifyContent:"center",zIndex:10},sheet:{boxSizing:"border-box",width:"100%",maxWidth:560,maxHeight:"88%",overflowY:"auto",backgroundColor:r.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,padding:`${t.md}px ${t.lg+t.xs+t.xs/2}px ${o.xl}px`,display:"flex",flexDirection:"column",gap:t.md,...I(e,"regular"),color:r.text.primary},sheetHandle:{alignSelf:"center",width:t.xxl+t.xs,height:t.xs,borderRadius:o.pill,backgroundColor:r.borderRingCream},sheetHeader:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:t.sm},sheetTitle:{...d(n.size.heading,n.lineHeight.snug,r.text.primary,"bold")},sheetHelper:d(n.size.bodyTight,n.lineHeight.normal,r.text.muted),closeGlyph:{fontSize:n.size.verdict,lineHeight:1,color:r.text.primary}}}i(sp,"makeScreenStyles");function Nt(e,r){return e===null?"":r?`${e} ${r}`:e}i(Nt,"formatEntityValue");function ii(e){if(e===null||e.length===0)return "";let r=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(r!==null){let n=r[1]??"",l=r[2]??"",a=r[3]??"";return `${Number(l)}/${Number(a)}/${n.slice(2)}`}let t=Date.parse(e);if(Number.isNaN(t))return e;let o=new Date(t);return `${o.getUTCMonth()+1}/${o.getUTCDate()}/${String(o.getUTCFullYear()).slice(2)}`}i(ii,"formatShortDate");var Fs=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Q(e){if(!e)return "-";let r=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(r!==null){let n=Fs[Number(r[2])-1];return n===void 0?"-":`${n} ${Number(r[3])}, ${r[1]}`}let t=Date.parse(e);if(Number.isNaN(t))return "-";let o=new Date(t);return `${Fs[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(Q,"formatRecordsDate");var me=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 Br(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(Br,"markerStatusLabel");function Ft(e,r){return r<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${r} visits`}i(Ft,"trajectoryLabel");function jr(e){let r=e.replace(/_/g," ").trim();return r.length===0?e:r.charAt(0).toUpperCase()+r.slice(1)}i(jr,"humanize");var Ls=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 Lt(e){return Object.prototype.hasOwnProperty.call(Ls,e)?Ls[e]:jr(e)}i(Lt,"bodySystemLabel");var zs=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 zt(e){return Object.prototype.hasOwnProperty.call(zs,e)?zs[e]:jr(e)}i(zt,"soapSectionLabel");function Ms(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(Ms,"formatWeightKg");function cr(e,r,t){if((e===null||!Number.isFinite(e))&&t)return t;if(e===null||!Number.isFinite(e))return "-";let o=e.toFixed(3).replace(/\.?0+$/,"");return r?`${o} ${r}`:o}i(cr,"formatMarkerReading");function ai(e,r,t){let o=Ft(r,t);return e?`${me.measured(Q(e))}${o?` \xB7 ${o}`:""}`:o}i(ai,"labDetailLine");var $s=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"})}),si=60;function Us(e){return `Try again in ${e}s`}i(Us,"coolingActionLabel");var Bs="Try again, available shortly";var le=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 lp(e,r){if(!e)return false;let t=Date.parse(e);return Number.isNaN(t)?false:t<=r}i(lp,"isShareExpired");function dp(e,r){let t=Q(e);return t==="-"?r?"Expired":"No expiry date":r?`Expired ${t}`:`Expires ${t}`}i(dp,"formatShareExpiry");function js(e,r,t){let o=e.map(n=>{let l=lp(n.expiresAt,t),a=dp(n.expiresAt,l),d=Q(n.createdAt),s=l?"Expired":"Active",c=a.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return {shareId:n.shareId,shareUrl:r[n.shareId]??null,active:!l,statusLabel:s,expiryLabel:a,createdLabel:d==="-"?null:`Created ${d}`,a11yLabel:`Share link. ${s}. ${a}.`,actionContext:c}});return Object.freeze([...o.filter(n=>n.active),...o.filter(n=>!n.active)])}i(js,"buildShareRows");function Un(e,r){let t=e?.httpStatus;if(Yr(e)){if(r==="create")return "Records access for this pet is off, so a new link cannot be created.";if(r==="download")return "Records access for this pet is off, so the PDF cannot be downloaded."}if(t===429)return "You are creating links a little too fast. Wait a moment, then try again.";if(r==="revoke"&&(t===404||t===409||t===410))return "That link was already turned off.";if(t===401||t===403)return "You need to be signed in as this pet's owner to do that.";switch(r){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(Un,"shareErrorMessage");function fe({width:e,height:r,radius:t,style:o}){let{color:n,radius:l}=ue();return jsx("span",{"aria-hidden":"true",style:{display:"block",width:e,height:r,borderRadius:t??l.xs,backgroundColor:n.skeleton,flexShrink:0,...o}})}i(fe,"SkeletonBlock");var li=180,Vs=44,di=62;function Mt({testID:e}){let r=$t(),t=i(o=>jsxs("div",{style:r.actionRow,children:[jsxs("div",{style:r.actionLeft,children:[jsx(fe,{width:18,height:18,radius:9}),jsx(fe,{width:"55%",height:14,radius:7})]}),jsx(fe,{width:18,height:18,radius:9})]},o),"action");return jsxs("div",{role:"progressbar","aria-label":ar.loading,"aria-busy":"true",style:r.dashboard,"data-testid":e,children:[jsx("div",{style:r.inset,children:jsxs("div",{style:r.summaryCard,children:[jsx(fe,{width:li,height:li,radius:li/2}),jsxs("div",{style:r.badges,children:[jsx(fe,{width:70,height:22,radius:11}),jsx(fe,{width:70,height:22,radius:11})]})]})}),jsx("div",{style:r.inset,children:jsx(fe,{width:150,height:16,radius:8})}),jsx("div",{style:r.carouselCard,children:jsx(fe,{width:"100%",height:300,radius:14})}),jsxs("div",{style:r.dots,children:[jsx(fe,{width:6,height:6,radius:3}),jsx(fe,{width:18,height:6,radius:3}),jsx(fe,{width:6,height:6,radius:3})]}),jsx("div",{style:r.centered,children:jsx(fe,{width:46,height:12,radius:6})}),jsx("div",{style:r.inset,children:jsx(fe,{width:"100%",height:Vs,radius:12})}),jsxs("div",{style:{...r.inset,...r.actions},children:[t("a"),t("b")]})]})}i(Mt,"DashboardSkeleton");function Ws({testID:e}){let r=$t();return jsxs("div",{role:"progressbar","aria-label":ce.loading,"aria-busy":"true",style:r.request,"data-testid":e,children:[jsx("div",{children:[0,1,2,3].map(t=>jsxs("div",{style:r.railRow,children:[jsxs("div",{style:r.railColumn,children:[jsx(fe,{width:24,height:24,radius:12}),t<3?jsx(fe,{width:2,height:20,radius:1}):null]}),jsxs("div",{style:r.railBody,children:[jsx(fe,{width:"55%",height:14,radius:7}),jsx(fe,{width:"75%",height:11,radius:6})]})]},t))}),jsxs("div",{style:r.statusCard,children:[jsx(fe,{width:"90%",height:13,radius:6}),jsx(fe,{width:"60%",height:13,radius:6})]}),jsx(fe,{width:"100%",height:50,radius:25})]})}i(Ws,"RequestSkeleton");function Gs({testID:e}){let r=$t();return jsxs("div",{role:"progressbar","aria-label":me.loadingTimeline,"aria-busy":"true",style:r.timeline,"data-testid":e,children:[jsx("div",{style:r.timelineDisclaimer,children:jsx(fe,{width:"100%",height:Vs,radius:12})}),Array.from({length:6},(t,o)=>jsxs("div",{children:[o>0?jsx("div",{style:r.timelineSeparator}):null,jsxs("div",{style:r.timelineRow,children:[jsx(fe,{width:34,height:34,radius:17}),jsxs("div",{style:r.timelineBody,children:[jsxs("div",{style:r.timelineTop,children:[jsx(fe,{width:44,height:10,radius:5}),jsx(fe,{width:56,height:12,radius:6})]}),jsx(fe,{width:"70%",height:14,radius:7}),o%2===0?jsx(fe,{width:"45%",height:12,radius:6}):null]})]})]},o))]})}i(Gs,"TimelineSkeleton");function Ys({testID:e}){let r=$t();return jsx("div",{role:"progressbar","aria-label":xe.loading,"aria-busy":"true",style:r.clinics,"data-testid":e,children:Array.from({length:5},(t,o)=>jsxs("div",{style:r.clinicRow,children:[jsx(fe,{width:"65%",height:14,radius:7}),jsx(fe,{width:"40%",height:11,radius:6})]},o))})}i(Ys,"ClinicsSkeleton");function Ks({testID:e}){let r=$t();return jsx("div",{role:"progressbar","aria-label":le.loadingLinks,"aria-busy":"true",style:r.shares,"data-testid":e,children:[0,1].map(t=>jsxs("div",{style:r.shareRow,children:[jsx(fe,{width:"55%",height:13}),jsx(fe,{width:"40%",height:11})]},t))})}i(Ks,"SharesSkeleton");function Ue({variant:e,onAction:r,message:t,testID:o}){let n=$t(),l=$s[e],[a,d]=useState(e==="rate_limited"?si:0);useEffect(()=>{e==="rate_limited"&&d(si);},[e]),useEffect(()=>{if(a<=0)return;let u=setTimeout(()=>d(p=>Math.max(0,p-1)),1e3);return ()=>clearTimeout(u)},[a]);let s=e==="rate_limited"&&a>0,c=s?Us(a):l.action;return jsxs("section",{role:"status",style:n.empty,"data-testid":o,children:[jsx("span",{"aria-hidden":"true",style:n.emptyGlyph}),jsx("h3",{style:n.emptyTitle,children:l.title}),jsx("p",{style:n.emptyBody,children:t??l.body}),c!==null&&r?jsx("button",{type:"button",onClick:r,disabled:s,"aria-label":s?Bs:c,style:{...n.emptyAction,...s?n.emptyActionDisabled:{}},"data-testid":o?`${o}-action`:`records-empty-${e}-action`,children:c}):null]})}i(Ue,"RecordsEmptyState");function $t(){let e=ue();return useMemo(()=>pp(e),[e])}i($t,"useStyles");function pp(e){let{color:r,space:t,radius:o,type:n}=e,l=`1px solid ${r.brandBorder}`;return {dashboard:{display:"flex",flexDirection:"column",gap:t.lg,padding:`${t.xs}px ${t.sm}px 0`,backgroundColor:r.background},inset:{padding:`0 ${t.sm}px`},summaryCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.md+t.xs/2,borderRadius:o.lg-t.xs,border:l,backgroundColor:r.surface,padding:`${t.lg+t.xs}px ${t.lg}px`},badges:{display:"flex",gap:t.md},carouselCard:{borderRadius:o.lg-t.xs,border:l,backgroundColor:r.surface,padding:t.lg},dots:{display:"flex",alignItems:"center",justifyContent:"center",gap:t.xs+t.xs/2},centered:{display:"flex",justifyContent:"center"},actions:{display:"flex",flexDirection:"column",gap:t.sm+t.xs/2},actionRow:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,border:l,backgroundColor:r.surface,padding:t.lg},actionLeft:{flex:1,display:"flex",alignItems:"center",gap:t.md},request:{display:"flex",flexDirection:"column",gap:t.lg+t.xs/2,padding:`${t.xs}px ${t.lg}px 0`},railRow:{display:"flex",alignItems:"flex-start",gap:t.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.xs/2,width:24},railBody:{flex:1,display:"flex",flexDirection:"column",gap:t.xs+t.xs/2,paddingBottom:t.lg+t.xs/2},statusCard:{display:"flex",flexDirection:"column",gap:t.sm,borderRadius:o.md,backgroundColor:r.brandSoft,padding:t.md+t.xs/2},timeline:{backgroundColor:r.background},timelineDisclaimer:{padding:`${t.xs}px ${t.lg}px ${t.md}px`},timelineRow:{display:"flex",gap:t.md,padding:`${t.md+t.xs/2}px ${t.lg}px`},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:t.xs-1},timelineTop:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:t.sm},timelineSeparator:{height:1,backgroundColor:r.brandBorder,marginLeft:di},clinics:{display:"flex",flexDirection:"column",gap:t.md},clinicRow:{display:"flex",flexDirection:"column",gap:t.sm,borderRadius:o.lg-t.xs/2,border:l,backgroundColor:r.surface,padding:`${t.md+t.xs/2}px`},shares:{display:"flex",flexDirection:"column",gap:t.md,padding:t.md,borderRadius:o.md,backgroundColor:r.surfaceCream,border:l},shareRow:{display:"flex",flexDirection:"column",gap:t.xs+t.xs/2},empty:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.sm+t.xs/2,padding:`${t.xxl}px ${t.xl}px`,textAlign:"center"},emptyGlyph:{boxSizing:"border-box",width:22,height:22,borderRadius:11,backgroundColor:r.brandSoft,border:l,marginBottom:t.xs},emptyTitle:{margin:0,...I(e,"bold"),fontSize:n.size.subtitle,lineHeight:`${Math.round(n.size.subtitle*n.lineHeight.snug)-1}px`,color:r.brand},emptyBody:{margin:0,...I(e,"regular"),fontSize:n.size.bodyTight,lineHeight:`${Math.round(n.size.bodyTight*n.lineHeight.normal)}px`,color:r.text.muted,maxWidth:320},emptyAction:{boxSizing:"border-box",marginTop:t.sm,minHeight:40,borderRadius:o.pill,padding:`0 ${t.lg+t.xs/2}px`,backgroundColor:r.brand,color:r.onPrimary,border:0,cursor:"pointer",...I(e,"bold"),fontSize:n.size.bodyTight},emptyActionDisabled:{opacity:.5,cursor:"default"}}}i(pp,"makeStyles");var yp=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function ci(e){let{userRef:r,scopeEpoch:t}=Z();return jsx(De,{capability:"recordsClinic",style:e.style,className:e.className,...Oe(e.onBack,$e),children:r===null?jsx("p",{role:"alert",children:W.sessionRequired}):jsx(gp,{...Te(e,["onNavigate","onBack"])},JSON.stringify([r,t,e.petRef]))})}i(ci,"EverfurClinicPicker");function gp({petRef:e,controller:r,recordsController:t,location:o,onNavigate:n,onBack:l,style:a,className:d}){let{theme:s,styles:c}=G(),u=_r(),p=is(r??u,o),f=Ke(t?{petRef:e,controller:t}:{petRef:e}),g=useRef(Kr()),[b,m]=useState(false),[C,R]=useState(null),[x,y]=useState(false),[v,h]=useState(""),[E,T]=useState(false),[w,D]=useState(""),[A,O]=useState(false),$=useCallback(P=>{n?.({name:"consent",clinic:jo(P,null,"",g.current())});},[n]),L=i(()=>{b||(m(true),R(null),f.createRequest(`records-upload-${Date.now().toString(36)}`).then(P=>{if(m(false),!P.ok){R(ce.errors.start);return}n?.({name:"request",requestId:P.value.id});}));},"startUpload"),V=E?v:p.query,J=yp.test(w.trim()),Ce=V.trim().length>0&&J,re=p.isSearchActive?p.clinics:p.recent,k=p.isSearchActive?p.error?Ze(p.error):!p.initialLoading&&p.clinics.length===0?"idle":null:p.recent.length>0||p.recentLoading?null:"idle",S={display:"flex",flexDirection:"column",gap:s.space.sm},q=i(P=>{let B=P.currentTarget;B.scrollTop+B.clientHeight>=B.scrollHeight-B.clientHeight*.6&&p.loadMore();},"onScroll");return jsxs("div",{className:d,style:{...c.root,...a},"data-testid":"records-clinic-picker",children:[jsx(We,{title:xe.title,onBack:l,testID:"records-clinic-header"}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.space.sm,margin:`0 ${s.space.lg}px ${s.space.sm}px`,padding:`0 ${s.space.md+s.space.xs/2}px`,height:44,borderRadius:22,backgroundColor:s.color.surfaceSubtle,border:`1px solid ${s.color.borderHairlineGreen}`},children:[jsx("input",{type:"search",value:p.query,onChange:P=>p.setQuery(P.target.value),placeholder:xe.placeholder,maxLength:200,"aria-label":xe.searchA11y,autoComplete:"off",style:{flex:1,border:0,background:"transparent",font:"inherit",fontSize:s.type.size.body,color:s.color.text.primary,outline:"none"},"data-testid":"records-clinic-search-input"}),p.query.length>0?jsx("button",{type:"button",onClick:()=>p.setQuery(""),"aria-label":xe.clearSearch,style:{...c.iconButton,width:32,height:32},"data-testid":"records-clinic-search-clear",children:jsx("span",{"aria-hidden":"true",style:c.closeGlyph,children:"\xD7"})}):null]}),n?jsxs("div",{style:{...S,padding:`0 ${s.space.lg}px ${s.space.md}px`},children:[C?jsx("p",{role:"alert",style:c.errorBanner,children:C}):null,jsx(Y,{label:b?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",ariaLabel:xe.uploadOwnA11y,busy:b,onClick:L,testID:"records-clinic-upload-own"})]}):null,jsxs("div",{style:{...c.body,...c.content,gap:s.space.md},onScroll:p.isSearchActive?q:void 0,"data-testid":"records-clinic-results",children:[p.isSearchActive?jsxs("section",{style:{...c.creamCard,borderStyle:"dashed",padding:`${s.space.md}px ${s.space.md+s.space.xs/2}px`},"data-testid":"records-clinic-fallback-card",children:[jsxs("button",{type:"button",onClick:()=>y(P=>!P),"aria-expanded":x,"aria-label":x?xe.fallback.collapseA11y:xe.fallback.expandA11y,style:{display:"flex",alignItems:"center",gap:s.space.md,width:"100%",minHeight:44,background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},"data-testid":"records-clinic-fallback",children:[jsxs("span",{style:{flex:1,display:"flex",flexDirection:"column",gap:s.space.xs/2},children:[jsx("span",{style:{...c.rowTitle,...I(s,"bold")},children:xe.fallback.title}),jsx("span",{style:c.muted,children:xe.fallback.subtitle})]}),jsx(vt,{direction:x?"up":"down"})]}),x?jsxs("div",{style:S,children:[jsx("label",{htmlFor:"records-clinic-fallback-name",style:c.fieldLabel,children:xe.fallback.nameLabel}),jsx("input",{id:"records-clinic-fallback-name",style:c.field,value:V,onChange:P=>{h(P.target.value),T(true);},placeholder:xe.fallback.namePlaceholder,maxLength:200,autoComplete:"off","data-testid":"records-clinic-fallback-name"}),jsx("label",{htmlFor:"records-clinic-fallback-email",style:c.fieldLabel,children:xe.fallback.emailLabel}),jsx("input",{id:"records-clinic-fallback-email",type:"email",style:c.field,value:w,onChange:P=>{D(P.target.value),O(false);},onBlur:()=>O(true),placeholder:xe.fallback.emailPlaceholder,maxLength:320,autoComplete:"off","data-testid":"records-clinic-fallback-email"}),A&&w.trim().length>0&&!J?jsx("p",{role:"alert",style:c.errorText,children:ce.errors.invalidEmail}):null,jsx("p",{style:c.muted,children:xe.fallback.reviewNote}),jsx(Y,{label:xe.fallback.submit,ariaLabel:xe.fallback.submitA11y,disabled:!Ce||!n,onClick:()=>n?.({name:"consent",clinic:jo(null,V.trim(),w.trim().toLowerCase(),g.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):p.recent.length>0?jsx("h3",{style:{...c.fieldLabel,...I(s,"bold"),textTransform:"uppercase",marginBottom:0},"data-testid":"records-clinic-recent-label",children:xe.recentlyUsed}):null,p.isSearchActive&&p.initialLoading?jsx(Ys,{testID:"records-clinic-page-loading"}):null,jsx("ul",{style:{...c.plainList,gap:s.space.md},children:re.map(P=>{let B=Ka(P.emailStatus),se=Qa(P.distanceKm),Pe=[P.name,P.address,P.phone?`phone ${P.phone}`:null,se?Xa(P.distanceKm):null,B.a11y].filter(Boolean).join(", "),te=B.tone==="positive"?{backgroundColor:s.color.badgeBgPositive,color:s.color.success}:B.tone==="caution"?{backgroundColor:s.color.badgeBgCaution,color:s.color.cautionAccent}:{backgroundColor:s.color.badgeBgNeutral,color:s.color.text.muted};return jsx("li",{children:jsxs("button",{type:"button",onClick:()=>$(P),"aria-label":xe.selectA11y(Pe),style:{...c.creamCard,backgroundColor:s.color.surface,width:"100%",textAlign:"left",cursor:"pointer",gap:s.space.sm,padding:`${s.space.md}px ${s.space.md+s.space.xs/2}px`,font:"inherit",color:"inherit"},"data-testid":`records-clinic-${P.id}`,children:[jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.space.sm},children:[jsx("span",{style:{...c.rowTitle,...I(s,"bold"),color:s.color.brand},children:P.name}),se?jsx("span",{"aria-hidden":"true",style:{...c.muted,...c.mono},children:se}):null]}),P.address?jsx("span",{style:c.rowDetail,children:P.address}):null,P.phone?jsx("span",{"aria-hidden":"true",style:c.rowMuted,children:P.phone}):null,jsx("span",{"aria-hidden":"true",style:{...c.chip,...te,...I(s,"bold"),fontSize:s.type.size.micro,alignSelf:"flex-start"},children:B.label})]})},P.id)})}),k&&!p.initialLoading?jsx(Ue,{variant:k,message:p.isSearchActive&&k==="idle"?xe.noMatch(p.debouncedQuery):p.error?.displayMessage,onAction:p.error?.retryable===true?p.retry:void 0,testID:"records-clinic-empty"}):null,jsxs("div",{style:S,children:[p.loadingMore?jsx("p",{role:"status",style:{...c.muted,textAlign:"center"},"data-testid":"records-clinic-loading-more",children:xe.loadingMore}):null,p.pageError?jsx("button",{type:"button",onClick:p.loadMore,"aria-label":xe.loadMoreRetryA11y,style:{...c.pill,...c.pillLink},"data-testid":"records-clinic-page-error-retry",children:xe.loadMoreFailed}):null]})]}),jsx(Ie,{})]})}i(gp,"PickerBody");var qe=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${At} 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,r,t)=>`${e} of ${r} requests sent. ${t} couldn\u2019t be sent.`,"partial"),allSent:i(e=>`${e} ${e===1?"request":"requests"} sent.`,"allSent"),responded:i((e,r)=>`${e} of ${r} ${r===1?"clinic":"clinics"} responded`,"responded")});function ln(e,r,t,o){let n={owner_name:r,pet_name:t,clinic_name:o},l=false,a=e.scopeTemplate.replace(/\{([^{}]+)\}/g,(d,s)=>Object.prototype.hasOwnProperty.call(n,s)?n[s]??"":(l=true,""));return l||/[{}]/.test(a)?null:a}i(ln,"renderClinicScope");function dn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(dn,"clinicNeedsEmail");function Qs(e,r,t){let[o,n]=useState(e.ownerName),[l,a]=useState(""),[d,s]=useState(null),[c,u]=useState(""),[p,f]=useState([]),[g,b]=useState([]),[m,C]=useState(null),[R,x]=useState(null),[y,v]=useState(false),[h,E]=useState(false),[T,w]=useState(null),[D,A]=useState(0),O=useRef(false),$=useRef(false),L=useRef(0),V=useRef(Kr()),J=useRef(null),Ce=useRef(null),re=useRef(0);useEffect(()=>(O.current=true,$.current=false,v(false),()=>{O.current=false,re.current+=1,L.current+=1,J.current=null,Ce.current?.abort();}),[r]),useEffect(()=>{let te=true;return C(null),J.current=null,r.getAuthorizationCopy().then(ve=>{te&&(ve.ok?(C(ve.value),x(null)):x(ve.error));}).catch(()=>{te&&x(z("internalError"));}),()=>{te=false;}},[r,D]),useEffect(()=>{let te=true;return b([]),r.recentClinics({limit:5}).then(ve=>{te&&ve.ok&&b(ve.value.clinics);}).catch(()=>{}),()=>{te=false;}},[r]);let k=i(()=>{J.current=null,x(null);},"invalidate"),S=d?.name??l.trim(),q=m?ln(m,o.trim(),e.petName,S):null,P=dn(d),B=!!(m&&q&&o.trim()&&e.petName.trim()&&S&&(!P||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(c.trim()))&&t),se=i(async()=>{if($.current)return;let te=++L.current;E(true);try{let ve=await r.searchClinics({query:l.trim(),limit:100});if(!O.current||te!==L.current)return;ve.ok?(f(ve.value.clinics),x(null)):x(ve.error);}catch{O.current&&te===L.current&&x(z("internalError"));}finally{O.current&&te===L.current&&E(false);}},"search"),Pe=i(async()=>{if($.current||T||!B||!m||!q||!t)return;$.current=true;let te=re.current,ve=i(()=>O.current&&re.current===te,"current");v(true),x(null);try{if(!J.current){Ce.current=new AbortController;let Ve=await t({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:S,authorizationVersion:m.authorizationVersion,scopeText:q,signal:Ce.current.signal});if(!ve()||Ve===null)return;let xr=d&&(!P||d.emailStatus==="none")?{clinicId:d.id}:{clinicFreeText:S};J.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:m.authorizationVersion,...xr,...P?{clinicEmail:c.trim().toLowerCase()}:{},...Ve.signatureId!==void 0?{signatureId:Ve.signatureId}:{signaturePngBase64:Ve.signaturePngBase64},idempotencyKey:V.current()};}if(!ve())return;let or=await r.createClinicRequest(J.current);if(!ve())return;if(!or.ok){x(or.error);return}if(or.value.petRef!==e.petRef){x(z("internalError"));return}w(or.value),J.current=null,e.onCreated?.(or.value);}catch{ve()&&x(z("internalError"));}finally{$.current=false,ve()&&v(false);}},"submit");return {ownerName:o,query:l,clinic:d,email:c,clinics:p,copy:m,scope:q,error:R,busy:y,searching:h,created:T,ready:B,needsEmail:P,recent:p.length===0&&d===null?g:[],setOwnerName(te){$.current||(k(),n(te));},setQuery(te){$.current||(k(),L.current+=1,E(false),f([]),s(null),u(""),a(te));},setEmail(te){$.current||(k(),u(te));},selectClinic(te){$.current||(k(),L.current+=1,E(false),f([]),s(te),a(te.name),u(""));},invalidate:k,search:se,submit:Pe,retryCopy(){x(null),A(te=>te+1);}}}i(Qs,"useClinicRequestForm");var bp=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Bt(e){return e.clinic?.name??e.freeText??""}i(Bt,"draftName");function Ut(e){return dn(e.clinic)}i(Ut,"draftNeedsEmail");function Xs(e,r,t,o,n){let[l,a]=useState(e.ownerName),[d,s]=useState(""),[c,u]=useState([]),[p,f]=useState([]),[g,b]=useState([]),[m,C]=useState(null),[R,x]=useState(null),[y,v]=useState(false),[h,E]=useState(false),[T,w]=useState(null),[D,A]=useState(null),[O,$]=useState(0),L=useRef(false),V=useRef(false),J=useRef(0),Ce=useRef(0),re=useRef(Kr()),k=useRef(null),S=useRef(null);useEffect(()=>(L.current=true,V.current=false,v(false),()=>{L.current=false,Ce.current+=1,J.current+=1,k.current=null,S.current?.abort();}),[r,t]),useEffect(()=>{let M=true;return C(null),k.current=null,r.getAuthorizationCopy().then(be=>{M&&(be.ok?(C(be.value),x(null)):x(be.error));}).catch(()=>{M&&x(z("internalError"));}),()=>{M=false;}},[r,O]),useEffect(()=>{let M=true;return f([]),r.recentClinics({limit:5}).then(be=>{M&&be.ok&&f(be.value.clinics);}).catch(()=>{}),()=>{M=false;}},[r]);let q=i(()=>{k.current=null,x(null);},"invalidate"),P=g.map(Bt),B=m?P.map(M=>ln(m,l.trim(),e.petName,M)):[],se=B.every(M=>M!==null)?B.join(`
2
+
3
+ `):null,Pe=g.length>0&&g.every(M=>!Ut(M)||bp.test(M.email.trim())),te=g.length>=At,ve=!!(m&&se&&l.trim()&&e.petName.trim()&&Pe&&o)&&T===null,or=i(async()=>{if(V.current)return;let M=++J.current;E(true);try{let be=await r.searchClinics({query:d.trim(),limit:100});if(!L.current||M!==J.current)return;be.ok?(u(be.value.clinics),x(null)):x(be.error);}catch{L.current&&M===J.current&&x(z("internalError"));}finally{L.current&&M===J.current&&E(false);}},"search"),Ve=i(M=>{V.current||te||T!==null||M.clinic!==null&&g.some(be=>be.clinic?.id===M.clinic?.id)||(q(),b(be=>[...be,{...M,key:re.current(),idempotencyKey:re.current()}]),u([]),s(""));},"add"),xr=i(async()=>{if(V.current||T!==null||!ve||!m||!se||!o)return;V.current=true;let M=Ce.current,be=i(()=>L.current&&Ce.current===M,"current");v(true),x(null);try{if(k.current===null){S.current=new AbortController;let ir=await o({petRef:e.petRef,petName:e.petName,ownerName:l.trim(),clinicName:P.join(", "),authorizationVersion:m.authorizationVersion,scopeText:se,signal:S.current.signal});if(!be()||ir===null)return;if(k.current=ir,ir.signaturePngBase64!==void 0&&n!==void 0){let Hd=await n(ir.signaturePngBase64,S.current.signal);if(!be())return;k.current={signatureId:Hd.signatureId};}}let wr=k.current,Xt=g.map(ir=>({...ir.clinic!==null&&(!Ut(ir)||ir.clinic.emailStatus==="none")?{clinicId:ir.clinic.id}:{clinicFreeText:Bt(ir)},...Ut(ir)?{clinicEmail:ir.email.trim().toLowerCase()}:{},...wr.signatureId!==void 0?{signatureId:wr.signatureId}:{signaturePngBase64:wr.signaturePngBase64},idempotencyKey:ir.idempotencyKey})),Jt=await t.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:m.authorizationVersion,clinics:Xt});if(!be())return;if(!Jt.ok){x(Jt.error);return}w(Jt.value),e.onCreated?.(Jt.value),Sr(Jt.value.requestGroupId,M);}catch{be()&&x(z("internalError"));}finally{V.current=false,be()&&v(false);}},"submit"),Sr=i(async(M,be)=>{try{let wr=await r.getRequestGroup(M);if(!L.current||Ce.current!==be)return;wr.ok&&wr.value.petRef===e.petRef&&A(wr.value);}catch{}},"loadGroup"),Ee=i(async()=>{T===null||V.current||await Sr(T.requestGroupId,Ce.current);},"refreshGroup");return {ownerName:l,query:d,clinics:c,copy:m,scopeText:se,error:R,busy:y,searching:h,drafts:g,outcome:T,group:D,ready:ve,atCap:te,recent:c.length===0?p.filter(M=>!g.some(be=>be.clinic?.id===M.id)):[],setOwnerName(M){V.current||(q(),a(M));},setQuery(M){V.current||(J.current+=1,E(false),u([]),s(M));},search:or,addClinic(M){Ve({clinic:M,freeText:null,email:""});},addFreeText(){let M=d.trim();M.length!==0&&Ve({clinic:null,freeText:M,email:""});},setDraftEmail(M,be){V.current||(q(),b(wr=>wr.map(Xt=>Xt.key===M?{...Xt,email:be}:Xt)));},removeDraft(M){V.current||T!==null||(q(),b(be=>be.filter(wr=>wr.key!==M)));},submit:xr,refreshGroup:Ee,retryCopy(){x(null),$(M=>M+1);}}}i(Xs,"useClinicBatchForm");function Js(e){try{let r=new URL(e);if(r.protocol!=="https:"||r.username||r.password||r.port&&r.port!=="443")return !1;let t=r.hostname.toLowerCase();return t==="s3.amazonaws.com"||t.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(t)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(t)||t==="s3-accelerate.amazonaws.com"||t.endsWith(".s3-accelerate.amazonaws.com")||t==="s3-accelerate.dualstack.amazonaws.com"||t.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}i(Js,"trustedSignatureUploadUrl");function Zs(e,r,t,o){e.clearRect(0,0,t,o);let n=r.trim();if(!n)return;let l=Math.max(1,t-32),a=Math.min(44,Math.max(16,Math.round(o*.34))),d=i(()=>{e.font=`italic 700 ${a}px Georgia, "Times New Roman", serif`;},"font");for(d();a>12&&e.measureText(n).width>l;)a-=2,d();e.textAlign="center",e.textBaseline="middle",e.fillText(n,t/2,o/2,l);}i(Zs,"paintClinicTypedSignature");function el(e,r,t,o){e.clearRect(0,0,t,o);for(let n of r){let l=n[0];if(l!==void 0){e.beginPath(),e.moveTo(l[0],l[1]),n.length===1&&e.lineTo(l[0],l[1]);for(let a=1;a<n.length;a+=1){let d=n[a];d!==void 0&&e.lineTo(d[0],d[1]);}e.stroke();}}}i(el,"paintSignatureStrokes");async function rl(e,r,t,o=fetch){let n=i(()=>new Error("Signature upload failed"),"fail"),l=await new Promise(f=>e.toBlob(f,"image/png"));if(!l||!l.size||l.size>2*1024*1024||t.aborted)throw n();let a=await r.initiateSignatureUpload(l.size);if(!a.ok||t.aborted||!Js(a.value.uploadUrl))throw n();let d=new FormData;for(let[f,g]of Object.entries(a.value.uploadFields))d.append(f,g);d.append("file",l,"signature.png");let s=new AbortController,c=i(()=>s.abort(),"onAbort");t.addEventListener("abort",c,{once:true});let u=setTimeout(c,9e4);try{if(!(await o(a.value.uploadUrl,{method:"POST",body:d,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:s.signal})).ok||t.aborted)throw n()}catch{throw n()}finally{clearTimeout(u),t.removeEventListener("abort",c);}let p=await r.completeSignatureUpload(a.value.uploadId);if(!p.ok||t.aborted)throw n();return {signatureId:p.value}}i(rl,"registerClinicSignature");var Rp=8,vp=480,Cp=160;function St(e){let r=useRef(null),t=useRef(false),o=useRef([]),[n,l]=useState("draw"),[a,d]=useState(""),[s,c]=useState(false),u=useRef(a);u.current=a;let p=useCallback(()=>{let m=r.current,C=m?.getContext("2d");if(!m||!C)return;let R=typeof window<"u"&&window.devicePixelRatio||1;C.setTransform(R,0,0,R,0,0);let x=m.width/R,y=m.height/R;if(u.current.trim().length>0){C.fillStyle="#111",Zs(C,u.current,x,y);return}C.lineWidth=2,C.lineCap="round",C.lineJoin="round",C.strokeStyle="#111",el(C,o.current,x,y);},[]);useEffect(()=>{let m=r.current;if(!m)return;let C=i(()=>{let x=m.getBoundingClientRect(),y=typeof window<"u"&&window.devicePixelRatio||1,v=Math.max(1,Math.round((x.width||m.clientWidth||vp)*y)),h=Math.max(1,Math.round((x.height||m.clientHeight||Cp)*y));m.width!==v&&(m.width=v),m.height!==h&&(m.height=h),p();},"resize");if(C(),typeof ResizeObserver>"u")return;let R=new ResizeObserver(C);return R.observe(m),()=>R.disconnect()},[p]);let f=useCallback(()=>{e?.(),o.current=[],c(false),d(""),u.current="",p();},[e,p]),g=i(m=>{let C=m.currentTarget.getBoundingClientRect();return [m.clientX-C.left,m.clientY-C.top]},"point"),b=i(()=>o.current.reduce((m,C)=>m+C.length,0),"countPoints");return {canvas:r,mode:n,typed:a,signed:s,clear:f,setTyped(m){e?.(),d(m),u.current=m,c(!!m.trim()),p();},toggle(){f(),l(m=>m==="draw"?"type":"draw");},onPointerDown(m){n==="draw"&&(e?.(),t.current=true,m.currentTarget.setPointerCapture(m.pointerId),o.current=[...o.current,[g(m)]],p());},onPointerMove(m){if(!t.current||n!=="draw")return;let C=o.current[o.current.length-1];C!==void 0&&(o.current=[...o.current.slice(0,-1),[...C,g(m)]],p(),c(b()>=Rp));},onPointerUp(){t.current=false;},register(m,C){return !r.current||!s?Promise.reject(new Error("Signature upload failed")):rl(r.current,m,C)}}}i(St,"useSignatureCanvas");function wt({pad:e,disabled:r}){let t=ue(),o=e.mode==="type"?e.typed.trim():"",n={minHeight:44,padding:t.space.sm,border:`1px solid ${t.color.borderHairlineGreen}`,borderRadius:t.radius.sm,background:t.color.surface,color:t.color.text.primary,font:"inherit"},l={...n,cursor:"pointer"};return jsxs("div",{children:[jsx("p",{style:{margin:`0 0 ${t.space.sm}px`},children:e.mode==="draw"?K.draw:K.type}),jsx("button",{type:"button",style:{...l,alignSelf:"flex-start",marginBottom:t.space.sm,textDecoration:"underline"},disabled:r,onClick:e.toggle,"data-testid":"records-consent-sign-mode-toggle",children:e.mode==="draw"?K.toType:K.toDraw}),e.mode==="type"&&jsx("input",{"aria-label":K.type,style:{...n,display:"block",width:"100%",boxSizing:"border-box"},maxLength:Ya,value:e.typed,disabled:r,autoComplete:"off",onChange:a=>e.setTyped(a.target.value)}),jsx("canvas",{ref:e.canvas,role:"img","aria-label":o.length>0?K.typedSignatureA11y(o):K.sign,style:{display:"block",width:"100%",height:160,maxWidth:"100%",boxSizing:"border-box",touchAction:"none",background:"#fff",border:`1px solid ${t.color.borderHairlineGreen}`,...r?{opacity:.6,pointerEvents:"none"}:{},...e.mode==="type"?{pointerEvents:"none"}:{}},onPointerDown:a=>{r||e.onPointerDown(a);},onPointerMove:a=>{r||e.onPointerMove(a);},onPointerUp:e.onPointerUp,onPointerCancel:e.onPointerUp}),jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:t.space.sm,marginTop:t.space.sm},children:[jsx("p",{style:{margin:0,fontSize:t.type.size.tiny,color:t.color.text.muted},"data-testid":"records-signature-hint",children:e.signed?"\xA0":K.drawHint}),e.mode==="type"?null:jsx("button",{type:"button",style:l,disabled:r,onClick:e.clear,"aria-label":K.clearA11y,"data-testid":"records-signature-clear",children:K.clear})]})]})}i(wt,"SignatureCanvas");function fi(e){let{userRef:r,scopeEpoch:t}=Z();return jsx(De,{capability:"recordsClinic",...Oe(e.onClose,K.cancel),children:r===null?jsx("p",{role:"alert",children:W.sessionRequired}):jsx(Ep,{...Te(e,["onClose","onCreated"])},JSON.stringify([r,t,e.petRef,e.petName]))})}i(fi,"EverfurClinicRequestBatch");function Ep(e){let r=_r(),t=Ho(),o=e.controller??r,n=ue(),l=St(),a=Xs(e,o,e.batchClient??t,e.onCaptureSignature??(async m=>l.signed?l.register(o,m.signal):null)),d=e.onCaptureSignature!==void 0||l.signed,s={minHeight:44,padding:n.space.sm,border:`1px solid ${n.color.borderHairlineGreen}`,borderRadius:n.radius.sm,background:n.color.surface,color:n.color.text.primary,font:"inherit"},c={...s,display:"block",width:"100%",boxSizing:"border-box"},u={...s,cursor:"pointer"},p={margin:0,color:n.color.text.muted,fontSize:n.type.size.bodyTight},f=i(m=>[m.name,m.address,m.phone].filter(Boolean).join(", "),"clinicLabel"),g=a.busy?qe.sending:a.drafts.length===0?qe.addToContinue:a.error?qe.tryAgain:qe.send(a.drafts.length),b=a.outcome?qe.resultTitle:qe.title;return jsxs("section",{className:e.className,"aria-label":b,style:{background:n.color.surface,color:n.color.text.primary,padding:n.space.lg,borderRadius:n.radius.lg,minHeight:120,minWidth:0,overflowWrap:"anywhere",...e.style},children:[jsx("h2",{style:{margin:0,fontSize:n.type.size.heading},children:b}),jsx("p",{style:{margin:`${n.space.sm}px 0 ${n.space.lg}px`},children:e.petName}),a.outcome?jsxs("div",{style:{display:"grid",gap:n.space.sm},"data-testid":"records-batch-result",children:[jsx("p",{role:"status",style:{margin:0},children:a.outcome.createdCount===0?qe.allFailed:a.outcome.failedCount>0?qe.partial(a.outcome.createdCount,a.outcome.results.length,a.outcome.failedCount):qe.allSent(a.outcome.createdCount)}),jsx("h3",{style:{margin:0,fontSize:n.type.size.subtitle},children:qe.perClinic}),jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:n.space.sm},children:a.outcome.results.map((m,C)=>{let R=m.request?.clinicName??a.drafts[C]?.clinic?.name??m.clinicFreeText??"";return jsxs("li",{"data-testid":`records-batch-row-${m.created?"created":"failed"}`,children:[jsx("span",{children:R})," ",jsx("span",{style:p,children:m.created?qe.sent:qe.notSent}),m.created&&m.request?.statusLabel?jsx("p",{style:p,children:m.request.statusLabel}):null,!m.created&&m.failureReason?jsx("p",{style:p,children:m.failureReason}):null]},m.idempotencyKey)})}),a.group?jsx("p",{"aria-live":"polite",style:{margin:0},children:qe.responded(a.group.responded,a.group.total)}):null,a.group?.members.map(m=>m.statusLabel?jsx("p",{style:p,children:[m.clinicName,m.statusLabel].filter(Boolean).join(": ")},m.id):null)]}):jsxs("div",{style:{display:"grid",gap:n.space.md},children:[jsxs("label",{children:[K.ownerName,jsx("input",{style:c,maxLength:200,value:a.ownerName,disabled:a.busy,autoComplete:"name",onChange:m=>{l.clear(),a.setOwnerName(m.target.value);}})]}),a.drafts.length>0&&jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:n.space.sm},children:a.drafts.map(m=>jsxs("li",{"data-testid":`records-batch-draft-${m.key}`,style:{display:"grid",gap:n.space.xs},children:[jsx("span",{children:Bt(m)}),Ut(m)?jsxs("label",{children:[K.email,jsx("input",{style:c,type:"email",placeholder:K.emailPlaceholder,maxLength:320,autoComplete:"off",value:m.email,disabled:a.busy,onChange:C=>{l.clear(),a.setDraftEmail(m.key,C.target.value);}})]}):null,Ut(m)&&!m.email.trim()?jsx("p",{style:p,children:qe.emailToAdd}):null,jsx("button",{type:"button",style:u,disabled:a.busy,"aria-label":qe.remove(Bt(m)),onClick:()=>{l.clear(),a.removeDraft(m.key);},children:qe.remove(Bt(m))})]},m.key))}),jsx("p",{style:{margin:0},children:a.atCap?qe.atCap:qe.addClinic}),!a.atCap&&jsxs(Fragment,{children:[jsxs("label",{children:[K.clinic,jsx("input",{style:c,placeholder:K.placeholder,maxLength:200,value:a.query,disabled:a.busy,autoComplete:"off",onChange:m=>a.setQuery(m.target.value)})]}),jsx("button",{type:"button",style:u,disabled:a.busy||a.searching||a.query.trim().length<2,onClick:()=>{a.search();},children:K.search}),a.query.trim().length>0&&a.clinics.length===0&&!a.searching&&jsx("button",{type:"button",style:u,disabled:a.busy,onClick:()=>{l.clear(),a.addFreeText();},children:qe.addClinic}),a.searching&&jsx("p",{role:"status",children:W.loading}),a.recent.length>0&&jsx("h3",{style:{margin:0,fontSize:n.type.size.subtitle},children:K.recentlyUsed}),a.recent.map(m=>jsx("button",{type:"button",style:u,disabled:a.busy,onClick:()=>{l.clear(),a.addClinic(m);},children:f(m)},`recent-${m.id}`)),a.clinics.map(m=>jsx("button",{type:"button",style:u,disabled:a.busy,onClick:()=>{l.clear(),a.addClinic(m);},children:f(m)},m.id))]}),jsx("h3",{style:{margin:`${n.space.sm}px 0 0`,fontSize:n.type.size.subtitle},children:K.scopeHeading}),a.copy?jsx("p",{style:{whiteSpace:"pre-wrap",margin:0},children:a.drafts.length>0&&a.ownerName.trim()?a.scopeText??z("internalError").displayMessage:W.consentRequired}):!a.error&&jsx("p",{role:"status",children:W.loading}),!e.onCaptureSignature&&jsx(wt,{pad:l,disabled:a.busy}),!d&&jsx("p",{role:"alert",children:K.missingSignature}),a.error&&jsx("p",{role:"alert",children:a.error.displayMessage}),!a.copy&&a.error&&jsx("button",{type:"button",style:u,onClick:a.retryCopy,children:W.retry}),jsx("button",{type:"button","aria-label":qe.sendA11y(a.drafts.length),style:{...u,background:n.color.primary,color:n.color.onPrimary,opacity:a.busy||!a.ready||!d?.5:1},disabled:a.busy||!a.ready||!d,onClick:()=>{a.submit();},children:g})]}),e.onClose&&jsx("button",{type:"button",style:u,disabled:a.busy,onClick:e.onClose,children:K.cancel}),jsx(Ie,{})]})}i(Ep,"BatchBody");var Re=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,r)=>`I authorize ${r} to release ${we(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,r)=>`We don\u2019t have an email on file for ${r}. Add it so we can request ${we(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 Sp="value_text",ol=64,il=512;function al(e){return e!==null&&e.httpStatus===409&&!Yr(e)}i(al,"isFactReviewerLocked");var cn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:Sp}),sl=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,ll=/^\d{4}-\d{2}-\d{2}$/;function dl(e){if(e==null)return "text";let r=e.trim();return sl.test(r)?"num":ll.test(r)&&!Number.isNaN(Date.parse(r))?"date":r==="true"||r==="false"?"bool":"text"}i(dl,"inferFactValueKind");function yi(e,r){let t=r.trim(),o=dl(e);if(o==="num"&&sl.test(t)){let n=Number(t);if(Number.isFinite(n))return Object.freeze({[cn.num]:n})}return o==="date"&&ll.test(t)&&!Number.isNaN(Date.parse(t))?Object.freeze({[cn.date]:t}):Object.freeze(o==="bool"&&(t==="true"||t==="false")?{[cn.bool]:t==="true"}:{[cn.text]:t})}i(yi,"factCorrectionFor");var _e=z$1.string().nullish(),jn=z$1.number().nullish(),wp=z$1.object({collected_at:_e,at:_e,value:jn,unit:_e,qualitative_result:_e,ref_low:jn,ref_high:jn,status:_e,source_clinic:_e,source_doc_id:_e,doc_id:_e,reviewed:z$1.boolean().nullish()}),kp=z$1.object({collected_at:_e,at:_e,value:jn,unit:_e,qualitative_result:_e,status:_e}),_p=z$1.object({marker_id:z$1.string().min(1),canonical_name:_e,name:_e,loinc_code:_e,canonical_unit:_e,unit:_e,panel_name:_e,panel:_e,meaning_text:_e,meaning:_e,latest:kp.nullish(),trajectory:_e,points:z$1.array(wp).optional()}),Pp=z$1.object({total_markers:z$1.number().int().nonnegative(),in_range_count:z$1.number().int().nonnegative(),out_of_range_count:z$1.number().int().nonnegative(),unknown_count:z$1.number().int().nonnegative()}),Tp=z$1.object({markers:z$1.array(_p).optional(),summary:Pp.nullish(),disclaimer:z$1.string().optional(),featured_marker_id:_e});function Dp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Dp,"isObject");function cl(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(cl,"withheldMarkers");function ul(e,r){let t=Dp(r)?r:{},o=typeof t.pet_ref=="string"&&t.pet_ref.length>0?t.pet_ref:e;if(t.withheld===true)return cl(o);let n=Tp.safeParse(t);if(!n.success)return cl(o);let l=n.data,a=i(s=>Object.freeze({at:s.collected_at??s.at??null,value:s.value??null,unit:s.unit??null,qualitativeResult:s.qualitative_result??null,refLow:s.ref_low??null,refHigh:s.ref_high??null,status:s.status??null,sourceClinic:s.source_clinic??null,docId:s.source_doc_id??s.doc_id??null,reviewed:s.reviewed===true}),"point"),d=(l.markers??[]).map(s=>Object.freeze({markerId:s.marker_id,name:s.canonical_name??s.name??s.marker_id,loincCode:s.loinc_code??null,unit:s.canonical_unit??s.unit??null,panel:s.panel_name??s.panel??null,meaning:s.meaning_text??s.meaning??null,latest:s.latest?Object.freeze({at:s.latest.collected_at??s.latest.at??null,value:s.latest.value??null,unit:s.latest.unit??null,qualitativeResult:s.latest.qualitative_result??null,status:s.latest.status??null}):null,trajectory:s.trajectory??null,points:Object.freeze((s.points??[]).map(a))}));return Object.freeze({petRef:o,withheld:false,markers:Object.freeze(d),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(ul,"mapRecordMarkers");var Ip=z$1.string().min(1).refine(e=>e.startsWith("https://")),Op=z$1.object({source_doc_id:z$1.string().min(1),file_name:z$1.string().nullish(),doc_format:z$1.string().nullish(),byte_size:z$1.number().int().nonnegative().nullish(),received_at:z$1.string().nullish(),download_url:Ip,expires_in_seconds:z$1.number().int().nonnegative().nullish()}),Ap=z$1.object({items:z$1.array(z$1.unknown()).optional()});function pl(e){let r=Ap.safeParse(e);if(!r.success)return null;let t=[];for(let o of r.data.items??[]){let n=Op.safeParse(o);n.success&&t.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(t)}i(pl,"mapRequestDocuments");var qp=z$1.string().min(1).refine(e=>e.startsWith("https://")),un=z$1.string().nullish(),Np=z$1.object({share_id:z$1.string().min(1),share_url:z$1.string().min(1),expires_at:un}),Fp=z$1.object({shares:z$1.array(z$1.object({share_id:z$1.string().min(1),expires_at:un,created_at:un,view_count:z$1.number().int().nonnegative().nullish(),last_viewed_at:un})).optional()}),Lp=z$1.object({download_url:qp,expires_at:un});function zp(e,r){let t=e.trim();if(t.length===0)return null;try{let o=/^[a-z][a-z0-9+.-]*:/i.test(t)?new URL(t):r!==void 0?new URL(t,r):null;return o===null||o.protocol!=="https:"?null:o.toString()}catch{return null}}i(zp,"resolveShareUrl");function ml(e,r){let t=Np.safeParse(e);if(!t.success)return null;let o=zp(t.data.share_url,r);return o===null?null:Object.freeze({shareId:t.data.share_id,shareUrl:o,expiresAt:t.data.expires_at??null})}i(ml,"mapRecordShareLink");function fl(e){let r=Fp.safeParse(e);return r.success?Object.freeze((r.data.shares??[]).map(t=>Object.freeze({shareId:t.share_id,expiresAt:t.expires_at??null,createdAt:t.created_at??null,viewCount:t.view_count??0,lastViewedAt:t.last_viewed_at??null}))):null}i(fl,"mapRecordShareList");function yl(e){let r=Lp.safeParse(e);return r.success?Object.freeze({downloadUrl:r.data.download_url,expiresAt:r.data.expires_at??null}):null}i(yl,"mapRecordPdfLink");var Mp=z$1.object({signatures:z$1.array(z$1.object({signature_id:z$1.string().min(1),preview_url:z$1.string().min(1).refine(e=>e.startsWith("https://")),created_at:z$1.string().nullish()})).optional()});function gl(e){let r=Mp.safeParse(e);return r.success?Object.freeze((r.data.signatures??[]).map(t=>Object.freeze({signatureId:t.signature_id,previewUrl:t.preview_url,createdAt:t.created_at??null}))):null}i(gl,"mapSignatureSuggestions");var U=z$1.string().nullish(),pn=z$1.number().nullish(),$p=z$1.object({at:U,value:pn,unit:U,qualitative_result:U,ref_low:pn,ref_high:pn,status:U,doc_id:U}),Up=z$1.object({marker_id:z$1.string(),name:z$1.string(),loinc_code:U,unit:U,panel:U,meaning:U,latest:z$1.object({at:U,value:pn,unit:U,qualitative_result:U,status:U}).nullish(),trajectory:U,points:z$1.array($p).optional()}),Bp=z$1.object({encounter_id:z$1.string(),date:U,type:U,clinic_name:U,veterinarian:U,doc_id:U}),jp=z$1.object({note_id:z$1.string(),encounter_id:U,observed_on:U,sections:z$1.array(z$1.object({section:z$1.string(),text:z$1.string()})).optional()}),Hp=z$1.object({exam_id:z$1.string(),encounter_id:U,observed_on:U,doc_id:U,systems:z$1.record(z$1.object({finding_status:U,finding:U})).optional()}),Vp=z$1.object({has_lab_history:z$1.boolean().optional(),has_vaccination_history:z$1.boolean().optional(),has_weight_history:z$1.boolean().optional(),has_vitals_history:z$1.boolean().optional(),has_physical_exam_history:z$1.boolean().optional(),has_procedure_history:z$1.boolean().optional(),has_genetic_history:z$1.boolean().optional(),has_reproductive_history:z$1.boolean().optional(),has_parasite_prevention_history:z$1.boolean().optional(),earliest_record_at:U,latest_record_at:U,documents_ingested:z$1.number().int().nonnegative().optional(),documents_in_review:z$1.number().int().nonnegative().optional(),entities_pending_review:z$1.record(z$1.number().int().nonnegative()).optional(),held_total:z$1.number().int().nonnegative().optional()}),Wp=z$1.object({conflict_id:z$1.string(),entity_type:z$1.string(),field:U,severity:U,candidates:z$1.array(z$1.object({value:z$1.string(),source_doc_id:U,doc_id:U,collected_at:U})).optional()}),Gp=z$1.object({lab_results:z$1.array(Up).optional(),encounters:z$1.array(Bp).optional(),clinician_notes:z$1.array(jp).optional(),physical_exams:z$1.array(Hp).optional(),completeness:Vp.nullish(),conflicts:z$1.array(Wp).optional()}),Yp=z$1.object({visits:z$1.array(z$1.object({visit_id:z$1.string(),visit_date:U,veterinarian:U,summary:U,doc_id:U})),vaccines:z$1.array(z$1.object({vaccine_id:z$1.string(),product:U,lot:U,administered_on:U,expires_on:U,doc_id:U})),weights:z$1.array(z$1.object({weight_id:z$1.string(),observed_on:U,weight_kg:pn,doc_id:U})),medications:z$1.array(z$1.object({medication_id:z$1.string(),drug_name:U,dose:U,route:U,frequency:U,sig:U,rx_number:U,started_on:U,stopped_on:U,doc_id:U})),disclaimer:z$1.string().optional()}),Kp=z$1.object({document:Co,contributions:z$1.array(vo),contribution_count:z$1.number().int().nonnegative().optional()});function bi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(bi,"isObject");function hi(e,r){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:r}i(hi,"petOf");function gi(e,r){return Object.freeze({petRef:e,available:false,withheld:r,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(gi,"emptyDepth");function Qp(e,r){let t=bi(r)?r:{},o=hi(t,e);if(t.withheld===true)return gi(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(s=>s in t))return gi(o,false);let l=Gp.safeParse(t);if(!l.success)return gi(o,true);let a=l.data,d=i(s=>Object.freeze({at:s.at??null,value:s.value??null,unit:s.unit??null,qualitativeResult:s.qualitative_result??null,refLow:s.ref_low??null,refHigh:s.ref_high??null,status:s.status??null,docId:s.doc_id??null}),"point");return Object.freeze({petRef:o,available:true,withheld:false,labResults:Object.freeze((a.lab_results??[]).map(s=>Object.freeze({markerId:s.marker_id,name:s.name,loincCode:s.loinc_code??null,unit:s.unit??null,panel:s.panel??null,meaning:s.meaning??null,latest:Object.freeze({at:s.latest?.at??null,value:s.latest?.value??null,unit:s.latest?.unit??null,qualitativeResult:s.latest?.qualitative_result??null,status:s.latest?.status??null}),trajectory:s.trajectory??null,points:Object.freeze((s.points??[]).map(d))}))),encounters:Object.freeze((a.encounters??[]).map(s=>Object.freeze({encounterId:s.encounter_id,date:s.date??null,type:s.type??null,clinicName:s.clinic_name??null,veterinarian:s.veterinarian??null,docId:s.doc_id??null}))),clinicianNotes:Object.freeze((a.clinician_notes??[]).map(s=>Object.freeze({noteId:s.note_id,encounterId:s.encounter_id??null,observedOn:s.observed_on??null,sections:Object.freeze((s.sections??[]).map(c=>Object.freeze({section:c.section,text:c.text})))}))),physicalExams:Object.freeze((a.physical_exams??[]).map(s=>Object.freeze({examId:s.exam_id,encounterId:s.encounter_id??null,observedOn:s.observed_on??null,docId:s.doc_id??null,systems:Object.freeze(Object.entries(s.systems??{}).map(([c,u])=>Object.freeze({system:c,findingStatus:u.finding_status??null,finding:u.finding??null})))}))),completeness:a.completeness?Object.freeze({hasLabHistory:a.completeness.has_lab_history===true,hasVaccinationHistory:a.completeness.has_vaccination_history===true,hasWeightHistory:a.completeness.has_weight_history===true,hasVitalsHistory:a.completeness.has_vitals_history===true,hasPhysicalExamHistory:a.completeness.has_physical_exam_history===true,hasProcedureHistory:a.completeness.has_procedure_history===true,hasGeneticHistory:a.completeness.has_genetic_history===true,hasReproductiveHistory:a.completeness.has_reproductive_history===true,hasParasitePreventionHistory:a.completeness.has_parasite_prevention_history===true,earliestRecordAt:a.completeness.earliest_record_at??null,latestRecordAt:a.completeness.latest_record_at??null,documentsIngested:a.completeness.documents_ingested??0,documentsInReview:a.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...a.completeness.entities_pending_review??{}}),heldTotal:a.completeness.held_total??0}):null,conflicts:Object.freeze((a.conflicts??[]).map(s=>Object.freeze({conflictId:s.conflict_id,entityType:s.entity_type,field:s.field??null,severity:s.severity??"needs_review",candidates:Object.freeze((s.candidates??[]).map(c=>Object.freeze({value:c.value,docId:c.source_doc_id??c.doc_id??null,collectedAt:c.collected_at??null})))})))})}i(Qp,"mapRecordDepth");function bl(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(bl,"withheldTimeline");function Xp(e,r){let t=bi(r)?r:{},o=hi(t,e);if(t.withheld===true)return bl(o);let n=Yp.safeParse(t);if(!n.success)return bl(o);let l=n.data,a=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})),d=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})),s=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})),c=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:a.length===0&&d.length===0&&s.length===0&&c.length===0,visits:Object.freeze(a),vaccines:Object.freeze(d),weights:Object.freeze(s),medications:Object.freeze(c),disclaimer:l.disclaimer??""})}i(Xp,"mapRecordsTimeline");function Jp(e,r){let t=bi(r)?r:{},o=hi(t,e),n=i(()=>Object.freeze({petRef:o,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(t.withheld===true)return n();let l=Kp.safeParse(t);if(!l.success)return n();let a=Object.freeze(l.data.contributions.map(Eo));return Object.freeze({petRef:o,withheld:false,document:xo(l.data.document),contributions:a,contributionCount:l.data.contribution_count??a.length})}i(Jp,"mapDocumentContributions");var Zp="/widget/v1/records/pets";function hl(e){let r=e.funnel??st({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),t=i((s,c)=>typeof s=="string"&&s.length>0&&!lt(s)&&[...s].length<=c,"segment"),o=i(async(s,c,u,p)=>{if(!t(c,tr))return Zr();let f=await r.send(s,{method:"GET",path:u});if(!f.ok)return f;let g=p(f.value);return g.petRef===c?ke(g):j(z("internalError",{retryable:false}))},"read"),n=i(s=>`${Zp}/${encodeURIComponent(s)}`,"pet"),l=i(s=>`${n(s)}/everfur_record`,"record"),a=i(async(s,c,u)=>{let p=await r.send(s,c,c.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!p.ok)return p;let f=u(p.value);return f===null?j(z("internalError",{retryable:false})):ke(f)},"parsed"),d=i((s,c)=>!t(s.entityType,ol)||!t(s.canonicalKey,il)||s.idempotencyKey!==void 0&&!t(s.idempotencyKey,en)||c!==void 0&&Object.keys(c).length===0?null:{entity_type:s.entityType,canonical_key:s.canonicalKey,...c!==void 0?{corrected_fields:c}:{},...s.idempotencyKey!==void 0?{idempotency_key:s.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(s=>o("records.depth.record",s,`${n(s)}/record`,c=>Qp(s,c)),"getRecordDepth"),getTimeline:i(s=>o("records.depth.timeline",s,`${n(s)}/timeline`,c=>Xp(s,c)),"getTimeline"),getDocumentContributions(s,c){return t(c,64)?o("records.depth.contributions",s,`${n(s)}/documents/${encodeURIComponent(c)}/contributions`,u=>Jp(s,u)):Zr()},getMarkers:i(s=>o("records.depth.markers",s,`${n(s)}/markers`,c=>ul(s,c)),"getMarkers"),createShare(s){return t(s,tr)?a("records.share.create",{method:"POST",path:`${l(s)}/share`},c=>ml(c,e.apiBaseUrl)):Zr()},listShares(s){return t(s,tr)?a("records.share.list",{method:"GET",path:`${l(s)}/shares`},fl):Zr()},async revokeShare(s,c){if(!t(s,tr)||!t(c,64))return Zr();let u=await r.send("records.share.revoke",{method:"DELETE",path:`${l(s)}/shares/${encodeURIComponent(c)}`},{idempotent:false,maxAttempts:1});return u.ok?ke(void 0):u},getPdfLink(s){return t(s,tr)?a("records.pdf.link",{method:"GET",path:`${l(s)}/pdf-link`},yl):Zr()},async editFact(s,c){let u=t(s,tr)?d(c,c.correctedFields):null;if(u===null)return Zr();let p=await r.send("records.fact.edit",{method:"POST",path:`${l(s)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?ke(void 0):p},async removeFact(s,c){let u=t(s,tr)?d(c):null;if(u===null)return Zr();let p=await r.send("records.fact.remove",{method:"POST",path:`${l(s)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?ke(void 0):p},listRequestDocuments(s){return t(s,64)?a("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(s)}/documents`},pl):Zr()},listAuthorizationSignatures:i(()=>a("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},gl),"listAuthorizationSignatures")}}i(hl,"createRecordsDepthClient");function Zr(){return Promise.resolve(j(z("validationFailed",{retryable:false})))}i(Zr,"invalid");function Ar(){let{runtime:e,userRef:r,scopeEpoch:t}=Z();return useMemo(()=>{let{services:o}=e.registry;return hl({auth:o.authFor(r),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,r,t])}i(Ar,"useEverfurRecordsDepthClient");function qr(e,r,t,o=""){let n=Ar(),{userRef:l}=Z(),a=Pn(e),d=useMemo(()=>({}),[n,e,o,a]),[s,c]=useState({scope:d,value:null,error:null,loading:true}),u=useRef(0),p=useCallback(async()=>{let R=u.current+=1;if(c({scope:d,value:null,error:null,loading:true}),l===null){c({scope:d,value:null,error:null,loading:false});return}let x=await r(n,e);R===u.current&&(x.ok?c({scope:d,value:x.value,error:null,loading:false}):c({scope:d,value:null,error:x.error,loading:false}));},[n,e,r,d,l]);useEffect(()=>(p(),()=>{u.current+=1;}),[p]);let f=s.scope===d?s:{value:null,error:null,loading:true},g=useCallback(()=>{p();},[p]),b=f.error===null||f.error.httpStatus!==404,m=b?f.error:null,C=f.loading?"loading":m!==null?"error":f.value===null?"empty":f.value.withheld?"populated":t(f.value)?"empty":"populated";return useMemo(()=>({status:C,value:f.value,error:m,available:b,refresh:g}),[C,f.value,m,b,g])}i(qr,"useRecordsDepthRead");function mt(e){return e!==null&&e.httpStatus===404}i(mt,"isDarkRouteError");var om=i((e,r)=>e.getMarkers(r),"readMarkers"),im=i(e=>e.markers.length===0,"markersEmpty");function vi(e){let r=qr(e,om,im);return useMemo(()=>{let t=r.available&&r.value!==null&&!r.value.withheld?r.value:null;return {status:r.status,markers:t,available:r.available,error:r.error,refresh:r.refresh}},[r])}i(vi,"useRecordsMarkers");var am=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Cl(e){let{clinic:r,controller:t,depthClient:o,capture:n,onCreated:l}=e,a=r.clinic?.name??r.freeText??"",d=r.clinic===null,[s,c]=useState(false),[u,p]=useState(e.ownerName),[f,g]=useState(r.email),[b,m]=useState(false),[C,R]=useState(null),[x,y]=useState(null),[v,h]=useState(0),[E,T]=useState(null),[w,D]=useState(false),[A,O]=useState(null),[$,L]=useState([]),[V,J]=useState(null),[Ce,re]=useState(false),k=useRef(false),S=useRef(true),q=useRef(Kr()),P=useRef(null);useEffect(()=>(S.current=true,()=>{S.current=false,P.current=null;}),[t]),useEffect(()=>{let Ee=true;return R(null),P.current=null,t.getAuthorizationCopy().then(M=>{Ee&&(M.ok?(R(M.value),y(null)):y(M.error));}).catch(()=>{Ee&&y(z("internalError"));}),()=>{Ee=false;}},[t,v]),useEffect(()=>{if(o===void 0)return;let Ee=true;return o.listAuthorizationSignatures().then(M=>{Ee&&(M.ok?L(M.value):mt(M.error)||L([]));}).catch(()=>{}),()=>{Ee=false;}},[o]);let B=dn(r.clinic),se=f.trim().toLowerCase(),Pe=am.test(se),te=B&&(b||se.length>0)&&!Pe?Re.emailRequired:null,ve=C?ln(C,u.trim(),we(e.petName),a):null,or=e.hostCapture===true||Ce||V!==null,Ve=!!(s&&C&&ve&&u.trim()&&a&&or&&(!B||Pe)),xr=useCallback(async()=>{if(!(k.current||A!==null||!C||!ve)){if(!a){T(Re.missingDraftError);return}if(B&&!Pe){m(true),T(Re.emailRequired);return}if(!(!s||!u.trim())){k.current=true,D(true),T(null);try{if(P.current===null){let M=V!==null?{signatureId:V}:await n();if(!S.current)return;if(M===null){T(Re.missingSignatureError);return}let be=r.clinic&&(!B||r.clinic.emailStatus==="none")?{clinicId:r.clinic.id}:{clinicFreeText:a};P.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:C.authorizationVersion,...be,...B?{clinicEmail:se}:{},...M.signatureId!==void 0?{signatureId:M.signatureId}:{signaturePngBase64:M.signaturePngBase64},idempotencyKey:q.current()};}let Ee=await t.createClinicRequest(P.current);if(!S.current)return;if(!Ee.ok){T(Ee.error.displayMessage);return}if(Ee.value.petRef!==e.petRef){T(z("internalError").displayMessage);return}O(Ee.value),P.current=null,l?.(Ee.value);}catch{S.current&&T(z("internalError").displayMessage);}finally{k.current=false,S.current&&D(false);}}}},[s,n,r.clinic,a,t,C,A,e.petRef,B,se,l,u,V,ve,Pe]),Sr=useCallback(()=>{P.current=null,T(null);},[]);return {title:d?Re.titleFreeText:Re.titleDirectory,clinicName:a,isFreeText:d,authorized:s,ownerName:u,email:f,emailError:te,needsEmail:B,directoryClinicNoEmail:B&&r.clinic!==null,copy:C,copyError:x,scope:ve,error:E,busy:w,created:A,ready:Ve,signatures:$,reuseSignatureId:V,hasSignature:or,setAuthorized(Ee){k.current||(Sr(),c(Ee));},setOwnerName(Ee){k.current||(Sr(),p(Ee));},setEmail(Ee){k.current||(Sr(),m(false),g(Ee));},setSigned(Ee){k.current||(Sr(),re(Ee),Ee&&J(null));},pickReuseSignature(Ee){k.current||(Sr(),J(Ee));},retryCopy(){y(null),h(Ee=>Ee+1);},submit:xr}}i(Cl,"useRecordsConsentForm");function Ei(e){let{userRef:r,scopeEpoch:t}=Z();return jsx(De,{capability:"recordsClinic",style:e.style,className:e.className,...Oe(e.onBack,$e),children:r===null?jsx("p",{role:"alert",children:W.sessionRequired}):jsx(dm,{...Te(e,["onCreated","onNavigate","onBack"])},JSON.stringify([r,t,e.petRef,e.clinic.key]))})}i(Ei,"EverfurRecordsConsent");function dm({petRef:e,petName:r,clinic:t,ownerName:o,onCaptureSignature:n,onCreated:l,controller:a,onNavigate:d,onBack:s,style:c,className:u}){let{theme:p,styles:f}=G(),g=_r(),b=a??g,m=Ar(),C=St(),R=Cl({petRef:e,petName:r,ownerName:o??"",clinic:t,controller:b,depthClient:m,capture:n?()=>n({petRef:e,petName:we(r),ownerName:R.ownerName,clinicName:R.clinicName,authorizationVersion:R.copy?.authorizationVersion??"",scopeText:R.scope??"",signal:new AbortController().signal}):async()=>C.signed?C.register(b,new AbortController().signal):null,hostCapture:n!==void 0,onCreated:i(w=>{l?.(w),d?.({name:"dashboard"});},"onCreated")}),x=C.signed,y=useRef(R);y.current=R,useEffect(()=>{y.current.setSigned(x);},[x]);let v=R.busy,h={display:"flex",flexDirection:"column",gap:p.space.sm},E="records-consent-owner-name",T="records-consent-clinic-email";return jsxs("div",{className:u,style:{...f.root,...c},"data-testid":"records-consent-screen",children:[jsx(We,{title:R.title,onBack:s,testID:"records-consent-header"}),jsxs("div",{style:{...f.body,...f.content,gap:p.space.lg+p.space.xs/2},"data-testid":"records-consent",children:[jsxs("section",{style:f.creamCard,"aria-label":Re.scopeHeading,children:[jsx("h3",{style:{...f.sectionTitle,color:p.color.brand},children:Re.scopeHeading}),jsx("p",{style:f.bodyText,children:Re.scopeBody}),jsx("ul",{style:{...f.plainList,gap:p.space.sm},children:Re.whatWeDo.map(w=>jsxs("li",{style:{...f.bodyText,display:"flex",gap:p.space.sm},children:[jsx("span",{"aria-hidden":"true",style:{color:p.color.brand,...I(p,"bold")},children:"\u2713"}),jsx("span",{children:w})]},w))}),jsx("p",{style:{...f.muted,paddingTop:p.space.xs,borderTop:`1px solid ${p.color.borderHairlineGreen}`},children:Re.retentionNote}),R.copy&&R.scope?jsx("p",{style:{...f.rowDetail,whiteSpace:"pre-wrap"},"data-testid":"records-consent-scope",children:R.scope}):R.copyError?jsxs(Fragment,{children:[jsx("p",{role:"alert",style:f.errorText,children:R.copyError.displayMessage}),jsx(Y,{label:W.retry,kind:"outline",onClick:R.retryCopy,testID:"records-consent-copy-retry"})]}):jsx("p",{role:"status",style:f.muted,children:W.loading})]}),jsxs("button",{type:"button",role:"checkbox","aria-checked":R.authorized,onClick:()=>R.setAuthorized(!R.authorized),style:{display:"flex",alignItems:"flex-start",gap:p.space.md,textAlign:"left",font:"inherit",cursor:"pointer",borderRadius:p.radius.lg-p.space.xs,border:`1px solid ${R.authorized?p.color.brand:p.color.brandBorder}`,backgroundColor:R.authorized?p.color.brandSoft:p.color.surface,padding:p.space.md+p.space.xs/2,color:p.color.text.primary},"data-testid":"records-authorize-toggle",children:[jsx("span",{"aria-hidden":"true",style:{boxSizing:"border-box",flexShrink:0,width:p.space.xl,height:p.space.xl,borderRadius:p.radius.xs+1,border:`1.6px solid ${p.color.brand}`,backgroundColor:R.authorized?p.color.brand:p.color.surface,color:p.color.onPrimary,display:"inline-flex",alignItems:"center",justifyContent:"center",...I(p,"bold")},children:R.authorized?"\u2713":""}),jsx("span",{style:{...f.rowTitle,...I(p,"bold"),fontSize:p.type.size.bodyTight},children:Re.authorizeLabel(r,R.clinicName)})]}),jsxs("div",{style:h,children:[jsx("label",{htmlFor:E,style:f.fieldLabel,children:Re.fullName}),jsx("input",{id:E,style:f.field,value:R.ownerName,placeholder:Re.fullNamePlaceholder,maxLength:200,disabled:v,autoComplete:"name",onChange:w=>R.setOwnerName(w.target.value),"data-testid":"records-consent-owner-name"})]}),R.needsEmail?jsxs("div",{style:h,"data-testid":"records-consent-email-block",children:[R.directoryClinicNoEmail?jsx("p",{style:f.cautionNote,"data-testid":"records-consent-no-email-note",children:Re.noEmailNote(r,R.clinicName)}):null,jsx("label",{htmlFor:T,style:f.fieldLabel,children:Re.emailLabel}),jsx("input",{id:T,type:"email",style:f.field,value:R.email,placeholder:Re.emailPlaceholder,maxLength:320,disabled:v,autoComplete:"off",onChange:w=>R.setEmail(w.target.value),"data-testid":"records-consent-clinic-email"}),R.emailError?jsx("p",{role:"alert",style:f.errorText,children:R.emailError}):null,jsx("p",{style:f.muted,"data-testid":"records-consent-review-note",children:Re.newClinicDirectSendNote})]}):null,n?null:jsxs("div",{style:h,children:[R.signatures.length>0?jsxs("div",{style:h,children:[jsx("span",{style:f.fieldLabel,children:Re.reuseSignature}),jsx("div",{style:{display:"flex",gap:p.space.sm,overflowX:"auto",padding:`${p.space.xs}px 0`},children:R.signatures.map(w=>{let D=R.reuseSignatureId===w.signatureId;return jsx("button",{type:"button",onClick:()=>R.pickReuseSignature(D?null:w.signatureId),"aria-label":D?Re.reuseTileSelectedA11y:Re.reuseTileA11y,"aria-pressed":D,style:{flexShrink:0,width:112,height:56,borderRadius:p.radius.sm,border:D?`2px solid ${p.color.brand}`:`1px solid ${p.color.brandBorder}`,backgroundColor:p.color.surface,padding:0,overflow:"hidden",cursor:"pointer"},"data-testid":`records-consent-reuse-${w.signatureId}`,children:jsx("img",{src:w.previewUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"contain"}})},w.signatureId)})}),jsx("p",{style:f.muted,children:Re.reuseHint})]}):null,jsx(wt,{pad:C,disabled:v}),jsx("p",{style:f.muted,children:Re.signatureHint(R.clinicName)}),!R.hasSignature&&R.clinicName.length>0?jsx("p",{style:f.muted,"data-testid":"records-consent-signature-required",children:Re.missingSignatureError}):null]}),R.error?jsx("p",{role:"alert","aria-live":"assertive",style:f.errorBanner,children:R.error}):null,R.created?jsx("p",{role:"status",style:f.bodyText,children:R.created.statusLabel||W.records}):null]}),jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:p.space.sm,padding:`${p.space.md}px ${p.space.lg}px ${p.space.xxl}px`,borderTop:`1px solid ${p.color.borderHairlineGreen}`,backgroundColor:p.color.background},children:[s?jsx(Y,{label:K.cancel,kind:"link",disabled:v,onClick:s,style:{flex:"0 0 auto"},testID:"records-consent-cancel"}):null,jsx(Y,{label:v?Re.submitting:Re.submit,ariaLabel:Re.submitA11y,disabled:!R.ready,busy:v,onClick:()=>{R.submit();},style:{flex:"1 1 12rem",minWidth:0,minHeight:54},testID:"records-consent-submit"})]}),jsx(Ie,{})]})}i(dm,"ConsentBody");function Vn(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(Vn,"markerStatusTone");function um(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(um,"markerStatusSpoken");function pm(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(pm,"rangePhrase");function Wn(e,r){let t=r?` ${r}`:"";return e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}${t}`:e.refLow!==null?`\u2265 ${e.refLow}${t}`:e.refHigh!==null?`\u2264 ${e.refHigh}${t}`:"-"}i(Wn,"formatReferenceRange");function xi(e,r){let t=r.reviewed?", reviewed by our team":"",o=r.sourceClinic?`, from ${r.sourceClinic}`:"";return `${Q(r.at)}: ${cr(r.value,e.unit,r.qualitativeResult)}, ${um(r.status)}${pm(r)}${o}${t}`}i(xi,"markerPointSpoken");function Be(e){return e?.trim()||"my pet"}i(Be,"lead");function El(e){let r=e.trim();return /[.!?]$/.test(r)?r:`${r}.`}i(El,"clause");function xl(e,r){let t=r.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Be(e)}'s ${t}`],n=[r.latestValueText?.trim(),r.statusText?.trim(),r.trajectoryText?.trim()].filter(Boolean).join(", ");return o[0]+=n?`: ${n}.`:".",r.meaningText?.trim()&&o.push(El(r.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Be(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:r.markerId,payload:{marker:t,...r.statusText?.trim()?{status:r.statusText.trim()}:{}}}}}i(xl,"buildMarkerAskPrompt");function Sl(e,r,t){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:l,unknownCount:a}=r;if(o===0)return {prompt:`I'm looking at ${Be(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Be(e)}?`,entityRef:{type:"marker_summary",id:t,payload:{total:0}}};let d=a>0?`, ${a} without a reference range`:"";return {prompt:`I'm looking at ${Be(e)}'s lab markers: ${o} total, ${n} in range, ${l} out of range${d}. What should I focus on?`,entityRef:{type:"marker_summary",id:t,payload:{total:o,inRange:n,outOfRange:l,unknown:a}}}}i(Sl,"buildMarkerSummaryAskPrompt");function wl(e,r){let t=r.canonicalName.trim()||"a lab marker",o=[`${t}: ${r.valueText.trim()}`];r.collectedAt?.trim()&&o.push(`collected ${r.collectedAt.trim()}`),r.sourceClinic?.trim()&&o.push(`from ${r.sourceClinic.trim()}`),r.referenceText?.trim()&&o.push(`reference range ${r.referenceText.trim()}`),r.flagged&&o.push(`flagged ${r.flagged}`);let n={marker:t};return r.flagged&&(n.status=r.flagged),r.reviewed!==void 0&&(n.reviewed=r.reviewed),{prompt:`I'm looking at ${Be(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:r.entityId,payload:n}}}i(wl,"buildMarkerReadingAskPrompt");function kl(e,r,t){let o=r.clinicName?.trim(),n=r.heldItemCount??0,l=n>0?`, ${n} fact${n===1?"":"s"} being verified`:"";return {prompt:`I'm looking at ${Be(e)}'s records request${o?` to ${o}`:""}, status: ${r.statusLabel.trim()}${l}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:t,payload:{status:r.status,held:n,...o?{clinic:o}:{}}}}}i(kl,"buildRecordsRequestAskPrompt");var mm=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function _l(e,r,t,o){let n=r.entityTypeLabel.trim()||"record",l=r.title.trim()||n,a=r.detail?.trim();return {prompt:`I'm looking at ${Be(e)}'s ${n.toLowerCase()}: ${l}${a?`, ${a}`:""}. What does this mean, and what should I keep on top of for ${Be(e)}?`,entityRef:{type:mm[t]??t,id:o,payload:{kind:n,title:l,...a?{detail:a}:{}}}}}i(_l,"buildEntityRowAskPrompt");function Pl(e,r,t){let o=r.filter(a=>a.label.trim()),n={type:"upcoming_care",id:t};if(o.length===0)return {prompt:`I'm looking at ${Be(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Be(e)} be on?`,entityRef:n};let l=[...o].sort((a,d)=>(a.tone==="overdue"?0:1)-(d.tone==="overdue"?0:1)).slice(0,4).map(a=>a.relativeText.trim()?`${a.label.trim()} (${a.relativeText.trim().toLowerCase()})`:a.label.trim());return {prompt:`I'm looking at ${Be(e)}'s upcoming care: ${l.join(", ")}. What should I prioritize for ${Be(e)}, and how do I stay on top of these?`,entityRef:n}}i(Pl,"buildUpcomingCareAskPrompt");function Tl(e,r,t){let o=[`I'm looking at ${Be(e)}'s physical exam${r.observedOn?.trim()?` from ${r.observedOn.trim()}`:""}.`],n=r.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 ${Be(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Be(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:t}}}i(Tl,"buildPhysicalExamAskPrompt");function Dl(e,r,t){let o=[`I'm looking at ${Be(e)}'s visit notes${r.observedOn?.trim()?` from ${r.observedOn.trim()}`:""}.`];for(let n of r.sections.filter(l=>l.text.trim()).slice(0,3))o.push(`${n.label.trim()||"Note"}: ${El(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Be(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:t}}}i(Dl,"buildVisitNoteAskPrompt");function Il(e,r,t){let o=r.scopeLabel.trim()||"a detail",n=r.candidates.filter(a=>a.value.trim()),l=n.slice(0,3).map(a=>`"${a.value.trim()}"${a.clinicName?.trim()?` (${a.clinicName.trim()})`:""}`).join(" vs ");return {prompt:`Two of ${Be(e)}'s documents disagree on ${o}: ${l}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:t,payload:{field:o,severity:r.severity,values:n.map(a=>a.value.trim()).join(" | ")}}}}i(Il,"buildConflictAskPrompt");function Hr(e,r){return e??r?.version??""}i(Hr,"resolveConsentVersion");function et(e,r){return Hr(e,r).length>0}i(et,"canGrantConsent");function Vr(e,r){return e.denialReason==="consent_required"?r?{kind:"consent_required"}:{kind:"consent_unavailable"}:e.denialReason==="pet_not_found"?{kind:"pet_not_found",error:z("petNotFound",{retryable:false})}:e.denialReason==="entitlement"?{kind:"error",error:z("accessDenied")}:e.denialReason==="session_required"?{kind:"session_required"}:e.withheld?{kind:"withheld"}:e.error===null?{kind:"withheld"}:{kind:"error",error:e.error}}i(Vr,"selectErrorView");function Gn(e){let r=e.clinicName?.trim()??"";return r.length>0?r:e.source==="owner_provided"?Ol.ownerUpload:Ol.clinicRequest}i(Gn,"selectRequestTitle");var Ol=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function Si(e){return `${e} ${W.beingReviewed}`}i(Si,"heldItemsLabel");function fm(e){let r=[...e].sort((t,o)=>t.updatedAt!==o.updatedAt?t.updatedAt>o.updatedAt?-1:1:t.createdAt!==o.createdAt?t.createdAt>o.createdAt?-1:1:0);return Object.freeze(r)}i(fm,"selectRequestList");function mn(e){let r=e.actionNeededLabel?.trim()??"";return r.length>0?r:e.statusLabel}i(mn,"selectPrimaryLabel");function Yn(e){if(e.showClinicPhone!==true)return null;let r=e.clinicPhone?.trim()??"";return r.length===0?null:{phone:r,dial:`tel:${r.replace(/[^+\d]/g,"")}`,clinicName:e.clinicName?.trim()||null}}i(Yn,"selectClinicCall");function Al(e){switch(e.wireStatus??e.status){case "published":return "positive";case "failed":case "clinic_declined":return "critical";case "revoked":return "neutral";case "clinic_responded_no_records":case "awaiting_upload":case "records_received":case "parsing":case "parsing_failed":case "in_review":case "review_email_failed":return "warning";default:return "info"}}i(Al,"selectRequestStatusTone");var pr=200,wi=16,ki=(pr-wi)/2,ql=2*Math.PI*ki;function Fl({summary:e,onAsk:r,testID:t}){let o=ym(),{theme:n,styles:l}=G(),{totalMarkers:a,inRangeCount:d,outOfRangeCount:s,unknownCount:c}=e,u=d+s+c,p=useMemo(()=>{if(!(u>0))return [];let f=[{key:"in_range",color:n.color.success,count:d},{key:"out_of_range",color:n.color.danger,count:s},{key:"unknown",color:n.color.text.muted,count:c}],g=0;return f.filter(b=>b.count>0).map(b=>{let m=b.count/u*ql,C=-g;return g+=m,{key:b.key,color:b.color,length:m,offset:C}})},[u,d,s,c,n]);return jsxs("section",{role:"group","aria-label":hr.title,style:o.card,"data-testid":t,children:[jsx("h3",{style:o.title,children:hr.title}),jsx("div",{style:o.ringRow,children:jsxs("div",{style:o.ringWrap,role:"img","aria-label":hr.a11y(a,d,s,c),children:[jsxs("svg",{width:pr,height:pr,viewBox:`0 0 ${pr} ${pr}`,"aria-hidden":"true",focusable:"false",children:[jsx("circle",{cx:pr/2,cy:pr/2,r:ki,stroke:n.color.surfaceSubtle,strokeWidth:wi,fill:"none"}),jsx("g",{transform:`rotate(-90 ${pr/2} ${pr/2})`,children:p.map(f=>jsx("circle",{cx:pr/2,cy:pr/2,r:ki,stroke:f.color,strokeWidth:wi,fill:"none",strokeDasharray:`${f.length} ${ql}`,strokeDashoffset:f.offset,strokeLinecap:p.length>1?"round":"butt","data-testid":`marker-ring-${f.key}`},f.key))})]}),jsxs("div",{style:o.center,"aria-hidden":"true",children:[jsx("span",{style:o.centerCount,children:a}),jsx("span",{style:o.centerLabel,children:a===1?hr.marker:hr.markers})]})]})}),p.length>0?jsxs("div",{style:o.badges,children:[jsx("span",{style:{...o.badge,borderColor:n.color.danger,color:n.color.danger},children:`${s} ${hr.outOfRange}`}),jsx("span",{style:{...o.badge,borderColor:n.color.success,color:n.color.success},children:`${d} ${hr.inRange}`}),c>0?jsx("span",{style:{...o.badge,borderColor:n.color.text.muted,color:n.color.text.muted},children:`${c} ${hr.noRange}`}):null]}):null,jsx("p",{style:o.subtitle,children:hr.subtitle}),r?jsx("button",{type:"button",onClick:r,"aria-label":hr.askA11y,style:{...l.pill,...l.pillAsk},"data-testid":"marker-summary-ask",children:hr.ask}):null]})}i(Fl,"MarkerSummaryCard");function ym(){let e=ue();return useMemo(()=>gm(e),[e])}i(ym,"useStyles");function gm(e){let{color:r,space:t,radius:o,type:n}=e;return {card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.sm+t.xs/2,borderRadius:o.sm,backgroundColor:r.surfaceCream,border:`1px solid ${r.brandBorder}`,padding:t.lg-1},title:{margin:0,...I(e,"bold"),fontSize:n.size.body,color:r.brand,letterSpacing:n.letterSpacing.headerBrand},ringRow:{display:"flex",justifyContent:"center"},ringWrap:{position:"relative",width:pr,height:pr},center:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",pointerEvents:"none"},centerCount:{...I(e,"medium"),fontSize:n.size.verdict*2,lineHeight:1.1,color:r.text.primary},centerLabel:{...I(e,"medium"),fontSize:n.size.heading-1,lineHeight:1.2,color:r.text.primary},badges:{display:"flex",flexWrap:"wrap",justifyContent:"center",gap:t.sm},badge:{border:"1px solid",borderRadius:o.pill,padding:`${t.xs}px ${t.sm+t.xs/2}px`,...I(e,"mono"),fontSize:n.size.nano,lineHeight:`${n.size.tiny}px`,textTransform:"uppercase",letterSpacing:n.letterSpacing.headerBrand/2},subtitle:{margin:0,...I(e,"regular"),fontSize:n.size.caption,lineHeight:`${Math.round(n.size.caption*n.lineHeight.relaxed)}px`,color:r.text.primary}}}i(gm,"makeStyles");function bm(e){return e.value!==null&&Number.isFinite(e.value)}i(bm,"numeric");function Ll(e){let r=e.points.filter(bm);if(r.length===0)return null;let t=e.points[e.points.length-1]??null,o=t?.refLow??null,n=t?.refHigh??null,l=r.map(R=>R.value),a=Math.min(...l,...o!==null?[o]:[],...n!==null?[n]:[]),d=Math.max(...l,...o!==null?[o]:[],...n!==null?[n]:[]);a===d&&(a-=1,d+=1);let s=(d-a)*.18,c=a-s,u=d+s,p=u-c,f=i(R=>(u-R)/p*100,"y"),g=6,b=r.length,m=r.map((R,x)=>({index:x,xPct:b<=1?50:g+x/(b-1)*(100-2*g),yPct:f(R.value),status:R.status,point:R})),C=o!==null||n!==null?{topPct:n!==null?f(n):0,bottomPct:o!==null?f(o):100}:null;return {points:m,band:C,firstDate:r[0]?.at??null,lastDate:r[r.length-1]?.at??null}}i(Ll,"buildMarkerChart");var Ml='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function $l(e){return e.tagName==="DIALOG"}i($l,"isDialogElement");function Vt(e,r,t){let o=useRef(null),n=useRef(false),l=useRef(null),a=useRef(t);a.current=t;let d=useCallback(()=>{if(!n.current)return;n.current=false;let u=a.current===void 0?l.current:a.current.current;l.current=null,u&&u.isConnected&&u.focus();},[]);useEffect(()=>{if(!e){d();return}if(!n.current){let f=typeof document>"u"?null:document.activeElement;l.current=f instanceof HTMLElement?f:null;}n.current=true;let u=o.current;if(u===null)return;if(!$l(u)){u.contains(document.activeElement)||(u.querySelector(Ml)??u).focus();return}let p=u;typeof p.showModal=="function"?p.open||p.showModal():p.setAttribute("open","");},[e,d]),useEffect(()=>d,[d]);let s=useCallback(u=>{let p=o.current;if(p===null)return;if(u.key==="Escape"&&!$l(p)){u.preventDefault(),u.stopPropagation(),r();return}if(u.key!=="Tab")return;let f=Array.from(p.querySelectorAll(Ml)),g=f[0],b=f[f.length-1];if(!g||!b){u.preventDefault();return}let m=document.activeElement;u.shiftKey&&(m===g||!p.contains(m))?(u.preventDefault(),b.focus()):!u.shiftKey&&(m===b||!p.contains(m))&&(u.preventDefault(),g.focus());},[r]),c=useCallback(u=>{u.preventDefault(),r();},[r]);return {dialogRef:o,onKeyDown:s,onCancel:c}}i(Vt,"useModalDialog");var Ul=100,Qn=44;function Rm({marker:e,onPointPress:r,onAsk:t}){let o=Pi(),{theme:n,styles:l}=G(),a=Br(e.latest?.status??null),d=Ft(e.trajectory,e.points.length),s=useMemo(()=>Ll(e),[e]),c=e.latest?cr(e.latest.value,e.unit,e.latest.qualitativeResult):null;return jsx("li",{style:o.page,"data-testid":`marker-card-${e.markerId}`,children:jsxs("article",{style:o.card,children:[jsxs("div",{style:o.headerRow,children:[jsxs("div",{style:o.nameColumn,children:[jsx("span",{style:o.markerName,children:e.name}),e.unit?jsx("span",{style:o.unit,children:e.unit}):null]}),jsx("span",{"aria-label":Xr.status(a.label),children:jsx(dr,{label:a.label,tone:Vn(e.latest?.status??null)})})]}),e.latest&&c!==null?jsxs("div",{style:o.latestRow,children:[jsx("span",{style:{...o.latestValue,...a.outOfRange?o.latestValueDanger:{}},"aria-label":Xr.latestA11y(c,a.label,Q(e.latest.at)),children:c}),jsx("span",{style:o.latestDate,children:Q(e.latest.at)})]}):null,d?jsx("p",{style:o.trajectory,children:d}):null,s!==null?jsxs("div",{style:o.chartWrap,children:[jsxs("svg",{viewBox:`0 0 ${Ul} ${Qn}`,preserveAspectRatio:"none",style:o.plot,"aria-hidden":"true",focusable:"false",children:[s.band?jsx("rect",{x:0,y:s.band.topPct/100*Qn,width:Ul,height:Math.max(0,(s.band.bottomPct-s.band.topPct)/100*Qn),fill:n.color.badgeBgPositive}):null,s.points.length>1?jsx("polyline",{fill:"none",stroke:n.color.brandBorder,strokeWidth:.6,vectorEffect:"non-scaling-stroke",points:s.points.map(u=>`${u.xPct},${u.yPct/100*Qn}`).join(" ")}):null]}),jsx("div",{style:o.dotLayer,children:s.points.map(u=>jsx("button",{type:"button",onClick:()=>r(e,u.point),"aria-label":xi(e,u.point),style:{...o.dot,...u.status==="above"||u.status==="below"?o.dotDanger:{},left:`${u.xPct}%`,top:`${u.yPct}%`},"data-testid":`marker-point-${e.markerId}-${u.index}`},u.index))}),jsx("ul",{"aria-label":Xr.readingsA11y(e.name),style:o.a11yTable,children:e.points.map((u,p)=>jsx("li",{children:xi(e,u)},p))}),jsx("p",{style:e.points.length===1?o.singleHint:o.tapHint,children:e.points.length===1?Xr.singleHint:Xr.tapHint})]}):jsx("p",{style:o.emptyBody,children:Xr.empty}),t?jsx("button",{type:"button",onClick:()=>t(e),"aria-label":Xr.askA11y(e.name),style:{...l.pill,...l.pillAsk},"data-testid":`marker-ask-${e.markerId}`,children:Xr.ask}):null]})})}i(Rm,"MarkerTrendCard");function jl({markers:e,onPointPress:r,onAsk:t}){let o=Pi(),[n,l]=useState(0),a=i(s=>{let c=s.currentTarget;c.clientWidth<=0||l(Math.max(0,Math.min(Math.round(c.scrollLeft/c.clientWidth),e.length-1)));},"onScroll"),d=e[n]??null;return jsxs("div",{style:o.carousel,"data-testid":"marker-carousel",children:[jsx("ul",{style:o.track,onScroll:a,children:e.map(s=>jsx(Rm,{marker:s,onPointPress:r,onAsk:t},s.markerId))}),jsxs("div",{style:o.footer,"aria-label":ni.a11y(d?.name??null,n,e.length),children:[jsx("div",{style:o.dots,"aria-hidden":"true",children:e.map((s,c)=>jsx("span",{style:{...o.dotIndicator,...c===n?o.dotActive:{}}},s.markerId))}),jsx("span",{style:o.counter,children:ni.counter(n,e.length)})]})]})}i(jl,"MarkerTrendCarousel");function Hl({marker:e,point:r,onClose:t,onAsk:o}){let n=Pi(),{styles:l}=G(),a=Vt(e!==null&&r!==null,t);if(e===null||r===null)return null;let d=i((s,c)=>jsxs("div",{style:n.detailRow,children:[jsx("dt",{style:n.detailLabel,children:s}),jsx("dd",{style:n.detailValue,children:c})]},s),"row");return jsx("div",{style:l.sheetBackdrop,onClick:t,"data-testid":"marker-provenance-backdrop",children:jsxs("div",{ref:a.dialogRef,role:"dialog","aria-modal":"true","aria-label":sr.title,style:{...l.sheet,backgroundColor:n.sheetBg.backgroundColor},onClick:s=>s.stopPropagation(),onKeyDown:a.onKeyDown,"data-testid":"marker-provenance-sheet",children:[jsx("span",{style:l.sheetHandle,"aria-hidden":"true"}),jsxs("div",{style:l.sheetHeader,children:[jsx("h3",{style:l.sheetTitle,children:sr.title}),jsx("button",{type:"button",onClick:t,"aria-label":sr.close,style:l.iconButton,"data-testid":"marker-provenance-close",children:jsx("span",{style:l.closeGlyph,"aria-hidden":"true",children:"\xD7"})})]}),jsxs("div",{style:n.valueRow,children:[jsx("span",{style:n.markerName,children:e.name}),jsx("span",{style:n.latestValue,children:cr(r.value,e.unit,r.qualitativeResult)})]}),r.reviewed?jsx("span",{style:n.reviewed,children:sr.reviewed}):null,jsxs("dl",{style:n.details,children:[d(sr.collected,Q(r.at)),r.sourceClinic?d(sr.clinic,r.sourceClinic):null,d(sr.referenceRange,r.refLow!==null||r.refHigh!==null?Wn(r,e.unit):sr.noRange),r.docId?d(sr.sourceDocument,r.docId):null]}),r.reviewed?null:jsx("p",{style:n.unverified,children:sr.unverified}),o?jsx("button",{type:"button",onClick:o,"aria-label":sr.askA11y,style:{...l.pill,...l.pillAsk},"data-testid":"marker-provenance-ask",children:sr.ask}):null]})})}i(Hl,"MarkerProvenanceDialog");function Pi(){let e=ue();return useMemo(()=>vm(e),[e])}i(Pi,"useStyles");function vm(e){let{color:r,space:t,radius:o,type:n}=e,l=i((d,s,c,u="regular")=>({margin:0,...I(e,u),fontSize:d,lineHeight:`${Math.round(d*s)}px`,color:c}),"text"),a=t.md;return {page:{flex:"0 0 100%",scrollSnapAlign:"start",boxSizing:"border-box",padding:`0 ${t.sm}px`,listStyle:"none"},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.md,borderRadius:o.lg-t.xs/2,border:`1px solid ${r.brandBorder}`,backgroundColor:r.surface,padding:t.lg},headerRow:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:t.sm+t.xs/2},nameColumn:{flex:1,display:"flex",flexDirection:"column",gap:t.xs/2,minWidth:0},markerName:{...l(n.size.subtitle,n.lineHeight.snug,r.text.primary,"bold")},unit:{...I(e,"mono"),fontSize:n.size.tiny,lineHeight:`${n.size.body}px`,color:r.text.muted},latestRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:t.md},latestValue:{...l(n.size.verdict+t.xs,n.lineHeight.tight,r.text.primary,"bold")},latestValueDanger:{color:r.danger},latestDate:l(n.size.caption,n.lineHeight.normal,r.text.muted),trajectory:l(n.size.bodyTight,n.lineHeight.normal,r.text.muted),chartWrap:{position:"relative",display:"flex",flexDirection:"column",gap:t.sm},plot:{display:"block",width:"100%",height:140,borderRadius:o.sm,backgroundColor:r.surfaceCream,border:`1px solid ${r.borderHairlineGreen}`},dotLayer:{position:"absolute",left:0,right:0,top:0,height:140},dot:{position:"absolute",boxSizing:"border-box",width:a,height:a,borderRadius:a/2,marginLeft:-a/2,marginTop:-a/2,backgroundColor:r.brand,border:`2px solid ${r.surface}`,padding:0,cursor:"pointer"},dotDanger:{backgroundColor:r.danger},a11yTable:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",margin:0,padding:0,listStyle:"none"},tapHint:{...l(n.size.tiny,n.lineHeight.normal,r.text.placeholder),textAlign:"center"},singleHint:{...l(n.size.caption,n.lineHeight.normal,r.text.muted),textAlign:"center"},emptyBody:{...l(n.size.bodyTight,n.lineHeight.normal,r.text.muted),textAlign:"center",padding:`${t.xxl+t.xs}px 0`},carousel:{display:"flex",flexDirection:"column"},track:{display:"flex",overflowX:"auto",scrollSnapType:"x mandatory",margin:0,padding:0,listStyle:"none"},footer:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.sm,paddingTop:t.md},dots:{display:"flex",gap:t.xs+t.xs/2},dotIndicator:{display:"block",width:t.xs+t.xs/2,height:t.xs+t.xs/2,borderRadius:t.xs-1,backgroundColor:r.borderHairlineGreen},dotActive:{width:t.lg+t.xs/2,backgroundColor:r.brand},counter:{...I(e,"mono"),fontSize:n.size.tiny,lineHeight:`${n.size.body}px`,letterSpacing:n.letterSpacing.eyebrow/3,color:r.text.muted},sheetBg:{backgroundColor:r.surfaceCream},valueRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:t.md},reviewed:{alignSelf:"flex-start",borderRadius:o.pill,padding:`${t.xs}px ${t.sm+t.xs/2}px`,backgroundColor:r.badgeBgPositive,...l(n.size.tiny,n.lineHeight.normal,r.success,"medium")},details:{margin:0,display:"flex",flexDirection:"column",gap:t.md},detailRow:{display:"flex",flexDirection:"column",gap:t.xs/2},detailLabel:{...l(n.size.caption,n.lineHeight.normal,r.text.muted,"medium")},detailValue:{...l(n.size.body,n.lineHeight.normal,r.text.primary),marginLeft:0},unverified:l(n.size.caption,n.lineHeight.normal,r.text.muted)}}i(vm,"makeStyles");var Cm=Object.freeze({vaccination:"Vaccination",medication:"Medication",problem:"Problem",body_weight:"Weight",allergy:"Allergy",vital:"Vital",lab_result:"Lab result",parasite_prevention:"Preventive"}),Em="Given",xm=/^\d{4}-\d{2}-\d{2}/,Sm=" \xB7 ";function rt(e){let r=e.filter(t=>t!==null&&t.trim().length>0);return r.length>0?r.join(Sm):null}i(rt,"joinDetail");function wm(e,r){let t=e.label.trim();if(t.length>0)return t;let o=Cm[e.category];return o!==void 0?o:r(e.category)}i(wm,"rowTitle");function Vl(e,r){let t=wm(e,r.humanize),o=r.formatEntityValue(e.value,e.unit),n=o.trim().length>0?o:null,l=e.observedAt!==null&&e.observedAt.trim().length>0?r.formatRecordsDate(e.observedAt):null,a=l!==null&&l!=="-"?l:null;switch(e.category){case "vaccination":{let d=e.value!==null&&xm.test(e.value.trim()),s=d?r.formatRecordsDate(e.value):a;return s!==null&&s!=="-"?{title:t,detail:rt([`${Em} ${s}`,d?null:n])}:{title:t,detail:rt([n])}}case "medication":return {title:t,detail:rt([a])};case "problem":return {title:t,detail:rt([a])};case "body_weight":return {title:t,detail:rt([a])};case "allergy":return {title:t,detail:rt([a])};case "vital":return {title:t,detail:rt([n,a])};case "lab_result":return {title:t,detail:rt([n,a])};default:return {title:t,detail:rt([n,a])}}}i(Vl,"entityRowSummary");var H=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,r)=>`${Q(e)} to ${Q(r)}`,"dateRange"),documents:"Documents",uploadedDocument:me.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:me.labResults,visits:me.visits,physicalExams:me.physicalExams,visitNotes:me.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"})}),Wl=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 kt(e){return Object.prototype.hasOwnProperty.call(Wl,e)?Wl[e]:jr(e)}i(kt,"entityTypeLabel");var Xn=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function Gl(e){let r=Xn.filter(o=>e.includes(o)),t=e.filter(o=>!Xn.includes(o));return [...r,...t]}i(Gl,"orderEntityTypes");function Jn(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(Jn,"conflictSeverityMeta");function yn(e,r){if(!e)return null;let t=Date.parse(e);if(Number.isNaN(t))return null;let o=t<r-1440*60*1e3;return {label:o?H.overdue:H.due(Q(e)),overdue:o}}i(yn,"dueBadge");function Yl(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(Yl,"formatReferenceBand");var Xe=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 Kl(e,r){return Yr(e)?r==="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.":al(e)?r==="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.":r==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}i(Kl,"factEditErrorMessage");var km=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function Ti(e,r){if(Object.keys(r.edits).length===0&&r.removed.length===0)return e;let t=[];for(let o of e){let n=o.canonicalKey??null;if(n!==null&&r.removed.includes(n))continue;let l=n!==null?r.edits[n]:void 0;t.push(l===void 0?o:Object.freeze({...o,value:l}));}return Object.freeze(t)}i(Ti,"applyFactOverlay");function Di(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(Di,"isFactEditable");function _m(){return `records-fact-${Date.now().toString(36)}`}i(_m,"defaultFactKey");function Ii(e,r={}){let t=Ar(),{userRef:o}=Z(),[n,l]=useState(km),[a,d]=useState(false),[s,c]=useState(null),u=useMemo(()=>({}),[t,e,o]),[p,f]=useState(null),g=useCallback(()=>f(u),[u]),b=o!==null&&p!==u,m=useRef(false),C=useRef(r.newIdempotencyKey);C.current=r.newIdempotencyKey;let R=useCallback(()=>(C.current??_m)(),[]),x=useCallback((E,T,w)=>{if(d(false),!E.ok){if(T(),mt(E.error)){g();return}c(Kl(E.error,w));}},[g]),y=useCallback(async(E,T)=>{let w=E.canonicalKey??"",D=T.trim();if(m.current||w.length===0||D.length===0)return j(z("validationFailed",{retryable:false}));m.current=true,d(true),c(null);let A=n;l($=>({...$,edits:{...$.edits,[w]:D}}));let O=await t.editFact(e,{entityType:E.category,canonicalKey:w,correctedFields:yi(E.value,D),idempotencyKey:R()});return m.current=false,x(O,()=>l(A),"edit"),O},[t,e,n,x,R]),v=useCallback(async E=>{let T=E.canonicalKey??"";if(m.current||T.length===0)return j(z("validationFailed",{retryable:false}));m.current=true,d(true),c(null);let w=n;l(A=>({...A,removed:[...A.removed,T]}));let D=await t.removeFact(e,{entityType:E.category,canonicalKey:T,idempotencyKey:R()});return m.current=false,x(D,()=>l(w),"remove"),D},[t,e,n,x,R]),h=useCallback(()=>c(null),[]);return useMemo(()=>({overlay:n,busy:a,error:s,available:b,edit:y,remove:v,clearError:h}),[n,a,s,b,y,v,h])}i(Ii,"useRecordFactEdit");function Jl({entity:e,factEdit:r,children:t}){let{theme:o,styles:n}=G(),[l,a]=useState(false),d=useRef(null),s=e.label.trim()||Xe.detail;return jsxs("div",{style:{display:"flex",alignItems:"center",gap:o.space.sm},children:[jsx("div",{style:{flex:1,minWidth:0},children:t}),jsx("button",{ref:d,type:"button",onClick:()=>a(true),"aria-label":Xe.editA11y(s),style:n.iconButton,"data-testid":`fact-edit-open-${e.canonicalKey??e.key}`,children:jsx("span",{"aria-hidden":"true",style:{display:"block",width:o.space.md+o.space.xs/2,height:2,backgroundColor:o.color.brand,borderRadius:o.radius.pill,transform:"rotate(-45deg)"}})}),l?jsx(Dm,{entity:e,title:s,factEdit:r,onClose:()=>a(false),returnFocusTo:d}):null]})}i(Jl,"FactEditAffordance");function Dm({entity:e,title:r,factEdit:t,onClose:o,returnFocusTo:n}){let{theme:l,styles:a}=G(),d=Vt(true,o,n),[s,c]=useState(e.value??""),[u,p]=useState(null),[f,g]=useState(false);useEffect(()=>{t.clearError();},[t]);let b=s.trim().length>0&&s.trim()!==(e.value??"").trim(),m=u??t.error,C=t.busy,R=i(()=>{if(!b){p(Xe.noChange);return}p(null),t.edit(e,s).then(v=>{v.ok&&o();});},"submitEdit"),x=i(()=>{p(null),t.remove(e).then(v=>{v.ok?o():g(false);});},"submitRemove"),y=`fact-edit-${e.key}`;return jsx("div",{style:a.sheetBackdrop,onClick:o,children:jsxs("div",{ref:d.dialogRef,role:"dialog","aria-modal":"true","aria-label":Xe.title(r),style:a.sheet,onClick:v=>v.stopPropagation(),onKeyDown:d.onKeyDown,"data-testid":"fact-edit-sheet",children:[jsx("span",{style:a.sheetHandle,"aria-hidden":"true"}),jsxs("div",{style:a.sheetHeader,children:[jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:l.space.xs},children:[jsx("h3",{style:a.sheetTitle,children:Xe.title(r)}),jsx("p",{role:"status","aria-live":"polite",style:{...a.sheetHelper,...m?a.errorText:{}},children:m??Xe.helper})]}),jsx("button",{type:"button",onClick:o,"aria-label":Xe.close,style:a.iconButton,"data-testid":"fact-edit-close",children:jsx("span",{style:a.closeGlyph,"aria-hidden":"true",children:"\xD7"})})]}),jsx("label",{htmlFor:y,style:a.fieldLabel,children:e.label}),jsx("input",{id:y,style:a.field,value:s,onChange:v=>{c(v.target.value),p(null);},disabled:C,maxLength:512,"data-testid":"fact-edit-field"}),f?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:l.space.sm,padding:l.space.md,borderRadius:l.radius.md,backgroundColor:l.color.badgeBgCritical},"data-testid":"fact-edit-confirm-remove",children:[jsx("p",{style:a.bodyText,children:Xe.confirmRemove}),jsxs("div",{style:{display:"flex",gap:l.space.sm},children:[jsx(Y,{label:C?Xe.removing:Xe.removeConfirm,kind:"danger",busy:C,onClick:x,style:{flex:1},testID:"fact-edit-remove-confirm"}),jsx(Y,{label:Xe.keep,kind:"outline",disabled:C,onClick:()=>g(false),style:{flex:1},testID:"fact-edit-remove-cancel"})]})]}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:l.space.sm},children:[jsx(Y,{label:C?Xe.saving:Xe.save,busy:C,disabled:!b,onClick:R,testID:"fact-edit-save"}),jsx("button",{type:"button","aria-label":Xe.removeA11y(r),disabled:C,onClick:()=>{p(null),g(true);},style:{...a.pill,...a.pillLink,color:l.color.danger,...C?a.pillDisabled:{}},"data-testid":"fact-edit-remove",children:Xe.remove})]})]})})}i(Dm,"FactEditSheet");function Zl(e){return e.value!==null&&Number.isFinite(e.value)}i(Zl,"isFinitePoint");function ro(e){return e.display!==null&&e.display.length>0?e.display:e.value!==null?String(e.value):""}i(ro,"pointDisplay");function ed(e){let r=e.find(E=>E.points.some(Zl));if(r===void 0)return null;let t=r.points.filter(Zl),o=t[0];if(o===void 0)return null;let n=t.map(E=>E.value),l=Math.min(...n),a=Math.max(...n);l===a&&(l-=1,a+=1);let d=(a-l)*.18,s=l-d,c=a+d,u=c-s,p=6,f=t.length,g=t.map((E,T)=>({xPct:f<=1?50:p+T/(f-1)*(100-2*p),yPct:(c-E.value)/u*100})),b=(c-a)/u*100,m=(c-l)/u*100,C=t.reduce((E,T)=>T.value<E.value?T:E,o),R=t.reduce((E,T)=>T.value>E.value?T:E,o),x=t[t.length-1]??o,y=r.points[r.points.length-1]??x,v=ro(y),h=v.length>0?v:ro(x);return {label:r.label,heroDisplay:h,minDisplay:ro(C),maxDisplay:ro(R),firstDate:ii(r.points[0]?.at??null),lastDate:ii(y.at),points:g,bandTopPct:b,bandBottomPct:m}}i(ed,"buildTrendModel");function Im(e){let r=e.indexOf(":");return r<=0?null:e.slice(0,r)}i(Im,"entityTypeOf");function rd(e,r,t){let o=new Map,n=[];for(let d of e){let s=Im(d.key)??"",c=o.get(s);c===void 0?(o.set(s,[d]),n.push(s)):c.push(d);}let l=r.filter(d=>o.has(d)),a=n.filter(d=>!l.includes(d));return Object.freeze([...l,...a].map(d=>Object.freeze({entityType:d.length>0?d:null,label:d.length>0?t(d):null,series:Object.freeze([...o.get(d)??[]])})))}i(rd,"groupSeriesByEntityType");function td({series:e}){let r=ue(),t=useMemo(()=>qm(r),[r]),o=useMemo(()=>rd(e,Xn,kt),[e]);return o.length===0?null:jsxs("section",{"aria-label":H.careTimeline,style:t.section,children:[jsxs("div",{children:[jsx("h3",{style:t.sectionTitle,children:H.careTimeline}),jsx("p",{style:t.sectionSub,children:H.careTimelineSub})]}),o.map(n=>jsxs("div",{style:t.group,children:[n.label===null?null:jsx("p",{style:t.eyebrow,children:n.label}),n.series.map(l=>jsx(Om,{series:l,styles:t},l.key))]},n.entityType??"_"))]})}i(td,"TrendRangeCard");function Om({series:e,styles:r}){let t=useMemo(()=>ed([e]),[e]);if(t===null){let n=e.points[e.points.length-1]?.display??null;return jsxs("div",{style:r.card,children:[jsx("p",{style:r.eyebrow,children:e.label}),n!==null&&n.length>0?jsx("p",{style:r.hero,children:n}):null]})}return jsx(Am,{model:t,styles:r})}i(Om,"SeriesChart");function Am({model:e,styles:r}){let t=e.heroDisplay.length>0?`${e.label}, ${e.heroDisplay}`:e.label,o=Math.max(0,e.bandBottomPct-e.bandTopPct),n=e.points.length-1;return jsxs("div",{style:r.card,children:[jsxs("div",{role:"img","aria-label":t,children:[jsx("p",{style:r.eyebrow,children:e.label}),e.heroDisplay.length>0?jsx("p",{style:r.hero,children:e.heroDisplay}):null]}),jsxs("div",{"aria-hidden":"true",style:r.plot,children:[e.points.map((l,a)=>jsx("div",{style:{...r.guide,left:`${l.xPct}%`}},`g-${a}`)),jsx("div",{style:{...r.band,top:`${e.bandTopPct}%`,height:`${o}%`}}),e.points.map((l,a)=>jsx("div",{style:{...r.point,...a===n?r.pointLatest:null,left:`${l.xPct}%`,top:`${l.yPct}%`}},`pt-${a}`)),e.maxDisplay.length>0?jsx("span",{style:{...r.edgeLabel,top:`${e.bandTopPct}%`},children:e.maxDisplay}):null,e.minDisplay.length>0?jsx("span",{style:{...r.edgeLabel,top:`${e.bandBottomPct}%`},children:e.minDisplay}):null]}),e.firstDate.length>0||e.lastDate.length>0?jsxs("div",{"aria-hidden":"true",style:r.dates,children:[jsx("span",{children:e.firstDate}),jsx("span",{children:e.lastDate})]}):null]})}i(Am,"TrendChart");function qm(e){let{color:r,space:t,radius:o,type:n}=e,l=i((d,s)=>`${Math.round(d*s)}px`,"lh"),a=t.sm;return {section:{display:"flex",flexDirection:"column",gap:t.lg},sectionTitle:{margin:0,...I(e,"bold"),fontSize:n.size.bodyTight,lineHeight:l(n.size.bodyTight,n.lineHeight.tight),color:r.text.primary},sectionSub:{margin:`${t.xs}px 0 0`,...I(e,"regular"),fontSize:n.size.caption,lineHeight:l(n.size.caption,n.lineHeight.normal),color:r.text.muted},group:{display:"flex",flexDirection:"column",gap:t.sm},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.sm,padding:t.lg,borderRadius:o.md,backgroundColor:r.surfaceCream,border:`1px solid ${r.brandBorder}`},eyebrow:{margin:0,...I(e,"regular"),fontSize:n.size.caption,lineHeight:l(n.size.caption,n.lineHeight.normal),color:r.text.muted,letterSpacing:n.letterSpacing.eyebrow,textTransform:"uppercase",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},hero:{margin:0,...I(e,"bold"),fontSize:n.size.verdict,lineHeight:l(n.size.verdict,n.lineHeight.tight),color:r.text.primary,letterSpacing:n.letterSpacing.tight},plot:{position:"relative",height:t.xxl*3,marginTop:t.xs},guide:{position:"absolute",top:0,bottom:0,width:1,backgroundColor:r.borderHairlineGreen},band:{position:"absolute",left:t.xs,right:t.xs,borderRadius:o.sm,backgroundColor:r.brandSoft},point:{boxSizing:"border-box",position:"absolute",width:a,height:a,marginLeft:-(a/2),marginTop:-(a/2),borderRadius:o.pill,backgroundColor:r.brand,border:`1px solid ${r.surfaceCream}`},pointLatest:{backgroundColor:r.accent,borderColor:r.onAccent},edgeLabel:{position:"absolute",right:0,marginTop:-t.sm,...I(e,"medium"),fontSize:n.size.tiny,lineHeight:l(n.size.tiny,n.lineHeight.tight),color:r.text.muted,whiteSpace:"nowrap"},dates:{display:"flex",justifyContent:"space-between",...I(e,"regular"),fontSize:n.size.tiny,lineHeight:l(n.size.tiny,n.lineHeight.normal),color:r.text.muted}}}i(qm,"makeStyles");function to({record:e,depth:r,petName:t,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:a,nowMs:d}){let{theme:s,styles:c}=G(),u=d??Date.now(),p=useMemo(()=>a?Ti(e.entities,a.overlay):e.entities,[e.entities,a]),f=useMemo(()=>{let y=[],v=new Map;for(let h of p){let E=h.category.trim();if(E.length===0)continue;let T=v.get(E);T===void 0?(y.push(E),v.set(E,[h])):T.push(h);}return {order:Gl(y),groups:v}},[p]),g=Object.values(e.documents),b=a!==void 0&&a.available,m=i((y,v,h)=>l?jsx("button",{type:"button",onClick:()=>{let E=y();l(E.prompt,E.entityRef);},"aria-label":v,style:{...c.pill,...c.pillAsk,marginTop:s.space.lg,alignSelf:"flex-start"},"data-testid":h,children:v}):null,"ask"),C={display:"flex",flexDirection:"column",gap:s.space.lg+s.space.xs},R=i(y=>({...c.row,...y>0?c.rowDivider:{}}),"rowStyle"),x={...c.card,padding:`${s.space.md}px ${s.space.lg}px`,display:"flex",flexDirection:"column"};return jsxs(Fragment,{children:[jsxs("div",{style:C,children:[r&&r.conflicts.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-conflicts",children:[jsx(Tr,{title:H.needsAttention,count:r.conflicts.length}),[...r.conflicts].sort((y,v)=>Jn(y.severity).rank-Jn(v.severity).rank).map(y=>{let v=Jn(y.severity),h=jr(y.field??y.entityType);return jsxs("div",{style:{...x,borderColor:c.chipTones[v.tone].color,gap:s.space.sm},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.space.sm},children:[jsx("span",{style:{...c.rowTitle,...I(s,"bold"),flex:1},children:v.label}),jsx(dr,{label:h,tone:v.tone})]}),jsx("p",{style:c.rowDetail,children:H.conflictSub}),y.candidates.map((E,T)=>jsxs("div",{style:{borderTop:`1px solid ${s.color.borderHairlineGreen}`,paddingTop:s.space.sm},children:[jsx("p",{style:c.rowTitle,children:E.value}),jsx("p",{style:c.rowMuted,children:[E.docId?e.documents[E.docId]?.title??H.uploadedDocument:H.uploadedDocument,E.collectedAt?Q(E.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},T)),m(()=>Il(t,{scopeLabel:h,severity:y.severity,candidates:y.candidates.map(E=>({value:E.value,clinicName:E.docId?e.documents[E.docId]?.title??null:null}))},y.conflictId),H.askConflict,`records-ask-conflict-${y.conflictId}`)]},y.conflictId)})]}):null,r?.completeness?jsxs("section",{style:c.section,"data-testid":"record-section-completeness",children:[jsx(Tr,{title:H.whatsOnFile}),jsxs("div",{style:c.card,children:[jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:s.space.sm,padding:`${s.space.md}px 0`},children:[[H.coverage.labs,r.completeness.hasLabHistory],[H.coverage.vaccines,r.completeness.hasVaccinationHistory],[H.coverage.weight,r.completeness.hasWeightHistory],[H.coverage.vitals,r.completeness.hasVitalsHistory],[H.coverage.exams,r.completeness.hasPhysicalExamHistory],[H.coverage.procedures,r.completeness.hasProcedureHistory],[H.coverage.genetics,r.completeness.hasGeneticHistory],[H.coverage.parasite,r.completeness.hasParasitePreventionHistory],[H.coverage.reproductive,r.completeness.hasReproductiveHistory]].map(([y,v])=>jsx("span",{"aria-label":`${y}: ${v?H.onFile:H.noneOnFile}`,style:{...c.chip,...v?c.chipTones.positive:{backgroundColor:s.color.badgeBgNeutral,color:s.color.text.muted},fontSize:s.type.size.caption},children:y},y))}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.space.sm,paddingBottom:s.space.md},children:[jsx("span",{style:{...c.rowDetail,flex:1,marginTop:0},children:H.documentsOnFile(r.completeness.documentsIngested)}),r.completeness.documentsInReview>0?jsx(dr,{label:H.inReviewChip(r.completeness.documentsInReview),tone:"warning"}):null,Ai(r.completeness.heldTotal,r.completeness.entitiesPendingReview)>0?jsx("span",{"aria-label":H.beingVerifiedA11y(Ai(r.completeness.heldTotal,r.completeness.entitiesPendingReview)),children:jsx(dr,{label:H.beingVerified(Ai(r.completeness.heldTotal,r.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),r.completeness.earliestRecordAt||r.completeness.latestRecordAt?jsx("p",{style:{...c.rowDetail,paddingBottom:s.space.md},children:H.dateRange(r.completeness.earliestRecordAt,r.completeness.latestRecordAt)}):null,Object.entries(r.completeness.entitiesPendingReview).filter(([,y])=>y>0).length>0?jsxs("p",{style:{...c.rowMuted,paddingBottom:s.space.md},children:[H.pendingReview,Object.entries(r.completeness.entitiesPendingReview).filter(([,y])=>y>0).map(([y,v])=>`${kt(y)} (${v})`).join(", ")]}):null]})]}):null,g.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-documents",children:[jsx(Tr,{title:H.documents,count:g.length}),jsx("ul",{style:c.card,children:g.map((y,v)=>{let h=y.title?.trim()||H.uploadedDocument,E=y.receivedAt?Q(y.receivedAt):null,T=jsxs(Fragment,{children:[jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:h}),E?jsx("span",{style:{...c.rowDetail,display:"block"},children:E}):null]}),n?jsx(vt,{}):null]});return jsx("li",{style:R(v),children:n?jsx("button",{type:"button",onClick:()=>n({name:"contributions",docId:y.docId}),"aria-label":H.documentRowA11y(h),style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.space.md,width:"100%",background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit"},"data-testid":`records-document-row-${y.docId}`,children:T}):T},y.docId)})})]}):null,e.identity.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-identity",children:[jsx(Tr,{title:H.identity}),jsx("dl",{style:c.card,children:e.identity.map((y,v)=>jsxs("div",{style:R(v),children:[jsx("dt",{style:{...c.rowDetail,...I(s,"medium"),marginTop:0},children:y.label}),jsx("dd",{style:{...c.rowTitle,margin:0,textAlign:"right"},children:y.value})]},`${v}:${y.label}`))})]}):null,jsx(td,{series:e.entitySeries}),e.forwardLooking.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-upcoming",children:[jsx(Tr,{title:H.upcomingCare,count:e.forwardLooking.length}),jsx("ul",{style:c.card,children:e.forwardLooking.map((y,v)=>{let h=yn(y.dueAt,u);return jsxs("li",{style:R(v),children:[jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:y.title}),y.detail?jsx("span",{style:{...c.rowDetail,display:"block"},children:y.detail}):null]}),h?jsx(dr,{label:h.label,tone:h.overdue?"critical":"info"}):null]},`${y.title}-${v}`)})}),m(()=>Pl(t,e.forwardLooking.map(y=>{let v=yn(y.dueAt,u);return {label:y.title,relativeText:v?.label??"",tone:v?.overdue?"overdue":"upcoming"}}),e.petRef),H.askUpcomingCare,"records-ask-upcoming-care")]}):null,f.order.map(y=>{let v=f.groups.get(y)??[];if(v.length===0)return null;let h=kt(y);return jsxs("section",{style:c.section,"data-testid":`record-section-${y}`,children:[jsx(Tr,{title:h,count:v.length}),jsx("ul",{style:c.card,children:v.map((E,T)=>{let w=Vl(E,{formatEntityValue:Nt,formatRecordsDate:Q,humanize:jr}),D=w.detail,A=jsxs("div",{style:R(T),children:[jsxs("div",{style:{...c.rowMain,display:"flex",flexDirection:"column"},children:[jsx("span",{style:c.rowTitle,children:w.title}),D?jsx("span",{style:c.rowDetail,children:D}):null,m(()=>_l(t,{entityTypeLabel:h,title:w.title,detail:D},y,E.key),H.askEverfur,`records-ask-entity-${E.key}`)]}),E.status?jsx(dr,{label:jr(E.status)}):null]});return jsx("li",{children:b&&Di(E)&&a?jsx(Jl,{entity:E,factEdit:a,children:A}):A},E.key)})})]},y)}),r&&r.physicalExams.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-exams",children:[jsx(Tr,{title:H.physicalExams,count:r.physicalExams.length}),r.physicalExams.map(y=>jsxs("div",{style:x,children:[jsx("h4",{style:{...c.rowTitle,paddingTop:s.space.sm},children:y.observedOn?Q(y.observedOn):me.exam}),jsx("ul",{style:c.plainList,children:y.systems.map((v,h)=>{let E=v.findingStatus==="abnormal",T=E?me.abnormal:v.findingStatus==="not_examined"?me.notExamined:me.normal;return jsxs("li",{style:R(h),children:[jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:Lt(v.system)}),E&&v.finding?jsx("span",{style:{...c.rowDetail,display:"block"},children:v.finding}):null]}),jsx(dr,{label:T,tone:E?"warning":v.findingStatus==="not_examined"?"neutral":"positive"})]},v.system)})}),m(()=>Tl(t,{observedOn:y.observedOn?Q(y.observedOn):null,abnormal:y.systems.filter(v=>v.findingStatus==="abnormal").map(v=>({system:Lt(v.system),finding:v.finding??""}))},y.examId),H.askExam,`records-ask-exam-${y.examId}`)]},y.examId))]}):null,r&&r.clinicianNotes.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-notes",children:[jsx(Tr,{title:H.visitNotes,count:r.clinicianNotes.length}),r.clinicianNotes.map(y=>jsxs("div",{style:x,children:[jsx("h4",{style:{...c.rowTitle,paddingTop:s.space.sm},children:y.observedOn?Q(y.observedOn):me.visitNote}),jsx("dl",{style:c.plainList,children:y.sections.map((v,h)=>jsxs("div",{style:{padding:`${s.space.md}px 0`,...h>0?c.rowDivider:{}},children:[jsx("dt",{style:{...c.rowDetail,...I(s,"bold"),marginTop:0,textTransform:"uppercase"},children:zt(v.section)}),jsx("dd",{style:{...c.bodyText,marginLeft:0,...v.text?{}:{color:s.color.text.muted,fontStyle:"italic"}},children:v.text||me.notRecorded})]},`${v.section}:${h}`))}),m(()=>Dl(t,{observedOn:y.observedOn?Q(y.observedOn):null,sections:y.sections.map(v=>({label:zt(v.section),text:v.text}))},y.noteId),H.askVisit,`records-ask-note-${y.noteId}`)]},y.noteId))]}):null,o&&r&&r.labResults.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-labs",children:[jsx(Tr,{title:H.labResults,count:r.labResults.length}),jsx("ul",{style:c.card,children:r.labResults.map((y,v)=>{let h=Br(y.latest.status),E=ai(y.latest.at,y.trajectory,y.points.length);return jsxs("li",{style:R(v),children:[jsxs("span",{style:{...c.rowMain,display:"flex",flexDirection:"column"},children:[jsx("span",{style:c.rowTitle,children:y.name}),jsx("span",{style:c.rowValue,children:cr(y.latest.value,y.latest.unit,y.latest.qualitativeResult)}),E?jsx("span",{style:c.rowDetail,children:E}):null]}),jsx(dr,{label:h.label,tone:Vn(y.latest.status)})]},y.markerId)})})]}):null,r&&r.encounters.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-visits",children:[jsx(Tr,{title:H.visits,count:r.encounters.length}),jsx("ul",{style:c.card,children:r.encounters.map((y,v)=>{let h=[y.date?Q(y.date):null,y.clinicName,y.veterinarian].filter(E=>E&&E!=="-").join(" \xB7 ");return jsx("li",{style:R(v),children:jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:y.type?jr(y.type):me.visit}),h?jsx("span",{style:{...c.rowDetail,display:"block"},children:h}):null]})},y.encounterId)})})]}):null]}),jsx(pt,{disclaimer:e.disclaimer})]})}i(to,"RecordSections");function Ai(e,r){return e>0?e:Object.values(r).reduce((t,o)=>t+o,0)}i(Ai,"heldCount");var gn=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 id=Math.round(zr/(1024*1024)),Pt=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,r)=>`Uploading ${e+1} of ${r} records`,"uploading"),uploaded:i((e,r)=>`${e} of ${r} records uploaded`,"uploaded")});function ad(e){let r=Math.round(e.progress*100);switch(e.status){case "done":return Pt.done;case "failed":return Pt.failed;case "uploading":return e.progress>=1?Pt.verifying:`${r}%`;case "queued":return Pt.queued;default:return null}}i(ad,"uploadItemStatusLabel");function sd(e){if(e.length===0)return null;let r=i(l=>{let a=l.map(d=>d.name??"");return a.length<=3?a.join(", "):`${a.slice(0,3).join(", ")} and ${a.length-3} more`},"nameList"),t=e.filter(l=>l.reason==="too_large"),o=e.filter(l=>l.reason==="unsupported"),n=[];return o.length>0&&n.push(`${r(o)} ${o.length>1?"are not PDFs":"is not a PDF"}`),t.length>0&&n.push(`${r(t)} ${t.length>1?"are":"is"} over ${id} MB`),`Didn\u2019t upload: ${n.join("; ")}. We can only read PDFs up to ${id} MB right now.`}i(sd,"skippedFilesMessage");function ld(e){let r=[];for(let t of e)t.status==="skipped"&&t.skipReason!==null&&r.push({name:t.name,reason:t.skipReason});return r}i(ld,"skippedOf");var qi=[37,80,68,70,45],no="application/pdf,.pdf",Nm="application/octet-stream",Fm="file:web-document";async function Lm(e,r){let t=e.slice(0,r);try{return typeof t.arrayBuffer=="function"?new Uint8Array(await t.arrayBuffer()):await new Promise(o=>{let n=new FileReader;n.onload=()=>{o(n.result instanceof ArrayBuffer?new Uint8Array(n.result):new Uint8Array);},n.onerror=()=>o(new Uint8Array),n.readAsArrayBuffer(t);})}catch{return new Uint8Array}}i(Lm,"readHead");async function dd(e){if(e.size<qi.length)return false;let r=await Lm(e,qi.length);return qi.every((t,o)=>r[o]===t)}i(dd,"isPdfBlob");async function oo(e){let r=await dd(e),t=e.name,o=typeof t=="string"?t:void 0;return Object.freeze({uri:Fm,mimeType:r?it:Nm,sizeBytes:e.size,blob:e,...o!==void 0?{name:o}:{}})}i(oo,"fileToHandle");function Ni(e){let r=e.sizeBytes;return e.mimeType===it&&typeof r=="number"&&Number.isFinite(r)&&r>0&&r<=zr}i(Ni,"isUploadableHandle");function zm(e=document){return new Promise(r=>{let t=e.createElement("input");t.type="file",t.accept=no,t.hidden=true;let o=i(()=>{t.remove();},"done");t.addEventListener("change",()=>{let n=t.files?.[0];if(o(),n===void 0){r(null);return}oo(n).then(r);},{once:true}),t.addEventListener("cancel",()=>{o(),r(null);},{once:true}),e.body.appendChild(t),t.click();})}i(zm,"pickDocument");var Fr=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 cd({request:e,onRecovered:r,canUpload:t=false},o){let[n,l]=useState(""),[a,d]=useState(false),[s,c]=useState(null),[u,p]=useState(false),[f,g]=useState(null),b=useRef(false),m=useRef(false),C=useRef(0);useEffect(()=>(m.current=true,()=>{m.current=false,C.current+=1;}),[o]);let R=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,x=n.trim(),y=x.length<=320&&!Array.from(x).some(D=>D.charCodeAt(0)<=32||D.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(x),v=R.canUpdateClinicEmail===true&&x.length>0,h=R.canRetrySend===true&&!a&&!v,E=R.canUpdateClinicEmail===true&&!a&&y,T=R.canConvertToUpload===true&&t,w=i(async D=>{let A={retry:h,email:E,revoke:R.canRevoke===true&&u,convert:T};if(b.current||!m.current||!A[D])return;b.current=true,d(true),c(null);let O=C.current,$=i(()=>m.current&&O===C.current,"live");try{let L=D==="retry"?await o.retryRequest(e.id):D==="email"?await o.updateClinicEmail(e.id,x):D==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!$())return;if(!L.ok){c(L.error);return}if(L.value.id!==e.id||L.value.petRef!==e.petRef){c(z("internalError"));return}g({before:e.updatedAt,value:L.value}),l(""),p(!1),r();}catch{$()&&c(z("internalError"));}finally{b.current=false,$()&&d(false);}},"run");return {request:R,email:n,busy:a,error:s,canRetry:h,canUpdateEmail:E,canConvert:T,hasEmailEdit:v,confirmingRevoke:u&&R.canRevoke===true,emailInvalid:x.length>0&&!y,setEmail(D){b.current||(l(D),c(null));},retry:i(()=>w("retry"),"retry"),updateEmail:i(()=>w("email"),"updateEmail"),revoke:i(()=>w("revoke"),"revoke"),convert:i(()=>w("convert"),"convert"),askRevoke(){!b.current&&R.canRevoke===true&&p(true);},keepRequest(){b.current||p(false);}}}i(cd,"useRecordsRecovery");var $m=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],Um=["requested","awaiting_upload","records_received","processing","ready"],Bm=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],hn=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"}),fr=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"}),jm=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"}),Hm=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 Vm(e){return e.wireStatus??Hm[e.status]??"sent"}i(Vm,"wireStatusOf");function Wm(e,r){return e!=="awaiting_response"||r<=0?null:`${r} ${r===1?"reminder":"reminders"} sent`}i(Wm,"reminderProgressLabel");function Gm(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(Gm,"reachedRailIndex");function Ym(e){switch(e.dispatchStatus){case "sent":return fr.delivered;case "preparing":case "queued":case "sending":return fr.emailing;case "failed":return fr.bounced;default:return null}}i(Ym,"deliveryDetail");function Km(e,r){return Wm(r,e.reminderCount??0)??fr.waiting}i(Km,"awaitingDetail");function Rn(e){return e.source==="owner_provided"||!!e.convertedToUploadAt}i(Rn,"isOwnerSourcedRequest");function Qm(e,r,t){let o=Rn(r);switch(e){case "sent_to_clinic":return Ym(r);case "awaiting_clinic":return Km(r,t);case "awaiting_upload":return fr.upload;case "records_received":return o?fr.ownerAdded:fr.clinicSent;case "processing":return fr.preparing;case "ready":return fr.ready;default:return null}}i(Qm,"railDetail");function Xm(e,r){return !!e.reviewStartedAt||r==="parsing_failed"||r==="review_email_failed"}i(Xm,"tookReviewBranch");function Jm(e,r,t){if(e.key!=="processing"||!Xm(r,t))return [e];let o=t==="parsing_failed",n=t==="published",l=n?"done":o?"current":"done",a=n?"done":o?"upcoming":"current";return [{key:"parsing_failed",title:hn.parsing_failed,detail:fr.parsingFailed,at:null,state:l},{key:"manual_review",title:hn.manual_review,detail:fr.manualReview,at:r.reviewStartedAt??null,state:a}]}i(Jm,"expandProcessingPhase");function Zm(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(Zm,"convertedReachedIndex");function ud(e){return {key:"awaiting_clinic",title:fr.switchedTitle,detail:fr.switched,at:e.convertedToUploadAt??null,state:"done"}}i(ud,"convertedClinicSwitchEvent");function ef(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(ef,"ownerReachedIndex");function rf(e,r,t){switch(e){case "requested":return r.createdAt||null;case "awaiting_clinic":return r.lastReminderAt??null;case "processing":return r.parsingStartedAt??r.reviewStartedAt??null;case "ready":return t==="published"&&r.updatedAt||null;default:return null}}i(rf,"railTimestamp");function pd(e,r,t,o){return {key:e,title:hn[e],detail:Qm(e,r,t),at:rf(e,r,t),state:o}}i(pd,"railEvent");function tt(e,r){return {key:e,title:hn[e],detail:jm[e]??null,at:r.updatedAt||null,state:"failed"}}i(tt,"terminalEvent");function Li(e,r,t,o,n){return e.map((l,a)=>{let d=n?.(l)??null;if(d!==null)return d;let s=o==="published"||a<r?"done":a===r?"current":"upcoming";return pd(l,t,o,s)}).flatMap(l=>Jm(l,t,o))}i(Li,"walkRail");function zi(e){let r=Vm(e),t=i(n=>pd(n,e,r,"done"),"done");if(r==="revoked")return [t("requested"),tt("revoked",e)];if(e.convertedToUploadAt)return r==="failed"?[t("requested"),t("sent_to_clinic"),ud(e),t("awaiting_upload"),t("records_received"),tt("processing_failed",e)]:Li(Bm,Zm(r),e,r,n=>n==="awaiting_clinic"?ud(e):null);if(e.source==="owner_provided"){if(r==="failed"||r==="clinic_declined")return [t("requested"),t("awaiting_upload"),t("records_received"),tt("processing_failed",e)];let n=ef(r);return Li(Um,n<0?1:n,e,r)}if(r==="clinic_declined")return [t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),tt("clinic_declined",e)];if(r==="clinic_responded_no_records")return [t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),tt("clinic_no_records",e)];if(r==="failed"){let n=e.failureCode??null;return n==="no_response"?[t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),tt("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[t("requested"),tt("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),t("records_received"),tt("processing_failed",e)]:[t("requested"),tt("delivery_failed",e)]}let o=Gm(r);return Li($m,o<0?1:o,e,r)}i(zi,"buildRequestTimeline");var nf=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),io=24;function Gt({request:e}){let r=sf(),t=zi(e);return jsx("ol",{style:r.list,"aria-label":ce.timelineA11y,"data-testid":"records-timeline",children:t.map((o,n)=>jsx(of,{event:o,isLast:n===t.length-1,styles:r},o.key))})}i(Gt,"RequestTimeline");function of({event:e,isLast:r,styles:t}){let o=e.at?Q(e.at):null,n={...t.title,...e.state==="current"?t.titleCurrent:{},...e.state==="failed"?t.titleFailed:{},...e.state==="upcoming"?t.titleUpcoming:{}};return jsxs("li",{style:t.row,"data-testid":`records-timeline-${e.key}`,children:[jsxs("div",{style:t.railColumn,"aria-hidden":"true",children:[jsx(af,{state:e.state,styles:t}),r?null:jsx("div",{style:{...t.connector,...e.state==="done"?t.connectorDone:{}}})]}),jsxs("div",{style:t.body,children:[jsxs("div",{style:t.titleRow,children:[jsx("span",{style:n,children:e.title}),o&&e.at?jsx("time",{dateTime:e.at,style:t.date,children:o}):null]}),e.detail?jsx("span",{style:{...t.detail,...e.state==="upcoming"?t.detailUpcoming:{}},children:e.detail}):null,jsx("span",{style:t.srOnly,children:nf[e.state]})]})]})}i(of,"TimelineRow");function af({state:e,styles:r}){return e==="done"?jsx("div",{style:{...r.dot,...r.dotDone},children:"\u2713"}):e==="failed"?jsx("div",{style:{...r.dot,...r.dotFailed},children:"!"}):e==="current"?jsx("div",{style:{...r.dot,...r.dotCurrent},children:jsx("div",{style:r.dotCurrentCore})}):jsx("div",{style:{...r.dot,...r.dotUpcoming}})}i(af,"Dot");function sf(){let e=ue();return useMemo(()=>lf(e),[e])}i(sf,"useStyles");function lf(e){let{color:r}=e,t={boxSizing:"border-box",width:io,height:io,borderRadius:io/2,display:"flex",alignItems:"center",justifyContent:"center",...I(e,"bold"),fontSize:12,lineHeight:"14px"};return {list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},row:{display:"flex",alignItems:"flex-start",gap:12},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",alignSelf:"stretch",width:io,flexShrink:0},body:{flex:1,minWidth:0,paddingBottom:18,display:"flex",flexDirection:"column",gap:2},titleRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},dot:t,dotDone:{backgroundColor:r.brand,color:r.surface},dotFailed:{backgroundColor:r.danger,color:r.surface},dotCurrent:{border:`2px solid ${r.brand}`,backgroundColor:r.surface},dotCurrentCore:{width:10,height:10,borderRadius:5,backgroundColor:r.brand},dotUpcoming:{border:`2px solid ${r.borderHairlineGreen}`,backgroundColor:r.surface},connector:{width:2,flex:1,minHeight:22,backgroundColor:r.borderHairlineGreen,margin:"2px 0"},connectorDone:{backgroundColor:r.brand},title:{flex:1,...I(e,"bold"),fontSize:14,lineHeight:"18px",color:r.text.primary},titleCurrent:{color:r.brand},titleFailed:{color:r.danger},titleUpcoming:{color:r.text.muted,...I(e,"regular")},date:{...I(e,"regular"),fontSize:12,lineHeight:"16px",color:r.text.muted},detail:{...I(e,"regular"),fontSize:13,lineHeight:"17px",color:r.text.muted},detailUpcoming:{opacity:.7},srOnly:{position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0}}}i(lf,"makeStyles");var pf=300,mf=900,fd=120,yd=44,gd=40,bd=24,ff=3;function yt(e,r,t){let o=Vr(e,t);switch(o.kind){case "consent_required":return jsx(yf,{onGrant:r});case "consent_unavailable":return jsx(er,{label:W.consentRequired,glyph:"empty"});case "session_required":return jsx(er,{label:W.sessionRequired,glyph:"empty"});case "withheld":return jsx(er,{label:W.recordUnavailable,glyph:"withheld"});case "pet_not_found":case "error":return jsx(gf,{error:o.error,onRetry:e.refresh});default:return at(o)}}i(yt,"renderErrorFamily");function hd(){let{theme:e,styles:r}=Kt(),[t,o]=useState(false),n=useRef(null);useEffect(()=>{let a=setTimeout(()=>o(true),pf);return ()=>clearTimeout(a)},[]);let l=t&&!e.motion.reducedMotion;return useEffect(()=>{let a=n.current;if(!l||a===null||typeof a.animate!="function")return;let d=a.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:mf,iterations:1/0});return ()=>d.cancel()},[l]),jsx("div",{role:"status","aria-busy":"true","aria-label":W.loading,style:r.centered,children:t?jsx("div",{ref:n,"aria-hidden":"true",style:r.spinner}):null})}i(hd,"LoadingState");function Rd({records:e}){let{styles:r}=Kt(),t=e.uploadQueue;if(t.length===0)return null;let o=t.filter(a=>a.status!=="skipped"),n=o.filter(a=>a.status==="done").length,l=sd(ld(t));return jsxs("div",{style:r.card,"data-testid":"records-upload-queue",children:[l!==null?jsx("p",{role:"alert",style:r.errorText,children:l}):null,o.length>0?jsx("ul",{"aria-live":"polite","aria-label":e.isUploading?Pt.uploading(n,o.length):Pt.uploaded(n,o.length),style:{listStyle:"none",margin:0,padding:0},children:o.map(a=>{let d=Math.round(a.progress*100);return jsxs("li",{style:r.row,"data-testid":`records-upload-file-${a.status}`,children:[jsx("span",{style:r.rowLabel,children:a.name??""}),jsx("span",{style:r.rowValue,children:ad(a)}),a.status==="uploading"?jsx("progress",{max:100,value:d,style:{width:"100%"}}):null,a.status==="failed"&&a.error?jsx("span",{style:r.timelineMeta,children:a.error.displayMessage}):null]},a.key)})}):null]})}i(Rd,"UploadQueue");function yf({onGrant:e}){let{styles:r}=Kt();return jsxs("div",{role:"alert","aria-live":"assertive",style:r.centered,children:[jsx("p",{style:r.alertText,children:W.consentRequired}),jsx("button",{type:"button",onClick:e,style:r.primaryButton,children:W.allow})]})}i(yf,"ConsentRequiredState");function er({label:e,glyph:r}){let{styles:t}=Kt();return jsxs("div",{role:"alert","aria-live":"assertive",style:t.centered,children:[jsx("div",{"aria-hidden":"true",style:r==="withheld"?t.withheldGlyph:t.emptyGlyph}),jsx("p",{style:t.alertText,children:e})]})}i(er,"AlertState");function gf({error:e,onRetry:r}){let{styles:t}=Kt();return jsxs("div",{role:"alert","aria-live":"assertive",style:t.centered,children:[jsx("p",{style:t.errorText,children:e.displayMessage}),e.retryable?jsx("button",{type:"button",onClick:r,style:t.primaryButton,children:W.retry}):null]})}i(gf,"ErrorState");function vd({call:e,prompt:r}){let{styles:t}=Kt(),o=r.trim().length>0?r:gn.fallbackPrompt;return jsxs("div",{style:t.callCard,children:[jsx("p",{style:t.timelineLabel,children:gn.heading}),jsx("p",{style:t.timelineMeta,children:o}),jsx("a",{href:e.dial,"aria-label":gn.callAt(e.phone),style:t.linkButton,"data-testid":"records-call-clinic",children:gn.call})]})}i(vd,"ClinicCallCard");function Kt(){let e=ue(),r=useMemo(()=>bf(e),[e]);return {theme:e,styles:r}}i(Kt,"useRecordsTheme");function bf(e){let{color:r,space:t,radius:o,type:n,slots:l}=e,a=i((m,C)=>`${Math.round(m*C)}px`,"lh"),d=`1px solid ${r.brandBorder}`,s=Pr(l.recordCard,1),c=Ur(l.recordCard),u=i((m,C,R,x="regular")=>({margin:0,...I(e,x),fontSize:m,lineHeight:a(m,C),color:R}),"text"),p=i((m,C,R,x="regular")=>({...u(m,C,R,x),...c}),"inCard"),f={boxSizing:"border-box",minHeight:yd,minWidth:yd,padding:`${t.md}px ${t.xl}px`,borderRadius:o.pill,...I(e,"bold"),fontSize:n.size.body,letterSpacing:n.letterSpacing.tight},g={boxSizing:"border-box",width:gd,height:gd},b=e.brightness==="dark"?r.errorRed:r.danger;return {container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:fd,height:"100%",backgroundColor:r.background,color:r.text.primary,...I(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:fd,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:t.lg,padding:t.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:bd,height:bd,borderRadius:o.pill,border:`${ff}px solid ${r.brandSofter}`,borderTopColor:r.brand},emptyGlyph:{...g,borderRadius:o.lg,backgroundColor:r.brandSoft,border:d},withheldGlyph:{...g,borderRadius:o.sm,backgroundColor:r.badgeBgCaution,border:`1px solid ${r.cautionAccent}`},alertText:u(n.size.subtitle,n.lineHeight.snug,r.text.secondary),errorText:u(n.size.subtitle,n.lineHeight.snug,b),primaryButton:{...f,border:0,cursor:"pointer",backgroundColor:r.primary,color:r.onPrimary,...Pr(l.primaryButton),...Ur(l.primaryButton)},disabledButton:{...f,border:d,cursor:"default",backgroundColor:r.surfaceSubtle,color:r.text.muted},list:{display:"flex",flexDirection:"column",gap:t.md,padding:t.lg},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.xs,padding:`${t.md}px ${t.lg}px`,borderRadius:o.md,backgroundColor:r.surfaceCream,border:d,...s},cardTitle:{...p(n.size.heading,n.lineHeight.snug,r.text.primary,"bold"),letterSpacing:n.letterSpacing.tight},callCard:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:t.sm,padding:t.md,borderRadius:o.md,backgroundColor:r.surfaceCream,border:d,...s},linkButton:{...f,display:"inline-flex",alignItems:"center",justifyContent:"center",alignSelf:"flex-start",textDecoration:"none",border:0,backgroundColor:r.primary,color:r.onPrimary,...Pr(l.primaryButton),...Ur(l.primaryButton)},timelineLabel:{...p(n.size.subtitle,n.lineHeight.snug,r.text.secondary,"bold")},timelineMeta:p(n.size.bodyTight,n.lineHeight.normal,r.text.muted),row:{display:"flex",justifyContent:"space-between",gap:t.md,padding:`${t.xs}px 0`,borderBottom:`1px solid ${r.borderHairlineGreen}`},rowLabel:p(n.size.body,n.lineHeight.normal,r.text.muted),rowValue:{...p(n.size.body,n.lineHeight.normal,r.text.primary,"medium"),textAlign:"right"},disclaimer:u(n.size.caption,n.lineHeight.normal,r.text.muted)}}i(bf,"makeStyles");var Cf=i((e,r)=>e.getRecordDepth(r),"readDepth"),Ef=i(e=>!e.available,"depthEmpty");function $i(e){let{style:r,className:t,renderPending:o,...n}=Te(e,["onNavigate","onBack","onAsk"]),{userRef:l}=Z(),{styles:a}=G();return jsx(De,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,$e),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-dashboard",children:[l===null?jsx("div",{style:a.body,children:jsx(er,{label:W.sessionRequired,glyph:"empty"})}):jsx(xf,{...n}),jsx(Ie,{})]})})}i($i,"EverfurRecordsDashboard");function xf({petRef:e,petName:r,controller:t,consentVersion:o,onNavigate:n,onBack:l,onAsk:a}){let{theme:d,styles:s}=G(),c=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),u=Ke(c),p=vi(e),f=qr(e,Cf,Ef),[g,b]=useState(null),m=useCallback((S,q)=>b({marker:S,point:q}),[]),C=et(o,u.consent),R=i(()=>{let S=Hr(o,u.consent);S.length!==0&&u.grantConsent(S,`records-consent-${Date.now().toString(36)}`);},"onGrant"),x=p.markers?.markers??[],y=x.length>0,v=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,h=Nn(u.requests,e),E=zo({hasMarkers:y,requests:u.requests,petRef:e}),T=Mo({recordLoading:u.status==="loading",hasFullRecord:v,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:y,requestsLoading:u.status==="loading",dashboardState:E,drivingRequest:h}),w=p.markers?.disclaimer??u.record?.disclaimer??"",D=i(()=>{u.refresh(),p.refresh(),f.refresh();},"retryAll"),A=f.value!==null&&!f.value.withheld&&f.value.available?f.value:null,O=we(r),$=a&&p.markers?.summary?()=>{let S=Sl(r,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);a(S.prompt,S.entityRef);}:void 0,L=a?S=>{let q=xl(r,{canonicalName:S.name,markerId:S.markerId,latestValueText:S.latest?cr(S.latest.value,S.unit,S.latest.qualitativeResult):null,statusText:S.latest?Br(S.latest.status).label:null,trajectoryText:Ft(S.trajectory,S.points.length),meaningText:S.meaning});a(q.prompt,q.entityRef);}:void 0,V=a&&g?()=>{let{marker:S,point:q}=g,P=wl(r,{canonicalName:S.name,valueText:cr(q.value,S.unit,q.qualitativeResult),collectedAt:Q(q.at),sourceClinic:q.sourceClinic,referenceText:q.refLow!==null||q.refHigh!==null?Wn(q,S.unit):null,flagged:q.status==="above"?"above":q.status==="below"?"below":null,reviewed:q.reviewed,entityId:q.docId??S.markerId});b(null),a(P.prompt,P.entityRef);}:void 0,J=i((S,q,P)=>jsxs("button",{type:"button",onClick:q,"aria-label":S,style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",borderRadius:d.radius.md,border:`1px solid ${d.color.brandBorder}`,backgroundColor:d.color.surface,padding:d.space.lg,cursor:"pointer",font:"inherit",color:d.color.text.primary,textAlign:"left"},"data-testid":P,children:[jsxs("span",{style:{display:"flex",alignItems:"center",gap:d.space.md},children:[jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:18,height:18,borderRadius:d.radius.xs,backgroundColor:d.color.brandSoft,border:`1px solid ${d.color.brandBorder}`}}),jsx("span",{style:{...s.rowTitle},children:S})]}),jsx(vt,{})]}),"actionRow"),Ce=jsxs(Fragment,{children:[p.markers?.summary?jsx("div",{style:s.inset,children:jsx(Fl,{summary:p.markers.summary,onAsk:$,testID:"dashboard-marker-summary"})}):null,jsx("p",{style:s.lead,children:ar.lead(r)}),jsx(jl,{markers:x,onPointPress:m,onAsk:L})]}),re=i(S=>n?jsxs("div",{style:{...s.inset,display:"flex",flexDirection:"column",gap:d.space.sm+d.space.xs/2},children:[S?J(ar.viewFullRecord,()=>n({name:"record"}),"dashboard-full-record-action"):null,J(ar.viewTimeline,()=>n({name:"timeline"}),"dashboard-timeline-action")]}):null,"actions"),k;if(u.status==="error"){let S=Vr(u,C);k=S.kind==="error"||S.kind==="pet_not_found"?jsx(Ue,{variant:Ze(S.error),message:S.error.displayMessage,onAction:S.error.retryable?D:void 0,testID:"dashboard-error"}):yt(u,R,C);}else switch(T){case "loading":k=jsx(Mt,{testID:"dashboard-loading"});break;case "record":k=jsxs("div",{style:s.contentTight,"data-testid":"dashboard-record",children:[y?Ce:p.status==="error"?jsx("div",{style:s.inset,children:J(ar.retryMarkers,D,"dashboard-markers-retry")}):null,jsx("div",{style:s.inset,children:u.record?jsx(to,{record:u.record,depth:A,petName:r,showLabs:!y,onNavigate:n,onAsk:a}):null}),re(true)]});break;case "error":{let S=p.error??u.error;k=jsx(Ue,{variant:Ze(S),message:S?.displayMessage,onAction:S?.retryable?D:void 0,testID:"dashboard-error"});break}case "in_progress":k=jsxs("div",{style:s.content,"data-testid":"dashboard-in-progress",children:[h?jsx(Sf,{request:h,petName:O,onOpen:n?()=>n({name:"request",requestId:h.id}):void 0,onAsk:a?()=>{let S=kl(r,{clinicName:h.clinicName??null,statusLabel:mn(h),status:h.status,heldItemCount:h.heldItemCount},h.id);a(S.prompt,S.entityRef);}:void 0}):null,jsx(pt,{disclaimer:w})]});break;case "none":k=jsxs("div",{style:s.content,"data-testid":"dashboard-request-prompt",children:[jsxs("section",{style:{borderRadius:d.radius.sm,backgroundColor:d.color.surfaceCream,border:`1px solid ${d.color.borderRingCream}`,padding:`${d.space.lg+d.space.xs/2}px ${d.space.lg+d.space.xs}px`,display:"flex",flexDirection:"column",gap:d.space.sm},children:[jsx("h3",{style:{...s.sectionTitle,fontSize:d.type.size.subtitle,color:d.color.brand},children:Rt.title(r)}),jsx("p",{style:s.bodyText,children:Rt.body}),n?jsxs(Fragment,{children:[jsx(Y,{label:Rt.requestFromClinic,ariaLabel:Rt.requestFromClinicA11y(r),onClick:()=>n({name:"clinicPicker"}),testID:"dashboard-request-prompt-clinic"}),jsx(Y,{label:Rt.uploadDocument,kind:"outline",ariaLabel:Rt.uploadDocumentA11y(r),onClick:()=>n({name:"upload"}),testID:"dashboard-request-prompt-upload"})]}):null]}),jsx(pt,{disclaimer:w})]});break;case "labs_only":k=jsxs("div",{style:s.contentTight,"data-testid":"dashboard-labs-only",children:[Ce,jsx("div",{style:s.inset,children:jsx(pt,{disclaimer:w})}),re(false)]});break;default:k=at(T);}return jsxs(Fragment,{children:[jsx(We,{title:ar.title,onBack:l,testID:"dashboard-header",right:n?jsx("button",{type:"button",onClick:()=>n({name:"timeline"}),"aria-label":ar.openTimeline,style:s.iconButton,"data-testid":"dashboard-timeline-link",children:jsx("span",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:4},children:[0,1,2].map(S=>jsx("span",{style:{display:"block",width:18,height:2,borderRadius:2,backgroundColor:d.color.brand}},S))})}):void 0}),jsx("div",{style:s.body,children:k}),jsx(Hl,{marker:g?.marker??null,point:g?.point??null,onClose:()=>b(null),onAsk:V})]})}i(xf,"DashboardBody");function Sf({request:e,petName:r,onOpen:t,onAsk:o}){let{theme:n,styles:l}=G(),a=e.clinicName?.trim()||qt.title(r),d=mn(e),s=jsxs("div",{style:{display:"flex",flexDirection:"column",gap:n.space.lg},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.space.sm},children:[jsx("span",{style:{...l.rowTitle,...I(n,"bold"),fontSize:n.type.size.subtitle},children:a}),t?jsx(vt,{}):null]}),jsx(Gt,{request:e}),d.length>0?jsx("p",{style:l.statusCard,children:d}):null]});return jsxs("section",{"aria-label":t?void 0:qt.a11y(r),style:{...l.creamCard,backgroundColor:n.color.surface,padding:n.space.lg+n.space.xs/2,gap:n.space.lg},"data-testid":"dashboard-in-progress-card",children:[t?jsx("button",{type:"button",onClick:t,"aria-label":qt.openA11y(r,d),style:{background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit",width:"100%"},"data-testid":"dashboard-in-progress-open",children:s}):s,o?jsx(Y,{label:qt.ask,kind:"ask",ariaLabel:qt.askA11y,onClick:o,testID:"dashboard-in-progress-ask"}):null]})}i(Sf,"InProgressCard");var so=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function Cd(e){if(!e)return null;let r=Date.parse(e);return Number.isNaN(r)?null:r}i(Cd,"toMillis");function Ed(e){let r=[...e.visits.map((t,o)=>({key:`visit-${o}-${t.visitId}`,kind:"visit",kindLabel:me.kind.visit,at:t.visitDate,date:Q(t.visitDate),title:t.summary??me.clinicVisit,detail:t.veterinarian?me.doctor(t.veterinarian):null,docId:t.docId})),...e.vaccines.map((t,o)=>{let n=[];return t.lot&&n.push(me.lot(t.lot)),t.expiresOn&&n.push(me.expires(Q(t.expiresOn))),{key:`vaccine-${o}-${t.vaccineId}`,kind:"vaccine",kindLabel:me.kind.vaccine,at:t.administeredOn,date:Q(t.administeredOn),title:t.product||me.kind.vaccine,detail:n.length?n.join(" \xB7 "):null,docId:t.docId}}),...e.weights.map((t,o)=>({key:`weight-${o}-${t.weightId}`,kind:"weight",kindLabel:me.kind.weight,at:t.observedOn,date:Q(t.observedOn),title:Ms(t.weightKg),detail:null,docId:t.docId})),...e.medications.map((t,o)=>{let n=[t.dose,t.route,t.frequency].filter(l=>!!l);return {key:`medication-${o}-${t.medicationId}`,kind:"medication",kindLabel:me.kind.medication,at:t.startedOn,date:Q(t.startedOn),title:t.drugName||me.kind.medication,detail:n.length?n.join(" \xB7 "):null,docId:t.docId}})];return Object.freeze(r.sort((t,o)=>{let n=Cd(t.at),l=Cd(o.at);return n===null&&l===null?so[t.kind]-so[o.kind]:n===null?1:l===null?-1:l!==n?l-n:so[t.kind]-so[o.kind]}))}i(Ed,"buildTimelineRows");var Tf=300,xd=120,Sd=44,Df=i((e,r)=>e.getTimeline(r),"readTimeline"),If=i(e=>e.isEmpty,"timelineEmpty");var Of=i(e=>e.contributions.length===0,"contributionsEmpty");function wd({petRef:e,style:r,className:t,onBack:o}){let n=qr(e,Df,If);return jsx(_d,{state:n,style:r,className:t,onBack:o,header:jsx(We,{title:me.timeline,onBack:nn(o),testID:"timeline-header"}),loading:jsx(Gs,{testID:"timeline-loading"}),empty:jsx(Ue,{variant:"no_records",testID:"timeline-empty"}),render:l=>jsx(Nf,{timeline:l})})}i(wd,"EverfurRecordsTimeline");function kd({petRef:e,docId:r,style:t,className:o,onBack:n}){let l=useCallback((s,c)=>s.getDocumentContributions(c,r),[r]),a=qr(e,l,Of,r),d=a.value?.document?.title?.trim()||me.uploadedDocument;return jsx(_d,{state:a,style:t,className:o,onBack:n,header:jsx(We,{title:d,onBack:nn(n),testID:"contributions-header"}),empty:jsx(Ue,{variant:"no_records",testID:"contributions-empty"}),render:s=>jsx(Ff,{view:s})})}i(kd,"EverfurDocumentContributions");function _d({state:e,style:r,className:t,header:o,loading:n,empty:l,render:a,onBack:d}){let{styles:s}=Ui(),{userRef:c}=Z();return jsx(De,{capability:"records",style:r,className:t,...Oe(nn(d),$e),children:jsxs("div",{className:t,style:{...s.container,...r},children:[o??null,jsx("div",{style:s.body,children:c===null?jsx("p",{role:"alert",style:s.alertText,children:W.sessionRequired}):Af(e,a,s,n,l)}),jsx(Ie,{})]})})}i(_d,"DepthSurface");function Af(e,r,t,o,n){switch(e.status){case "loading":return o??jsx(qf,{styles:t});case "empty":return n??jsx("div",{style:t.centered,children:jsx("div",{role:"img","aria-label":W.empty,style:t.emptyGlyph})});case "error":return e.error?jsx(Ue,{variant:Ze(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:r(e.value);default:return null}}i(Af,"renderState");function qf({styles:e}){let[r,t]=useState(false);return useEffect(()=>{let o=setTimeout(()=>t(true),Tf);return ()=>clearTimeout(o)},[]),jsx("div",{role:"status","aria-busy":"true","aria-label":W.loading,style:e.centered,children:r?jsx("div",{"aria-hidden":"true",style:e.spinner}):null})}i(qf,"LoadingState");function Nf({timeline:e}){let{styles:r}=Ui(),t=Ed(e);return jsxs("section",{"aria-label":me.timeline,style:r.timelineList,children:[e.disclaimer.length>0?jsx("p",{role:"note","aria-label":ar.important(e.disclaimer),style:r.timelineBand,children:e.disclaimer}):null,jsx("ul",{style:r.plainList,children:t.map((o,n)=>jsx("li",{style:n>0?r.timelineSeparated:void 0,"data-testid":`records-timeline-row-${o.kind}`,children:jsxs("div",{style:r.timelineRow,"aria-label":[o.kindLabel,o.date,o.title,o.detail].filter(Boolean).join(", "),children:[jsx("span",{"aria-hidden":"true",style:r.timelineBubble}),jsxs("div",{style:r.timelineBody,children:[jsxs("div",{style:r.topLine,children:[jsx("span",{style:r.timelineKind,children:o.kindLabel}),jsx("span",{style:r.date,children:o.date})]}),jsx("span",{style:r.timelineTitle,children:o.title}),o.detail?jsx("span",{style:r.rowDetail,children:o.detail}):null]})]})},o.key))})]})}i(Nf,"TimelineBody");function Ff({view:e}){let{styles:r}=Ui();return jsxs("section",{"aria-label":W.records,style:r.list,children:[e.document?.receivedAt?jsx("p",{style:r.rowDetail,children:Q(e.document.receivedAt)}):null,jsx("dl",{style:r.card,children:e.contributions.map(t=>jsxs("div",{style:r.row,children:[jsx("dt",{style:r.rowTitle,children:t.label}),jsx("dd",{style:r.rowValue,children:Nt(t.value,t.unit)}),t.observedAt?jsx("dd",{style:r.rowDetail,children:Q(t.observedAt)}):null]},t.key))})]})}i(Ff,"ContributionsBody");function Ui(){let e=ue(),r=useMemo(()=>Lf(e),[e]);return {theme:e,styles:r}}i(Ui,"useDepthTheme");function Lf(e){let{color:r,space:t,radius:o,type:n,slots:l}=e,a=i((f,g)=>`${Math.round(f*g)}px`,"lh"),d=i((f,g,b,m="regular")=>({margin:0,...I(e,m),fontSize:f,lineHeight:a(f,g),color:b}),"text"),s=Ur(l.recordCard),c=i((f,g,b,m="regular")=>({...d(f,g,b,m),...s}),"inCard"),u=`1px solid ${r.brandBorder}`,p=e.brightness==="dark"?r.errorRed:r.danger;return {container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:xd,height:"100%",backgroundColor:r.background,color:r.text.primary,...I(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:xd,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:t.lg,padding:t.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:24,height:24,borderRadius:o.pill,border:`3px solid ${r.brandSofter}`,borderTopColor:r.brand},emptyGlyph:{boxSizing:"border-box",width:40,height:40,borderRadius:o.lg,backgroundColor:r.brandSoft,border:u},alertText:d(n.size.subtitle,n.lineHeight.snug,r.text.secondary),errorText:d(n.size.subtitle,n.lineHeight.snug,p),primaryButton:{boxSizing:"border-box",minHeight:Sd,minWidth:Sd,padding:`${t.md}px ${t.xl}px`,borderRadius:o.pill,...I(e,"bold"),fontSize:n.size.body,border:0,cursor:"pointer",backgroundColor:r.primary,color:r.onPrimary,...Pr(l.primaryButton),...Ur(l.primaryButton)},list:{display:"flex",flexDirection:"column",gap:t.md,padding:t.lg},section:{display:"flex",flexDirection:"column",gap:t.sm},heading:{...d(n.size.heading,n.lineHeight.snug,r.text.primary,"bold")},card:{boxSizing:"border-box",listStyle:"none",display:"flex",flexDirection:"column",gap:t.sm,margin:0,padding:t.md,borderRadius:o.md,backgroundColor:r.surfaceCream,border:u,...Pr(l.recordCard,1)},plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:t.sm},row:{display:"flex",flexDirection:"column",gap:t.xs,padding:`${t.xs}px 0`,borderBottom:`1px solid ${r.borderHairlineGreen}`},topLine:{display:"flex",justifyContent:"space-between",gap:t.md},kindLabel:{...c(n.size.caption,n.lineHeight.normal,r.text.muted,"medium")},date:c(n.size.caption,n.lineHeight.normal,r.text.muted),rowTitle:{...c(n.size.body,n.lineHeight.normal,r.text.primary,"bold")},rowValue:{...c(n.size.body,n.lineHeight.normal,r.text.primary,"medium")},rowDetail:c(n.size.bodyTight,n.lineHeight.normal,r.text.muted),rowMuted:{...c(n.size.bodyTight,n.lineHeight.normal,r.text.muted),opacity:.7},chip:{...d(n.size.caption,n.lineHeight.normal,r.text.primary),alignSelf:"flex-start",padding:`${t.xs}px ${t.sm}px`,borderRadius:o.pill},chipNeutral:{backgroundColor:r.badgeBgNeutral},chipCaution:{backgroundColor:r.badgeBgCaution},chipCritical:{backgroundColor:r.badgeBgCritical},disclaimer:d(n.size.caption,n.lineHeight.normal,r.text.muted),timelineList:{display:"flex",flexDirection:"column",paddingBottom:t.xxl},timelineBand:{...d(n.size.caption,n.lineHeight.normal,r.text.secondary),borderRadius:o.md-t.xs/2,padding:t.md,backgroundColor:r.brandSoft,margin:`${t.xs}px ${t.lg}px ${t.md}px`},timelineSeparated:{borderTop:`1px solid ${r.brandBorder}`,marginLeft:di,paddingLeft:0},timelineRow:{display:"flex",gap:t.md,padding:`${t.md+t.xs/2}px ${t.lg}px`},timelineBubble:{boxSizing:"border-box",flexShrink:0,width:34,height:34,borderRadius:o.pill,backgroundColor:r.brandSoft,border:u},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:t.xs-1,minWidth:0},timelineKind:{...I(e,"mono"),fontSize:n.size.micro,lineHeight:`${n.size.bodyTight}px`,letterSpacing:n.letterSpacing.eyebrow/3,textTransform:"uppercase",color:r.text.secondary},timelineTitle:{...d(n.size.body,n.lineHeight.normal,r.text.primary,"medium")}}}i(Lf,"makeStyles");function Bi(e,r={}){let t=Ar(),{userRef:o}=Z(),n=r.now??Date.now,[l,a]=useState(null),[d,s]=useState(true),[c,u]=useState(null),[p,f]=useState(null),g=p===true,[b,m]=useState({}),[C,R]=useState(false),[x,y]=useState(null),[v,h]=useState(false),[E,T]=useState(false),w=Pn(e),D=useRef(0),A=useRef(true),O=useCallback(async()=>{let S=D.current+=1;if(s(true),u(null),o===null){a(null),s(false);return}let q=await t.listShares(e);S!==D.current||!A.current||(q.ok?(a(q.value),f(true)):mt(q.error)?(a(null),f(false)):(a(null),u(q.error),Pd(q)&&f(true)),s(false));},[t,e,o]);useEffect(()=>(A.current=true,O(),()=>{A.current=false,D.current+=1;}),[O]);let $=useRef(w);useEffect(()=>{$.current!==w&&($.current=w,m({}),T(true),O());},[w,O]);let L=useCallback(async()=>{R(true);let S=await t.createShare(e);return A.current&&(R(false),S.ok?(m(q=>({...q,[S.value.shareId]:S.value.shareUrl})),O()):mt(S.error)?f(false):Yr(S.error)&&T(true)),S},[t,e,O]),V=useCallback(async S=>{y(S);let q=await t.revokeShare(e,S);return A.current&&(y(null),O()),q},[t,e,O]),J=useCallback(async()=>{h(true);let S=await t.getPdfLink(e);return A.current&&(h(false),!S.ok&&Yr(S.error)&&T(true)),S},[t,e]),Ce=useCallback(()=>{T(false),O();},[O]),re=useMemo(()=>js(l??[],b,n()),[l,b,n]),k=d?"loading":c!==null?"error":re.length===0?"empty":"populated";return useMemo(()=>({status:k,rows:re,available:g,consentRequired:E,error:c,creating:C,revokingId:x,preparingPdf:v,createLink:L,revoke:V,pdfLink:J,refresh:Ce}),[k,re,g,E,c,C,x,v,L,V,J,Ce])}i(Bi,"useRecordShares");function Pd(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(Pd,"answeredBehindGate");function Td(e){return e.available||e.status!=="empty"}i(Td,"sharesListShown");function ji(e){let r=Ar(),{userRef:t}=Z(),o=useMemo(()=>({}),[r,e,t]),[n,l]=useState({scope:o,lit:null});useEffect(()=>{if(t===null)return;let d=true;return r.listShares(e).then(s=>{d&&(!s.ok&&mt(s.error)?l({scope:o,lit:false}):Pd(s)&&l({scope:o,lit:true}));},()=>{}),()=>{d=false;}},[r,e,t,o]);let a=n.scope===o?n.lit:null;return useMemo(()=>({lit:a}),[a])}i(ji,"useRecordsDepthProbe");function Hi(e){let r=Ar(),o=ji(e).lit===true,[n,l]=useState(false),[a,d]=useState(null),s=useRef(true);useEffect(()=>(s.current=true,()=>{s.current=false;}),[]);let c=useCallback(async()=>{l(true),d(null);let u=await r.getPdfLink(e);return s.current&&(l(false),u.ok||d(u.error)),u},[r,e]);return useMemo(()=>({preparing:n,available:o,error:a,pdfLink:c}),[n,o,a,c])}i(Hi,"useRecordPdfLink");function Vi(e){typeof window<"u"&&window.open(e,"_blank","noopener");}i(Vi,"openInNewTab");function zf(e){return typeof navigator>"u"||!navigator.clipboard?Promise.reject(new Error("clipboard unavailable")):navigator.clipboard.writeText(e)}i(zf,"copyText");function Id({petRef:e,onClose:r,onNavigate:t,onOpenUrl:o,onCopy:n,returnFocusTo:l}){let{theme:a,styles:d}=G(),s=Vt(true,r,l),c=Bi(e),[u,p]=useState(null),[f,g]=useState(null),b=c.available&&!c.consentRequired,m=i((h,E)=>{on(o??(w=>Vi(w)),h,E).then(w=>{w.ok||p(le.toasts.shareSheet);});},"open"),C=i(()=>{p(null),c.createLink().then(h=>{h.ok?m(h.value.shareUrl,"share_link"):p(Un(h.error,"create"));});},"onCreateLink"),R=i(()=>{p(null),c.pdfLink().then(h=>{h.ok?m(h.value.downloadUrl,"record_pdf"):p(Un(h.error,"download"));});},"onDownload"),x=i(h=>{h.shareUrl!==null&&on(n??zf,h.shareUrl).then(E=>p(E.ok?le.toasts.copied:le.toasts.copyFailed));},"onCopyRow"),y=i(h=>{c.revoke(h).then(E=>{g(null),p(E.ok?le.toasts.turnedOff:Un(E.error,"revoke"));});},"onConfirmRevoke"),v={display:"flex",flexDirection:"column",gap:a.space.sm,padding:a.space.md,borderRadius:a.radius.md,backgroundColor:a.color.surfaceCream,border:`1px solid ${a.color.brandBorder}`};return jsx("div",{style:d.sheetBackdrop,onClick:r,children:jsxs("div",{ref:s.dialogRef,role:"dialog","aria-modal":"true","aria-label":le.title,style:d.sheet,onClick:h=>h.stopPropagation(),onKeyDown:s.onKeyDown,"data-testid":"share-record-sheet",children:[jsx("span",{style:d.sheetHandle,"aria-hidden":"true"}),jsxs("div",{style:d.sheetHeader,children:[jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:a.space.xs},children:[jsx("h3",{style:d.sheetTitle,children:le.title}),jsx("p",{style:d.sheetHelper,children:le.helper})]}),jsx("button",{type:"button",onClick:r,"aria-label":le.close,style:d.iconButton,"data-testid":"share-record-close",children:jsx("span",{style:d.closeGlyph,"aria-hidden":"true",children:"\xD7"})})]}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:a.space.sm},children:[t?jsx(Y,{label:le.viewDocument,onClick:()=>{r(),t({name:"document"});},testID:"share-view-document"}):null,b?jsx(Y,{label:c.creating?le.creatingLink:le.createLink,kind:"outline",busy:c.creating,onClick:C,testID:"share-create-link"}):null,b?jsx(Y,{label:c.preparingPdf?le.preparingPdf:le.downloadPdf,kind:"outline",busy:c.preparingPdf,onClick:R,testID:"share-download-pdf"}):null]}),c.consentRequired?jsxs("div",{style:v,"data-testid":"share-consent-off",children:[jsx("p",{style:d.rowTitle,children:le.consentOffTitle}),jsx("p",{style:d.muted,children:le.consentOffBody}),jsx(Y,{label:le.retry,kind:"outline",onClick:c.refresh,testID:"share-consent-retry"})]}):null,u?jsx("p",{role:"status","aria-live":"polite",style:d.infoNote,"data-testid":"share-notice",children:u}):null,Td(c)?jsxs("section",{"aria-label":le.activeLinks,style:{display:"flex",flexDirection:"column",gap:a.space.sm},children:[jsx("h4",{style:{...d.fieldLabel,...I(a,"bold"),textTransform:"uppercase"},children:le.activeLinks}),c.status==="loading"?jsx(Ks,{testID:"share-record-loading"}):c.status==="error"?jsxs("div",{style:v,"data-testid":"share-record-error",children:[jsx("p",{style:d.rowTitle,children:le.errorTitle}),jsx("p",{style:d.muted,children:le.errorBody}),jsx(Y,{label:le.retry,kind:"outline",onClick:c.refresh,testID:"share-record-retry"})]}):c.rows.length===0?jsxs("div",{style:v,"data-testid":"share-record-empty",children:[jsx("p",{style:d.rowTitle,children:le.emptyTitle}),jsx("p",{style:d.muted,children:le.emptyBody})]}):jsx("ul",{style:{...d.plainList,gap:a.space.md},children:c.rows.map(h=>jsxs("li",{style:{...v},"data-testid":`share-row-${h.shareId}`,children:[jsxs("div",{"aria-label":h.a11yLabel,children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.space.sm},children:[jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:a.space.sm,height:a.space.sm,borderRadius:a.space.xs,backgroundColor:h.active?a.color.success:a.color.text.muted}}),jsx("span",{style:{...d.rowTitle,...I(a,"bold")},children:h.statusLabel}),jsx("span",{style:d.muted,children:h.expiryLabel})]}),h.createdLabel?jsx("p",{style:d.muted,children:h.createdLabel}):null]}),f===h.shareId?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:a.space.sm},"data-testid":`share-revoke-confirm-${h.shareId}`,children:[jsx("p",{style:d.bodyText,children:le.confirmTurnOff}),jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:a.space.sm},children:[jsx(Y,{label:c.revokingId===h.shareId?le.turningOff:le.turnOff,kind:"danger",busy:c.revokingId===h.shareId,onClick:()=>y(h.shareId),testID:`share-revoke-do-${h.shareId}`}),jsx(Y,{label:le.keep,kind:"outline",disabled:c.revokingId===h.shareId,onClick:()=>g(null),testID:`share-revoke-cancel-${h.shareId}`})]})]}):jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:a.space.sm},children:[jsx(Y,{label:le.copyLink,kind:"outline",disabled:h.shareUrl===null,ariaLabel:le.copyLinkA11y(h.actionContext),onClick:()=>x(h),testID:`share-copy-${h.shareId}`}),jsx(Y,{label:le.turnOff,kind:"danger",ariaLabel:le.turnOffA11y(h.actionContext),onClick:()=>g(h.shareId),testID:`share-ask-revoke-${h.shareId}`})]})]},h.shareId))})]}):null]})})}i(Id,"ShareSheet");var gr=H.document,Od=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),Mf=i((e,r)=>e.getRecordDepth(r),"readDepth"),$f=i(e=>!e.available,"depthEmpty");function Uf(e,r){return e.identity.length===0&&e.entities.length===0&&e.forwardLooking.length===0&&(r===null||r.labResults.length===0&&r.physicalExams.length===0&&r.clinicianNotes.length===0)}i(Uf,"documentIsEmpty");function Gi(e){let{style:r,className:t,renderPending:o,...n}=Te(e,["onBack"]),{userRef:l}=Z(),{theme:a,styles:d}=G();return jsx(De,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,$e),children:jsxs("div",{className:t,style:{...d.root,backgroundColor:a.color.surface,...r},"data-testid":"record-document-screen",children:[l===null?jsx("div",{style:d.body,children:jsx(er,{label:W.sessionRequired,glyph:"empty"})}):jsx(Bf,{...n}),jsx(Ie,{})]})})}i(Gi,"EverfurRecordDocument");function Bf({petRef:e,petName:r,controller:t,consentVersion:o,onBack:n,onOpenUrl:l}){let{theme:a,styles:d}=G(),s=Ad(),c=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),u=Ke(c),p=qr(e,Mf,$f),f=Hi(e),g=et(o,u.consent),b=i(()=>{let v=Hr(o,u.consent);v.length!==0&&u.grantConsent(v,`records-consent-${Date.now().toString(36)}`);},"onGrant"),m=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,C=u.record,R=i(()=>{f.pdfLink().then(v=>{if(!v.ok)return;on(l??(E=>Vi(E)),v.value.downloadUrl,"record_pdf");});},"download"),x,y=false;if(u.status==="loading"||p.status==="loading"&&C!==null)x=jsx("div",{"data-testid":"record-document-loading",children:jsx(hd,{})});else if(u.status==="error"){let v=Vr(u,g);x=v.kind==="error"||v.kind==="pet_not_found"?jsx(Ue,{variant:Ze(v.error),message:v.error.displayMessage,onAction:v.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):yt(u,b,g);}else C===null||Uf(C,m)?x=jsx("p",{style:s.empty,"data-testid":"record-document-empty",children:gr.empty}):(y=true,x=jsx(jf,{record:C,depth:m,petName:r,wordmark:a.meta.displayName}));return jsxs(Fragment,{children:[jsx(We,{title:gr.title,variant:"document",onBack:n,testID:"record-document-header",right:f.available&&y?jsx("button",{type:"button",onClick:R,disabled:f.preparing,"aria-busy":f.preparing,"aria-label":gr.download,style:d.iconButton,"data-testid":"record-document-download",children:jsx("span",{"aria-hidden":"true",style:{display:"block",width:12,height:12,borderLeft:`2px solid ${a.color.brand}`,borderBottom:`2px solid ${a.color.brand}`,transform:"rotate(-45deg)"}})}):void 0}),f.error?jsx("p",{role:"alert",style:{...d.errorText,padding:`0 ${a.space.lg}px`},children:f.error.displayMessage}):null,jsx("div",{style:d.body,children:x})]})}i(Bf,"DocumentBody");function jf({record:e,depth:r,petName:t,wordmark:o}){let n=Ad(),l=useMemo(()=>{let c=[],u=new Map;for(let g of e.entities){let b=g.category.trim();if(b.length===0)continue;let m=u.get(b);m===void 0?(c.push(b),u.set(b,[g])):m.push(g);}let p=Od.filter(g=>c.includes(g)),f=c.filter(g=>!Od.includes(g));return [...p,...f].map(g=>({type:g,rows:u.get(g)??[]}))},[e.entities]),a=Date.now(),d=i((c,u,p)=>jsxs("section",{style:n.section,"data-testid":p,children:[jsxs("div",{style:n.sectionHeader,children:[jsx("h3",{style:n.sectionTitle,children:c}),jsx("span",{style:n.rule})]}),jsx("div",{children:u})]},p),"section"),s=i((c,u)=>({...n.row,...c>0?n.rowDivider:{},...u}),"row");return jsxs("article",{style:n.page,"data-testid":"record-document",children:[jsxs("header",{style:n.letterhead,children:[jsx("span",{style:n.wordmark,children:o}),jsx("span",{style:n.docTitle,children:gr.docTitle}),jsx("span",{style:n.petName,children:t?.trim()||gr.namelessPet}),jsx("span",{style:n.generated,children:gr.generated(e.generatedAt)})]}),e.identity.length>0?d(gr.identity,e.identity.map((c,u)=>jsxs("div",{style:s(u),children:[jsx("span",{style:n.rowLabel,children:c.label}),jsx("span",{style:n.rowValue,children:c.value})]},`${u}:${c.label}`)),"record-document-identity"):null,r&&r.labResults.length>0?d(gr.labs,r.labResults.map((c,u)=>{let p=Br(c.latest.status),f=Yl(c.points[c.points.length-1]??null),g=cr(c.latest.value,c.latest.unit??c.unit,c.latest.qualitativeResult);return jsxs("div",{style:s(u,p.outOfRange?n.rowFlag:void 0),children:[jsxs("span",{style:n.rowMain,children:[jsx("span",{style:n.rowLabel,children:c.name}),jsxs("span",{style:n.rowMeta,children:[f?gr.ref(f):gr.noRange,c.latest.at?` \xB7 ${Q(c.latest.at)}`:""]})]}),jsxs("span",{style:n.rowRight,children:[g!=="-"?jsx("span",{style:{...n.rowValue,...p.outOfRange?n.alert:{}},children:g}):null,jsx("span",{style:{...n.markerStatus,...p.outOfRange?n.alert:{}},children:p.label})]})]},c.markerId)}),"record-document-labs"):null,l.map(({type:c,rows:u})=>d(kt(c),u.map((p,f)=>{let g=[Nt(p.value,p.unit),p.observedAt?Q(p.observedAt):null].filter(b=>b&&b.length>0).join(" \xB7 ");return jsx("div",{style:s(f),children:jsxs("span",{style:n.rowMain,children:[jsx("span",{style:n.rowLabel,children:p.label}),g?jsx("span",{style:n.rowMeta,children:g}):null]})},p.key)}),`record-document-${c}`)),e.forwardLooking.length>0?d(gr.upcomingCare,e.forwardLooking.map((c,u)=>{let p=yn(c.dueAt,a);return jsxs("div",{style:s(u),children:[jsxs("span",{style:n.rowMain,children:[jsx("span",{style:n.rowLabel,children:c.title}),c.detail?jsx("span",{style:n.rowMeta,children:c.detail}):null]}),p?jsx("span",{style:{...n.rowValue,...p.overdue?n.alert:{}},children:p.label}):null]},`${c.title}-${u}`)}),"record-document-upcoming"):null,r&&r.physicalExams.length>0?d(gr.physicalExams,r.physicalExams.map((c,u)=>jsxs("div",{style:{...n.block,...u>0?n.rowDivider:{}},children:[c.observedOn?jsx("span",{style:n.blockDate,children:Q(c.observedOn)}):null,c.systems.filter(p=>p.finding).map(p=>jsxs("div",{style:n.fieldRow,children:[jsx("span",{style:n.fieldLabel,children:Lt(p.system)}),jsx("span",{style:n.fieldValue,children:p.finding})]},p.system))]},c.examId)),"record-document-exams"):null,r&&r.clinicianNotes.length>0?d(gr.clinicianNotes,r.clinicianNotes.map((c,u)=>jsxs("div",{style:{...n.block,...u>0?n.rowDivider:{}},children:[c.observedOn?jsx("span",{style:n.blockDate,children:Q(c.observedOn)}):null,c.sections.filter(p=>p.text).map((p,f)=>jsxs("div",{style:n.noteSection,children:[jsx("span",{style:n.noteLabel,children:zt(p.section)}),jsx("p",{style:n.noteBody,children:p.text})]},`${p.section}-${f}`))]},c.noteId)),"record-document-notes"):null,e.disclaimer.length>0?jsx("p",{style:n.disclaimer,children:e.disclaimer}):null]})}i(jf,"RecordDocument");function Ad(){let e=ue();return useMemo(()=>Hf(e),[e])}i(Ad,"useDocStyles");function Hf(e){let{color:r,space:t,radius:o,type:n}=e,l=i((s,c,u,p="regular")=>({margin:0,...I(e,p),fontSize:s,lineHeight:`${Math.round(s*c)}px`,color:u}),"text"),a=i((s,c)=>({margin:0,...I(e,"mono"),fontSize:s,lineHeight:`${s+t.xs-1}px`,color:c,letterSpacing:n.letterSpacing.eyebrow/2,textTransform:"uppercase"}),"monoText"),d=`1px solid ${r.borderHairlineGreen}`;return {empty:{...l(n.size.body,n.lineHeight.normal,r.text.muted,"medium"),textAlign:"center",padding:`${t.xxl}px ${t.xxl}px`},page:{padding:`0 ${t.lg+t.xs}px ${t.xxl+t.lg}px`,...I(e,"regular")},letterhead:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.xs+t.xs/2,padding:`${t.md}px 0 ${t.lg+t.xs+t.xs/2}px`,borderBottom:`2px solid ${r.brand}`,marginBottom:t.sm},wordmark:{...l(n.size.heading,n.lineHeight.snug,r.brand,"bold"),letterSpacing:n.letterSpacing.headerBrand},docTitle:{...a(n.size.caption,r.brand),marginTop:t.sm+t.xs/2,letterSpacing:n.letterSpacing.eyebrow+.4},petName:l(n.size.verdict+t.xs/2,n.lineHeight.tight,r.text.primary),generated:{...a(n.size.tiny,r.text.muted),textTransform:"none"},section:{marginTop:t.lg+t.xs+t.xs/2},sectionHeader:{display:"flex",alignItems:"center",gap:t.sm+t.xs/2,marginBottom:t.sm},sectionTitle:a(n.size.tiny,r.brand),rule:{flex:1,height:1,backgroundColor:r.borderHairlineGreen},row:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:t.md+t.xs/2,padding:`${t.sm+1}px 0`},rowDivider:{borderTop:d},rowFlag:{backgroundColor:r.badgeBgCritical,margin:`0 -${t.sm}px`,padding:`${t.sm+1}px ${t.sm}px`,borderRadius:o.xs},rowMain:{display:"flex",flexDirection:"column",minWidth:0},rowRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:t.xs/2},rowLabel:{...l(n.size.body,n.lineHeight.normal,r.text.primary,"medium")},rowValue:{...l(n.size.body,n.lineHeight.normal,r.text.primary,"bold"),textAlign:"right"},alert:{color:r.danger},rowMeta:{marginTop:t.xs/2,...I(e,"mono"),fontSize:n.size.tiny,lineHeight:`${n.size.body}px`,color:r.text.muted},markerStatus:a(n.size.micro,r.text.muted),block:{padding:`${t.sm+t.xs/2}px 0`},blockDate:{...a(n.size.tiny,r.text.muted),display:"block",marginBottom:t.xs+t.xs/2},fieldRow:{display:"flex",alignItems:"flex-start",gap:t.md+t.xs/2,padding:`${t.xs-1}px 0`},fieldLabel:{width:120,flexShrink:0,...l(n.size.bodyTight,n.lineHeight.normal,r.text.muted,"medium")},fieldValue:{flex:1,...l(n.size.bodyTight,n.lineHeight.normal,r.text.primary,"medium")},noteSection:{marginTop:t.sm},noteLabel:{...a(n.size.tiny,r.brand),display:"block",marginBottom:t.xs/2},noteBody:l(n.size.bodyTight,n.lineHeight.relaxed,r.text.primary),disclaimer:{...l(n.size.tiny,n.lineHeight.relaxed,r.text.muted),marginTop:o.xl,paddingTop:t.md+t.xs/2,borderTop:d}}}i(Hf,"makeDocStyles");var Kf=i((e,r)=>e.getRecordDepth(r),"readDepth"),Qf=i(e=>!e.available,"depthEmpty");function Yi(e){let{style:r,className:t,renderPending:o,...n}=Te(e,["onNavigate","onBack","onAsk"]),{userRef:l}=Z(),{styles:a}=G();return jsx(De,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,$e),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"everfur-record-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(er,{label:W.sessionRequired,glyph:"empty"})}):jsx(Xf,{...n}),jsx(Ie,{})]})})}i(Yi,"EverfurRecordDetail");function Xf({petRef:e,petName:r,controller:t,consentVersion:o,onNavigate:n,onBack:l,onAsk:a,onOpenUrl:d,onCopy:s}){let{theme:c,styles:u}=G(),p=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),f=Ke(p),g=qr(e,Kf,Qf),b=Ii(e),m=ji(e),[C,R]=useState(false),x=useRef(null),y=et(o,f.consent),v=i(()=>{let A=Hr(o,f.consent);A.length!==0&&f.grantConsent(A,`records-consent-${Date.now().toString(36)}`);},"onGrant"),h=g.value!==null&&!g.value.withheld&&g.value.available?g.value:null,E=f.record,T=i(()=>{f.refresh(),g.refresh();},"retry"),w=n!==void 0||m.lit===true,D;if(f.status==="loading"||g.status==="loading"&&E!==null&&!E.isEmpty)D=jsx(Mt,{testID:"everfur-record-loading"});else if(f.status==="error"){let A=Vr(f,y);D=A.kind==="error"||A.kind==="pet_not_found"?jsx(Ue,{variant:Ze(A.error),message:A.error.displayMessage,onAction:A.error.retryable?T:void 0,testID:"everfur-record-error"}):yt(f,v,y);}else if(E===null||E.isEmpty){let A=h?.completeness?.documentsInReview??0;D=jsxs("div",{style:u.content,"data-testid":"everfur-record-empty",children:[jsx(Ue,{variant:"no_records",message:A>0?H.inReview(A):void 0}),jsx(pt,{disclaimer:E?.disclaimer??""})]});}else D=jsx("div",{style:{...u.content,gap:c.space.lg+c.space.xs,paddingBottom:c.space.xxl+c.space.sm},"data-testid":"everfur-record",children:jsx(to,{record:E,depth:h,petName:r,onNavigate:n,onAsk:a,factEdit:b})});return jsxs(Fragment,{children:[jsx(We,{title:H.title,onBack:l,testID:"everfur-record-header",right:w||n?jsxs(Fragment,{children:[n?jsx("button",{type:"button",onClick:()=>n({name:"clinicBatch"}),"aria-label":H.requestClinicsA11y,style:u.iconButton,"data-testid":"everfur-record-request-clinics",children:jsx("span",{"aria-hidden":"true",style:{display:"block",width:14,height:14,border:`2px solid ${c.color.brand}`,transform:"rotate(45deg)"}})}):null,w?jsx("button",{ref:x,type:"button",onClick:()=>R(true),"aria-label":H.shareA11y,style:u.iconButton,"data-testid":"everfur-record-share",children:jsx("span",{"aria-hidden":"true",style:{display:"block",width:16,height:16,borderRadius:c.radius.pill,border:`2px solid ${c.color.brand}`}})}):null]}):void 0}),jsx("div",{style:u.body,children:D}),C?jsx(Id,{petRef:e,onClose:()=>R(false),returnFocusTo:x,onNavigate:n,...d?{onOpenUrl:d}:{},...s?{onCopy:s}:{}}):null]})}i(Xf,"RecordBody");var po=Object.freeze({download:"Download",downloadA11y:i(e=>`Download, ${e}`,"downloadA11y"),listA11y:"You added these records"});function Jf(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(Jf,"formatBytes");function Zf(e){let r=e?.trim();return r?r.toUpperCase():null}i(Zf,"formatLabel");function Ki(e){return Object.freeze(e.map(r=>{let t=Zf(r.docFormat),o=r.receivedAt?Q(r.receivedAt):null,n=r.fileName??t??o??r.sourceDocId,a=[r.fileName!==null&&t!==null&&r.fileName.toUpperCase().endsWith(`.${t}`)||n===t?null:t,r.byteSize!==null?Jf(r.byteSize):null,n===o?null:o].filter(d=>!!d).join(" \xB7 ");return Object.freeze({key:r.sourceDocId,title:n,meta:a||null,downloadUrl:r.downloadUrl})}))}i(Ki,"requestDocumentRows");function Xi(e,r={}){let t=r.enabled??true,o=Ar(),{userRef:n}=Z(),[l,a]=useState(null),[d,s]=useState(t),[c,u]=useState(null),p=useRef(0),f=useRef(true),g=useCallback(async()=>{let R=p.current+=1;if(!t||n===null){a(null),u(null),s(false);return}s(true),u(null);let x=await o.listRequestDocuments(e);R!==p.current||!f.current||(x.ok?a(x.value):(a(null),u(x.error)),s(false));},[o,t,e,n]);useEffect(()=>(f.current=true,g(),()=>{f.current=false,p.current+=1;}),[g]);let b=useMemo(()=>l===null?[]:Ki(l),[l]),m=useCallback(()=>{g();},[g]),C=d?"loading":c!==null?"error":b.length===0?"empty":"populated";return useMemo(()=>({status:C,rows:b,error:c,refresh:m}),[C,b,c,m])}i(Xi,"useRequestDocuments");function Cn({requestId:e,open:r=true,testID:t="records-request-documents"}){let{theme:o,styles:n}=G(),l=Xi(e,{enabled:r});return r?l.status==="loading"?jsx("div",{style:{paddingTop:o.space.sm},"aria-busy":"true","data-testid":`${t}-loading`,children:jsx(fe,{width:"100%",height:o.space.lg+o.space.md})}):l.status==="error"?jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:o.space.sm,paddingTop:o.space.sm},"data-testid":`${t}-error`,children:[jsx("p",{style:{...n.muted,margin:0},role:"alert",children:l.error?.displayMessage??""}),l.error?.retryable===true?jsx(Y,{label:W.retry,kind:"outline",onClick:l.refresh,testID:`${t}-retry`}):null]}):l.status==="empty"?null:jsx("ul",{"aria-label":po.listA11y,style:{...n.plainList,paddingTop:o.space.sm},"data-testid":t,children:l.rows.map((a,d)=>jsxs("li",{style:ry(o.space.sm,d===0?null:o.color.brandBorder),children:[jsxs("div",{style:{minWidth:0},children:[jsx("p",{style:{...n.rowTitle,margin:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.title}),a.meta!==null?jsx("p",{style:{...n.muted,margin:0,fontVariantNumeric:"tabular-nums"},children:a.meta}):null]}),jsx("a",{href:a.downloadUrl,download:true,target:"_blank",rel:"noopener noreferrer","aria-label":po.downloadA11y(a.title),style:{...n.pill,...n.pillOutline,textDecoration:"none"},"data-testid":`${t}-download-${a.key}`,children:po.download})]},a.key))}):null}i(Cn,"RequestDocumentsList");function ry(e,r){return {display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:e,paddingTop:e,paddingBottom:e,...r!==null?{borderTop:`1px solid ${r}`}:{}}}i(ry,"rowStyle");var ty=Math.round(zr/(1024*1024)),Ye=Object.freeze({title:i(e=>`Upload ${we(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 ${we(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 ${ty} 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,r)=>`Uploading ${e+1} of ${r}\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."})});function ra(e){let{style:r,className:t,renderPending:o,...n}=Te(e,["onNavigate","onBack"]),{userRef:l}=Z(),{styles:a}=G();return jsx(De,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,$e),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"upload-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(er,{label:W.sessionRequired,glyph:"empty"})}):jsx(iy,{...n}),jsx(Ie,{})]})})}i(ra,"EverfurRecordsUpload");function iy({petRef:e,petName:r,controller:t,onNavigate:o,onBack:n}){let{theme:l,styles:a}=G(),{runtime:d}=Z(),s=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),c=Ke(s),u=t!==void 0||wn(d.registry.services.uploadTransport);return jsxs(Fragment,{children:[jsx(We,{title:"",onBack:n,testID:"upload-header"}),jsxs("div",{style:{...a.body,...a.content,padding:l.space.lg+l.space.xs,gap:l.space.lg+l.space.xs},children:[jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:l.space.sm,textAlign:"center"},children:[jsx("span",{"aria-hidden":"true",style:{display:"block",width:52,height:52,borderRadius:l.radius.pill,backgroundColor:l.color.brandSoft,border:`1px solid ${l.color.brandBorder}`}}),jsx("h3",{style:{...a.sectionTitle,fontSize:l.type.size.heading+2,color:l.color.brand},children:Ye.title(r)}),jsx("p",{style:{...a.muted,fontSize:l.type.size.body,maxWidth:340},children:Ye.subtitle(r)})]}),jsx(ta,{records:c,requestId:null,canUpload:u,onDone:o?p=>o({name:"request",requestId:p}):void 0})]})]})}i(iy,"UploadBody");function ta({records:e,requestId:r,canUpload:t,onDone:o}){let{theme:n,styles:l}=G(),a=useRef(null),d=`records-upload-format-hint-${r??"new"}`,[s,c]=useState(null),[u,p]=useState(0),[f,g]=useState(false),b=useRef(r),m=useRef([]),C=e.uploadQueue.filter(w=>w.status!=="skipped"),R=C.filter(w=>w.status==="done").length,x=C.filter(w=>w.status==="failed").length,y=!e.isUploading&&!f&&u>0,v=useCallback(async w=>{if(w.length!==0){c(null),g(true);try{let D=b.current;if(D===null){let O=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!O.ok){c(Ye.errors.start);return}D=O.value.id,b.current=D;}p(O=>O+1);let A=await e.uploadDocuments(D,w);m.current=A.flatMap((O,$)=>O.status==="failed"&&w[$]!==void 0?[w[$]]:[]);}finally{g(false);}}},[e]),h=i(w=>{let D=Array.from(w.currentTarget.files??[]);w.currentTarget.value="",!(D.length===0||!t)&&(async()=>{let A=[];for(let O of D)A.push(await oo(O));if(A.length===1&&!Ni(A[0])){c(Ye.errors.upload);return}await v(A);})();},"onChange"),E=i(()=>a.current?.click(),"pick"),T=e.isUploading||f;return jsxs("section",{style:{...l.creamCard,backgroundColor:n.color.surface,border:`1px solid ${n.color.brandSoft}`,borderRadius:n.radius.md},"data-testid":"records-upload-card",children:[jsx("h4",{style:{...l.rowTitle,...I(n,"bold"),fontSize:n.type.size.subtitle},children:Ye.cardTitle}),jsx("p",{id:d,style:l.muted,children:Ye.cardSubtitle}),jsx("input",{ref:a,type:"file",accept:no,multiple:true,tabIndex:-1,"aria-hidden":"true",hidden:true,disabled:!t,onChange:h,"data-testid":"records-upload-input"}),s?jsx("p",{role:"alert",style:l.errorBanner,children:s}):null,jsx(Rd,{records:e}),T?jsx("p",{style:l.muted,children:Ye.uploading(R,C.length)}):y?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:n.space.sm},children:[R>0?jsx("p",{role:"status",style:l.bodyText,children:Ye.received(R)}):null,x>0?jsx(Y,{label:Ye.retryFailed(x),kind:"link",ariaLabel:Ye.retryFailedA11y(x),onClick:()=>{v(m.current);},testID:"records-upload-retry-failed"}):null,jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:n.space.sm},children:[jsx(Y,{label:Ye.addMore,kind:"link",ariaLabel:Ye.addMoreA11y,ariaDescribedBy:d,disabled:!t,onClick:E,testID:"records-upload-another"}),o&&b.current!==null&&R>0?jsx(Y,{label:Ye.done,ariaLabel:Ye.doneA11y,onClick:()=>o(b.current),testID:"records-upload-done"}):null]})]}):jsx(Y,{label:Ye.chooseFiles,ariaLabel:Ye.chooseFilesA11y,ariaDescribedBy:d,disabled:!t,onClick:E,testID:"records-upload-choose"})]})}i(ta,"UploadRecordCard");function oa(e){let{style:r,className:t,renderPending:o,...n}=Te(e,["onNavigate","onBack"]),{userRef:l}=Z(),{styles:a}=G();return jsx(De,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,$e),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-request-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(er,{label:W.sessionRequired,glyph:"empty"})}):jsx(dy,{...n}),jsx(Ie,{})]})})}i(oa,"EverfurRecordsRequest");function dy({petRef:e,requestId:r,controller:t,onNavigate:o,onBack:n,nowMs:l}){let{styles:a}=G(),{runtime:d,userRef:s,scopeEpoch:c}=Z(),u=Ke(t?{petRef:e,controller:t}:{petRef:e}),p=u.requests.find(b=>b.id===r)??null,f=t!==void 0||wn(d.registry.services.uploadTransport),g;return u.status==="loading"?g=jsx(Ws,{testID:"records-request-loading"}):u.status==="error"&&u.error?g=jsx(Ue,{variant:Ze(u.error),message:u.error.displayMessage,onAction:u.error.retryable?u.refresh:void 0,testID:"records-request-error"}):p===null?g=jsx(Ue,{variant:"no_requests",testID:"records-request-missing"}):g=jsx(cy,{request:p,records:u,canUpload:f,onNavigate:o,nowMs:l},JSON.stringify([s,c,p.id])),jsxs(Fragment,{children:[jsx(We,{title:p?Gn(p):"",onBack:n,testID:"records-request-header"}),jsx("div",{style:a.body,children:g})]})}i(dy,"RequestBody");function cy({request:e,records:r,canUpload:t,onNavigate:o,nowMs:n}){let{theme:l,styles:a}=G(),d=cd({request:e,onRecovered:r.refresh,canUpload:t},_r()),[s,c]=useState(null),[u,p]=useState(false),[f,g]=useState(null),b=useRef(true);useEffect(()=>(b.current=true,()=>{b.current=false;}),[]);let m=d.request,C=n??Date.now(),R=m.status==="published",x=m.status==="published"||m.status==="failed"||m.status==="revoked",y=Uo(m),v=m.wireStatus==="clinic_responded_no_records",h=rs(m,C),E=x?null:m.waitingExpectation?.trim()||null,T=Yn(m),w=d.error!==null&&s!==null?s==="revoke"?ce.errors.cancel:ce.errors[s]:null,D=i((V,J)=>{c(V),J();},"run"),A=i(()=>{u||(p(true),g(null),r.createRequest(`records-upload-${Date.now().toString(36)}`).then(V=>{if(b.current){if(p(false),!V.ok){g(ce.errors.start);return}o?.({name:"request",requestId:V.value.id});}}));},"startFresh"),O={display:"flex",flexDirection:"column",gap:l.space.sm},$=i(V=>jsx("p",{role:"alert",style:a.errorBanner,children:V}),"errorBanner"),L=`records-failure-clinic-email-${m.id}`;return jsxs("div",{style:{...a.content,gap:l.space.lg+l.space.xs/2},"data-testid":`records-request-${m.id}`,children:[m.statusLabel.length>0||m.heldItemCount>0?jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:l.space.sm},"data-testid":"records-request-status-row",children:[m.statusLabel.length>0?jsx(dr,{label:m.statusLabel,tone:Al(m),testID:"records-request-status-chip"}):null,m.heldItemCount>0?jsx(dr,{label:Si(m.heldItemCount),tone:"neutral",testID:"records-request-held-count"}):null]}):null,m.status==="awaiting_upload"?jsx(ta,{records:r,requestId:m.id,canUpload:t}):null,E&&!h?jsx("p",{style:a.infoNote,children:E}):m.wireStatus==="awaiting_response"&&!h?jsx("p",{style:a.infoNote,children:ce.awaitingNote}):null,h?jsx("p",{style:a.cautionNote,"data-testid":"records-request-waiting-banner",children:ce.waitingBanner($o(m,C))}):null,R&&o?jsx(Y,{label:ce.viewRecords,onClick:()=>o({name:"dashboard"}),testID:"records-request-view-dashboard"}):null,ts(m)?jsxs("section",{style:{...O,gap:l.space.md,borderRadius:l.radius.lg-l.space.xs,padding:l.space.md+l.space.xs/2,backgroundColor:y?l.color.badgeBgCritical:l.color.badgeBgCaution},"data-testid":"records-failure-card",children:[jsx("p",{style:{...a.rowTitle,...I(l,"bold"),color:y?l.color.danger:l.color.warningStrong},children:es(m)}),m.canUpdateClinicEmail!==true&&m.canRetrySend!==true?jsx("p",{style:a.rowDetail,children:ce.nextStep}):null,m.canUpdateClinicEmail===true?jsxs("div",{style:O,children:[jsx("label",{htmlFor:L,style:a.fieldLabel,children:Fr.email}),jsx("input",{id:L,type:"email",style:a.field,placeholder:Fr.emailPlaceholder,autoComplete:"off",maxLength:320,value:d.email,disabled:d.busy,onChange:V=>d.setEmail(V.target.value),"data-testid":"records-failure-clinic-email"}),d.emailInvalid?jsx("p",{role:"alert",style:a.errorText,children:ce.errors.invalidEmail}):null,jsx(Y,{label:Fr.updateEmail,ariaLabel:Fr.updateEmailA11y,disabled:!d.canUpdateEmail,busy:d.busy&&s==="email",onClick:()=>D("email",d.updateEmail),testID:"records-failure-update-email"})]}):null,m.canRetrySend===true?jsx(Y,{label:Fr.retry,kind:"outline",ariaLabel:Fr.retryA11y,disabled:!d.canRetry,busy:d.busy&&s==="retry",onClick:()=>D("retry",d.retry),testID:"records-failure-retry-send"}):null,m.canRetrySend===true&&d.hasEmailEdit?jsx("p",{style:a.rowDetail,children:Fr.retryHint}):null,w&&(s==="email"||s==="retry")?$(w):null]}):null,(y||v)&&o?jsx(Y,{label:ce.tryAnotherClinic,kind:"outline",ariaLabel:ce.tryAnotherClinicA11y,onClick:()=>o({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,T!==null?jsxs("div",{style:O,children:[jsx(vd,{call:T,prompt:m.statusLabel}),m.canRetrySend===true?jsx(Y,{label:d.busy&&s==="retry"?ce.resending:ce.resend,kind:"outline",ariaLabel:d.busy&&s==="retry"?ce.resendingA11y:ce.resendA11y,disabled:!d.canRetry,onClick:()=>D("retry",d.retry),testID:"records-resend-authorization"}):null]}):null,d.canConvert?jsxs("div",{style:O,children:[jsx(Y,{label:d.busy&&s==="convert"?ce.converting:ce.convert,busy:d.busy&&s==="convert",onClick:()=>D("convert",d.convert),testID:"records-convert-upload"}),jsx("p",{style:a.muted,children:ce.convertHint}),w&&s==="convert"?$(w):null]}):null,x&&!R?jsxs("div",{style:O,children:[jsx(Y,{label:u?ce.freshUploadStarting:ce.freshUpload,kind:y||v?"outline":"primary",busy:u,onClick:A,testID:"records-upload-own-fresh"}),f?$(f):null]}):null,w&&s==="revoke"?$(w):null,m.canRevoke===true?d.confirmingRevoke?jsxs("div",{style:O,"data-testid":"records-revoke-confirm",children:[jsx("p",{style:{...a.rowTitle,...I(l,"bold"),fontSize:l.type.size.subtitle},children:Fr.cancelQuestion}),jsx("p",{style:a.bodyText,children:Fr.cancelConsequence}),jsx(Y,{label:d.busy&&s==="revoke"?ce.cancelling:ce.cancel,kind:"danger",ariaLabel:d.busy&&s==="revoke"?ce.cancellingA11y:ce.cancelA11y,busy:d.busy&&s==="revoke",onClick:()=>D("revoke",d.revoke),testID:"records-revoke-do"}),jsx(Y,{label:Fr.keepRequest,kind:"outline",disabled:d.busy,onClick:d.keepRequest,testID:"records-revoke-keep"})]}):jsx(Y,{label:ce.cancel,kind:"danger",ariaLabel:ce.cancelA11y,disabled:d.busy,onClick:d.askRevoke,testID:"records-revoke"}):null,jsx("div",{"aria-hidden":"true",style:{height:1,backgroundColor:l.color.borderHairlineGreen,margin:`${l.space.xs}px 0`}}),jsx(Gt,{request:m}),Rn(m)?jsx(Cn,{requestId:m.id}):null]})}i(cy,"RequestDetail");function Md(e){let{petRef:r,petName:t,controller:o,clinicController:n,consentVersion:l,ownerName:a,onCaptureSignature:d,initialScreen:s,historyMode:c="memory",onExit:u,style:p,className:f,renderPending:g,onOpenUrl:b,onCopy:m,onAsk:C,location:R}=Te(e,["onExit"]),[x,y]=useReducer(Fo,s,On),v=An(x),h=x.stack.length,E=useRef(h);E.current=h;let T=useRef(h),w=useRef(false);useEffect(()=>{if(c!=="browser"||typeof window>"u")return;let J=i(Ce=>{let re=Ce.state;(typeof re?.efRecords=="number"?re.efRecords:1)<E.current&&(w.current=true,y({type:"pop"}));},"onPopState");return window.addEventListener("popstate",J),()=>window.removeEventListener("popstate",J)},[c]),useEffect(()=>{if(c!=="browser"||typeof window>"u")return;let J=T.current;h>J?window.history.pushState({efRecords:h},""):h<J&&!w.current&&window.history.go(h-J),w.current=false,T.current=h;},[c,h]);let D=useCallback(J=>y({type:"navigate",screen:J}),[]),A=useMemo(()=>qn(x).handled?()=>y({type:"pop"}):u,[x,u]),O={onNavigate:D,...A?{onBack:A}:{},...t!==void 0?{petName:t}:{},...b?{onOpenUrl:b}:{},...m?{onCopy:m}:{},...C?{onAsk:C}:{},...R?{location:R}:{}},$={...o?{controller:o}:{},...l!==void 0?{consentVersion:l}:{}},L={...p?{style:p}:{},...f!==void 0?{className:f}:{}},V=g?{renderPending:g}:{};switch(v.name){case "dashboard":return jsx($i,{petRef:r,...O,...$,...V,...L});case "request":return jsx(oa,{petRef:r,requestId:v.requestId,...O,...o?{controller:o}:{},...V,...L});case "timeline":return jsx(wd,{petRef:r,...O,...L});case "record":return jsx(Yi,{petRef:r,...O,...$,...V,...L});case "document":return jsx(Gi,{petRef:r,...O,...$,...V,...L});case "contributions":return jsx(kd,{petRef:r,docId:v.docId,...O,...L});case "clinicPicker":return jsx(ci,{petRef:r,...O,...n?{controller:n}:{},...o?{recordsController:o}:{},...L});case "clinicBatch":return jsx(fi,{petRef:r,petName:t??"",ownerName:a??"",...A?{onClose:A}:{},onCreated:()=>y({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},...L});case "consent":return jsx(Ei,{petRef:r,clinic:v.clinic,...O,...a!==void 0?{ownerName:a}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},...L});case "upload":return jsx(ra,{petRef:r,...O,...o?{controller:o}:{},...V,...L});default:return at(v)}}i(Md,"EverfurRecordsFlow");var yy=Md;var Lr=Object.freeze({title:"Medical records",lead:"Follow your records requests and add records you already have.",viewRecord:"Visits & records",viewTimeline:"Timeline",viewLabs:"Labs & bloodwork",viewScreenings:"Screenings",requestsFor:i(e=>`Requests for ${we(e)}`,"requestsFor"),uploadPromptTitle:i(e=>`Do you already have ${we(e)}'s records?`,"uploadPromptTitle"),uploadPromptBody:"Upload PDF records you already have, up to 25 MB each. You can pick several at once. We'll read them and add the results to your records.",uploadAction:"Upload records I already have",uploadStarting:"Starting upload\u2026",noPet:"Add your pet in Chat before starting a records request.",askA11y:i(e=>`Ask Everfur about ${we(e)}'s medical records`,"askA11y")});function $d(e){return `I'm looking at ${e?.trim()||"my pet"}'s medical records. What do these records tell me about their health and what should I keep on top of?`}i($d,"buildRecordsPageAskPrompt");var mo=2;function Ud(e){return typeof e!="number"||!Number.isInteger(e)?mo:e<1?1:e>6?6:e}i(Ud,"headingLevel");function aa(e){return e>=6?6:e+1}i(aa,"nextHeadingLevel");function sa(e){return `h${String(e)}`}i(sa,"headingTag");var by=aa(mo);createContext(by);var vy=1248,Cy=Object.freeze({height:"auto"}),fo=Object.freeze({overflowY:"visible",flex:"0 0 auto"});function Ey(e){let{style:r,className:t,renderPending:o,...n}=Te(e,["onNavigate","onBack","onAsk"]),{userRef:l}=Z(),{styles:a}=G();return jsx(De,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,$e),children:jsxs("div",{className:t,style:{...a.root,...Cy,...r},"data-testid":"everfur-records-page",children:[l===null?jsx("div",{style:{...a.body,...fo},children:jsx(er,{label:W.sessionRequired,glyph:"empty"})}):jsx(xy,{...n}),jsx(Ie,{})]})})}i(Ey,"EverfurRecordsPage");function xy({petRef:e,petName:r,controller:t,consentVersion:o,onNavigate:n,onAsk:l,headingLevel:a}){let{theme:d,styles:s}=G(),c=Ud(a??mo),u=sa(c),p=sa(aa(c)),f=`${useId()}-requests-heading`,g=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),b=Ke(g),m=we(r),C=et(o,b.consent),R=i(()=>{let h=Hr(o,b.consent);h.length!==0&&b.grantConsent(h,`records-consent-${Date.now().toString(36)}`);},"onGrant"),x={boxSizing:"border-box",width:"100%",maxWidth:vy,margin:"0 auto",display:"flex",flexDirection:"column",gap:d.space.lg+d.space.xs,padding:`${d.space.lg}px ${d.space.lg}px ${d.space.xxl}px`};if(b.status==="loading")return jsx("div",{style:{...s.body,...fo},children:jsx("div",{style:x,children:jsx(Mt,{testID:"everfur-records-page-loading"})})});if(b.status==="error"){let h=Vr(b,C),E=h.kind==="error"||h.kind==="pet_not_found"?jsx(Ue,{variant:Ze(h.error),message:h.error.displayMessage,onAction:h.error.retryable?()=>b.refresh():void 0,testID:"everfur-records-page-error"}):yt(b,R,C);return jsx("div",{style:{...s.body,...fo},children:jsx("div",{style:x,children:E})})}let y=b.requests,v=y.length>0;return jsx("div",{style:{...s.body,...fo},children:jsxs("div",{style:x,"data-testid":"everfur-records-page-content",children:[jsxs("header",{style:{...s.creamCard,gap:d.space.md,padding:`${d.space.lg+d.space.xs}px ${d.space.lg+d.space.md}px`},"data-testid":"everfur-records-page-header",children:[jsx(u,{style:{...s.headerTitle,whiteSpace:"normal",overflow:"visible"},children:Lr.title}),jsx("p",{style:s.bodyText,children:Lr.lead}),n?jsxs("nav",{style:{display:"flex",flexWrap:"wrap",columnGap:d.space.lg,rowGap:d.space.xs},"data-testid":"everfur-records-page-links",children:[jsx(Bd,{label:Lr.viewRecord,onClick:()=>n({name:"record"}),testID:"everfur-records-page-link-record"}),jsx(Bd,{label:Lr.viewTimeline,onClick:()=>n({name:"timeline"}),testID:"everfur-records-page-link-timeline"})]}):null,l?jsx(Y,{label:Lr.askA11y(r),kind:"ask",ariaLabel:Lr.askA11y(r),onClick:()=>l($d(r),{type:"marker_summary",id:e}),testID:"everfur-records-page-ask"}):null]}),jsxs("section",{"aria-labelledby":f,style:s.section,"data-testid":"everfur-records-page-requests",children:[jsxs("div",{style:s.sectionHeader,children:[jsx(p,{id:f,style:{...s.sectionTitle,color:d.color.brand},children:Lr.requestsFor(r)}),v?jsx("span",{style:s.sectionCount,"data-testid":"everfur-records-page-requests-count",children:y.length}):null]}),v?jsx("ul",{style:{...s.plainList,gap:d.space.md},children:y.map(h=>jsxs("li",{style:s.creamCard,children:[jsx("span",{style:{...s.rowTitle,fontSize:d.type.size.subtitle},children:h.clinicName?.trim()||m}),jsx(Gt,{request:h}),Rn(h)?jsx(Cn,{requestId:h.id}):null]},h.id))}):jsxs("div",{style:s.creamCard,"data-testid":"everfur-records-page-upload-prompt",children:[jsx("span",{style:{...s.rowTitle,fontSize:d.type.size.subtitle},children:Lr.uploadPromptTitle(r)}),jsx("p",{style:s.bodyText,children:Lr.uploadPromptBody}),n?jsx(Y,{label:Lr.uploadAction,onClick:()=>n({name:"upload"}),testID:"everfur-records-page-upload"}):null]})]})]})})}i(xy,"RecordsPageBody");function Bd({label:e,onClick:r,testID:t}){let{theme:o,styles:n}=G();return jsx("button",{type:"button",onClick:r,style:{...n.pill,...n.pillLink,minHeight:44,padding:0,fontSize:o.type.size.bodyTight,textDecoration:"underline",textUnderlineOffset:4},"data-testid":t,children:e})}i(Bd,"PageLink");function Sy(e){let{userRef:r,scopeEpoch:t}=Z();return jsx(De,{capability:"recordsClinic",...Oe(e.onClose,K.cancel),children:r===null?jsx("p",{role:"alert",children:W.sessionRequired}):jsx(wy,{...Te(e,["onClose","onCreated"])},JSON.stringify([r,t,e.petRef,e.petName]))})}i(Sy,"EverfurClinicRequest");function wy(e){let r=_r(),t=e.controller??r,o=ue(),n={current:null},l=St(()=>n.current?.invalidate()),a=Qs(e,t,e.onCaptureSignature??(async u=>l.signed?l.register(t,u.signal):null));n.current=a;let d={minHeight:44,padding:o.space.sm,border:`1px solid ${o.color.borderHairlineGreen}`,borderRadius:o.radius.sm,background:o.color.surface,color:o.color.text.primary,font:"inherit"},s={...d,cursor:"pointer"},c=i(()=>{a.busy||l.clear();},"clear");return jsxs("section",{className:e.className,"aria-label":K.title,style:{background:o.color.surface,color:o.color.text.primary,padding:o.space.lg,borderRadius:o.radius.lg,minHeight:120,minWidth:0,overflowWrap:"anywhere",...e.style},children:[jsx("h2",{style:{margin:0,fontSize:o.type.size.heading},children:K.title}),jsx("p",{style:{margin:`${o.space.sm}px 0 ${o.space.lg}px`},children:e.petName}),a.created?jsx("p",{role:"status",children:a.created.statusLabel||W.records}):jsxs("div",{style:{display:"grid",gap:o.space.md},children:[jsxs("label",{children:[K.ownerName,jsx("input",{style:{...d,display:"block",width:"100%",boxSizing:"border-box"},maxLength:200,value:a.ownerName,disabled:a.busy,autoComplete:"name",onChange:u=>{c(),a.setOwnerName(u.target.value);}})]}),jsxs("label",{children:[K.clinic,jsx("input",{style:{...d,display:"block",width:"100%",boxSizing:"border-box"},placeholder:K.placeholder,maxLength:200,value:a.query,disabled:a.busy,autoComplete:"off",onChange:u=>{c(),a.setQuery(u.target.value);}})]}),jsx("button",{type:"button",style:s,disabled:a.busy||a.searching||a.query.trim().length<2,onClick:()=>{a.search();},children:K.search}),a.searching&&jsx("p",{role:"status",children:W.loading}),a.recent.length>0&&jsx("h3",{style:{margin:`${o.space.sm}px 0 0`,fontSize:o.type.size.subtitle},"data-testid":"records-clinic-recent-label",children:K.recentlyUsed}),a.recent.map(u=>jsxs("button",{type:"button",style:s,disabled:a.busy,onClick:()=>{c(),a.selectClinic(u);},children:[u.name,u.address?`, ${u.address}`:"",u.phone?`, ${u.phone}`:""]},`recent-${u.id}`)),a.clinics.map(u=>jsxs("button",{type:"button",style:s,disabled:a.busy,onClick:()=>{c(),a.selectClinic(u);},children:[u.name,u.address?`, ${u.address}`:"",u.phone?`, ${u.phone}`:""]},u.id)),a.needsEmail&&jsxs("label",{children:[K.email,jsx("input",{style:{...d,display:"block",width:"100%",boxSizing:"border-box"},type:"email",placeholder:K.emailPlaceholder,maxLength:320,autoComplete:"off",value:a.email,disabled:a.busy,onChange:u=>{c(),a.setEmail(u.target.value);}})]}),jsx("h3",{style:{margin:`${o.space.sm}px 0 0`,fontSize:o.type.size.subtitle},children:K.scopeHeading}),a.copy?jsx("p",{style:{whiteSpace:"pre-wrap",margin:0},children:a.query.trim()&&a.ownerName.trim()?a.scope??z("internalError").displayMessage:W.consentRequired}):!a.error&&jsx("p",{role:"status",children:W.loading}),!e.onCaptureSignature&&jsx(wt,{pad:l,disabled:a.busy}),a.error&&jsx("p",{role:"alert",children:a.error.displayMessage}),!a.copy&&a.error&&jsx("button",{type:"button",style:s,onClick:a.retryCopy,children:W.retry}),jsx("button",{type:"button",style:{...s,background:o.color.primary,color:o.color.onPrimary,opacity:a.busy||!a.ready||!e.onCaptureSignature&&!l.signed?.5:1},disabled:a.busy||!a.ready||!e.onCaptureSignature&&!l.signed,onClick:()=>{a.submit();},children:a.busy?K.sending:K.send})]}),e.onClose&&jsx("button",{type:"button",style:s,disabled:a.busy,onClick:e.onClose,children:K.cancel}),jsx(Ie,{})]})}i(wy,"ClinicRequestBody");var ky="file",_y="document.pdf",Py="records upload: the file handle carries no bytes",jd="records upload failed";function Ty(e={}){let r=e.xhr??(()=>new XMLHttpRequest);return Object.freeze({postMultipart(t,o,n){return new Promise((l,a)=>{let d=o.blob;if(d===void 0){a(new Error(Py));return}let{signal:s,onProgress:c}=n;if(s?.aborted===true){a(new Error(jd));return}let u=new FormData;for(let[m,C]of Object.entries(t.upload_fields))u.append(m,C);u.append(ky,d,_y);let p=r(),f=false,g=i(m=>{f||(f=true,s?.removeEventListener("abort",b),m?l():a(new Error(jd)));},"settle"),b=i(()=>{p.abort(),g(false);},"onAbort");p.open("POST",t.upload_url,true),p.withCredentials=false,c&&(p.upload.onprogress=m=>{!m.lengthComputable||m.total<=0||c(Math.min(1,Math.max(0,m.loaded/m.total)));}),p.onload=()=>g(p.status>=200&&p.status<300),p.onerror=()=>g(false),p.onabort=()=>g(false),p.ontimeout=()=>g(false),s?.addEventListener("abort",b,{once:true}),p.send(u);})}})}i(Ty,"createWebRecordsUploadTransport");
4
+ export{ci as EverfurClinicPicker,Sy as EverfurClinicRequest,fi as EverfurClinicRequestBatch,Yi as EverfurRecordDetail,Gi as EverfurRecordDocument,yy as EverfurRecords,Ei as EverfurRecordsConsent,$i as EverfurRecordsDashboard,Md as EverfurRecordsFlow,Ey as EverfurRecordsPage,oa as EverfurRecordsRequest,ra as EverfurRecordsUpload,At as RECORDS_CLINIC_BATCH_MAX,no as RECORDS_DOCUMENT_ACCEPT,ka as RECORDS_TERMINAL,hn as REQUEST_TIMELINE_TITLES,Cn as RequestDocumentsList,wt as SignatureCanvas,Ti as applyFactOverlay,zi as buildRequestTimeline,Ty as createWebRecordsUploadTransport,An as currentRecordsScreen,zo as deriveRecordsDashboardState,oo as fileToHandle,On as initialRecordsNav,Di as isFactEditable,dd as isPdfBlob,Ot as isTerminalStatus,Ni as isUploadableHandle,zm as pickDocument,Nn as pickPetRecordsRequest,qn as popRecordsNav,Ao as pushRecordsNav,ot as recordsDenialReasonOf,Fo as recordsNavReducer,qo as replaceRecordsNav,Ki as requestDocumentRows,No as resetRecordsNav,Yn as selectClinicCall,Mo as selectDashboardView,mn as selectPrimaryLabel,fm as selectRequestList,Gn as selectRequestTitle,Ga as transitionRecordsNav,Ke as useEverfurRecords,_r as useEverfurRecordsClinic,Ho as useEverfurRecordsClinicBatch,Ii as useRecordFactEdit,Hi as useRecordPdfLink,Bi as useRecordShares,vi as useRecordsMarkers,Xi as useRequestDocuments,St as useSignatureCanvas};